2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * The Original Code is Copyright (C) 2005 Blender Foundation.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): none yet.
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/DerivedMesh.c
36 #include "MEM_guardedalloc.h"
38 #include "DNA_cloth_types.h"
39 #include "DNA_key_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_armature_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_scene_types.h" // N_T
45 #include "BLI_blenlib.h"
46 #include "BLI_editVert.h"
48 #include "BLI_memarena.h"
49 #include "BLI_array.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_linklist.h"
54 #include "BKE_cdderivedmesh.h"
55 #include "BKE_displist.h"
57 #include "BKE_modifier.h"
59 #include "BKE_object.h"
60 #include "BKE_paint.h"
61 #include "BKE_texture.h"
62 #include "BKE_multires.h"
63 #include "BKE_armature.h"
64 #include "BKE_particle.h"
65 #include "BKE_tessmesh.h"
66 #include "BKE_bvhutils.h"
67 #include "BKE_deform.h"
69 #ifdef WITH_GAMEENGINE
70 #include "BKE_navmesh_conversion.h"
71 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
74 #include "BLO_sys_types.h" // for intptr_t support
78 #include "GPU_buffers.h"
80 #include "GPU_extensions.h"
81 #include "GPU_material.h"
83 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
85 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
86 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
88 ///////////////////////////////////
89 ///////////////////////////////////
91 static MVert *dm_getVertArray(DerivedMesh *dm)
93 MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
96 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
98 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
99 dm->copyVertArray(dm, mvert);
105 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
107 MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
110 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
111 dm->getNumEdges(dm));
112 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
113 dm->copyEdgeArray(dm, medge);
119 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
121 MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
124 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
125 dm->getNumTessFaces(dm));
126 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
127 dm->copyTessFaceArray(dm, mface);
133 static MLoop *dm_getLoopArray(DerivedMesh *dm)
135 MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
138 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
139 dm->getNumLoops(dm));
140 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
141 dm->copyLoopArray(dm, mloop);
147 static MPoly *dm_getPolyArray(DerivedMesh *dm)
149 MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
152 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
153 dm->getNumPolys(dm));
154 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
155 dm->copyPolyArray(dm, mpoly);
161 static MVert *dm_dupVertArray(DerivedMesh *dm)
163 MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
164 "dm_dupVertArray tmp");
166 if(tmp) dm->copyVertArray(dm, tmp);
171 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
173 MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
174 "dm_dupEdgeArray tmp");
176 if(tmp) dm->copyEdgeArray(dm, tmp);
181 static MFace *dm_dupFaceArray(DerivedMesh *dm)
183 MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
184 "dm_dupFaceArray tmp");
186 if(tmp) dm->copyTessFaceArray(dm, tmp);
191 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
193 MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumLoops(dm),
194 "dm_dupLoopArray tmp");
196 if(tmp) dm->copyLoopArray(dm, tmp);
201 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
203 MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumPolys(dm),
204 "dm_dupPolyArray tmp");
206 if(tmp) dm->copyPolyArray(dm, tmp);
211 static CustomData *dm_getVertCData(DerivedMesh *dm)
213 return &dm->vertData;
216 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
218 return &dm->edgeData;
221 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
223 return &dm->faceData;
226 static CustomData *dm_getLoopCData(DerivedMesh *dm)
228 return &dm->loopData;
231 static CustomData *dm_getPolyCData(DerivedMesh *dm)
233 return &dm->polyData;
236 void DM_init_funcs(DerivedMesh *dm)
238 /* default function implementations */
239 dm->getVertArray = dm_getVertArray;
240 dm->getEdgeArray = dm_getEdgeArray;
241 dm->getTessFaceArray = dm_getTessFaceArray;
242 dm->getLoopArray = dm_getLoopArray;
243 dm->getPolyArray = dm_getPolyArray;
244 dm->dupVertArray = dm_dupVertArray;
245 dm->dupEdgeArray = dm_dupEdgeArray;
246 dm->dupTessFaceArray = dm_dupFaceArray;
247 dm->dupLoopArray = dm_dupLoopArray;
248 dm->dupPolyArray = dm_dupPolyArray;
250 dm->getVertDataLayout = dm_getVertCData;
251 dm->getEdgeDataLayout = dm_getEdgeCData;
252 dm->getTessFaceDataLayout = dm_getTessFaceCData;
253 dm->getLoopDataLayout = dm_getLoopCData;
254 dm->getPolyDataLayout = dm_getPolyCData;
256 dm->getVertData = DM_get_vert_data;
257 dm->getEdgeData = DM_get_edge_data;
258 dm->getTessFaceData = DM_get_tessface_data;
259 dm->getVertDataArray = DM_get_vert_data_layer;
260 dm->getEdgeDataArray = DM_get_edge_data_layer;
261 dm->getTessFaceDataArray = DM_get_tessface_data_layer;
263 bvhcache_init(&dm->bvhCache);
266 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
267 int numTessFaces, int numLoops, int numPolys)
270 dm->numVertData = numVerts;
271 dm->numEdgeData = numEdges;
272 dm->numTessFaceData = numTessFaces;
273 dm->numLoopData = numLoops;
274 dm->numPolyData = numPolys;
279 dm->auto_bump_scale = -1.0f;
282 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
283 int numVerts, int numEdges, int numTessFaces,
284 int numLoops, int numPolys)
286 CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
287 CD_CALLOC, numVerts);
288 CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
289 CD_CALLOC, numEdges);
290 CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
291 CD_CALLOC, numTessFaces);
292 CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
293 CD_CALLOC, numLoops);
294 CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
295 CD_CALLOC, numPolys);
298 dm->numVertData = numVerts;
299 dm->numEdgeData = numEdges;
300 dm->numTessFaceData = numTessFaces;
301 dm->numLoopData = numLoops;
302 dm->numPolyData = numPolys;
309 int DM_release(DerivedMesh *dm)
312 bvhcache_free(&dm->bvhCache);
313 GPU_drawobject_free( dm );
314 CustomData_free(&dm->vertData, dm->numVertData);
315 CustomData_free(&dm->edgeData, dm->numEdgeData);
316 CustomData_free(&dm->faceData, dm->numTessFaceData);
317 CustomData_free(&dm->loopData, dm->numLoopData);
318 CustomData_free(&dm->polyData, dm->numPolyData);
323 CustomData_free_temporary(&dm->vertData, dm->numVertData);
324 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
325 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
326 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
327 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
333 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
335 CustomData_free(&target->loopData, source->numLoopData);
336 CustomData_free(&target->polyData, source->numPolyData);
338 CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
339 CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
341 target->numLoopData = source->numLoopData;
342 target->numPolyData = source->numPolyData;
344 if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
348 mloop = source->dupLoopArray(source);
349 mpoly = source->dupPolyArray(source);
350 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
351 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
355 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
357 /* dm might depend on me, so we need to do everything with a local copy */
359 int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
362 memset(&tmp.vdata, 0, sizeof(tmp.vdata));
363 memset(&tmp.edata, 0, sizeof(tmp.edata));
364 memset(&tmp.fdata, 0, sizeof(tmp.fdata));
365 memset(&tmp.ldata, 0, sizeof(tmp.ldata));
366 memset(&tmp.pdata, 0, sizeof(tmp.pdata));
368 totvert = tmp.totvert = dm->getNumVerts(dm);
369 totedge = tmp.totedge = dm->getNumEdges(dm);
370 totloop = tmp.totloop = dm->getNumLoops(dm);
371 totpoly = tmp.totpoly = dm->getNumPolys(dm);
373 CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
374 CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
375 CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
376 CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
378 if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
383 for (kb=me->key->block.first; kb; kb=kb->next, i++) {
384 if (i == ob->shapenr-1) {
391 printf("%s: error - could not find active shapekey %d!\n",
392 __func__, ob->shapenr-1);
397 /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
401 shapekey_layers_to_keyblocks(dm, me, i);
405 /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
406 we set them here in case they are missing */
407 if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
408 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
409 if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
410 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
411 if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
412 tmp.mloop = dm->dupLoopArray(dm);
413 tmp.mpoly = dm->dupPolyArray(dm);
415 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
416 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
419 /* object had got displacement layer, should copy this layer to save sculpted data */
420 /* NOTE: maybe some other layers should be copied? nazgul */
421 if(CustomData_has_layer(&me->ldata, CD_MDISPS)) {
422 if (totloop == me->totloop) {
423 MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
424 CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
428 /* yes, must be before _and_ after tesselate */
429 mesh_update_customdata_pointers(&tmp, TRUE);
431 tmp.totface = mesh_recalcTesselation(&tmp.fdata, &tmp.ldata, &tmp.pdata, tmp.mvert, tmp.totface, tmp.totloop, tmp.totpoly);
433 mesh_update_customdata_pointers(&tmp, TRUE);
436 CustomData_free(&me->vdata, me->totvert);
437 CustomData_free(&me->edata, me->totedge);
438 CustomData_free(&me->fdata, me->totface);
439 CustomData_free(&me->ldata, me->totloop);
440 CustomData_free(&me->pdata, me->totpoly);
442 /* ok, this should now use new CD shapekey data,
443 which shouuld be fed through the modifier
445 if(tmp.totvert != me->totvert && !did_shapekeys && me->key) {
446 printf("YEEK! this should be recoded! Shape key loss!!!\n");
447 if(tmp.key) tmp.key->id.us--;
454 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
456 int a, totvert = dm->getNumVerts(dm);
460 if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
462 if(kb->data) MEM_freeN(kb->data);
463 kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
464 kb->totelem= totvert;
467 mvert=dm->getVertDataArray(dm, CD_MVERT);
469 for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
470 copy_v3_v3(fp, mvert->co);
474 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
476 CustomData_set_only_copy(&dm->vertData, mask);
477 CustomData_set_only_copy(&dm->edgeData, mask);
478 CustomData_set_only_copy(&dm->faceData, mask);
481 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
483 CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
486 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
488 CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
491 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
493 CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
496 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
498 CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
501 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
503 CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
506 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
508 return CustomData_get(&dm->vertData, index, type);
511 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
513 return CustomData_get(&dm->edgeData, index, type);
516 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
518 return CustomData_get(&dm->faceData, index, type);
521 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
524 return dm->getVertArray(dm);
526 return CustomData_get_layer(&dm->vertData, type);
529 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
532 return dm->getEdgeArray(dm);
534 return CustomData_get_layer(&dm->edgeData, type);
537 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
539 if (type == CD_MFACE)
540 return dm->getTessFaceArray(dm);
542 return CustomData_get_layer(&dm->faceData, type);
545 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
547 return CustomData_get_layer(&dm->polyData, type);
550 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
552 CustomData_set(&dm->vertData, index, type, data);
555 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
557 CustomData_set(&dm->edgeData, index, type, data);
560 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
562 CustomData_set(&dm->faceData, index, type, data);
565 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
566 int source_index, int dest_index, int count)
568 CustomData_copy_data(&source->vertData, &dest->vertData,
569 source_index, dest_index, count);
572 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
573 int source_index, int dest_index, int count)
575 CustomData_copy_data(&source->edgeData, &dest->edgeData,
576 source_index, dest_index, count);
579 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
580 int source_index, int dest_index, int count)
582 CustomData_copy_data(&source->faceData, &dest->faceData,
583 source_index, dest_index, count);
586 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
587 int source_index, int dest_index, int count)
589 CustomData_copy_data(&source->loopData, &dest->loopData,
590 source_index, dest_index, count);
593 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
594 int source_index, int dest_index, int count)
596 CustomData_copy_data(&source->polyData, &dest->polyData,
597 source_index, dest_index, count);
600 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
602 CustomData_free_elem(&dm->vertData, index, count);
605 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
607 CustomData_free_elem(&dm->edgeData, index, count);
610 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
612 CustomData_free_elem(&dm->faceData, index, count);
615 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
617 CustomData_free_elem(&dm->loopData, index, count);
620 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
622 CustomData_free_elem(&dm->polyData, index, count);
625 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
626 int *src_indices, float *weights,
627 int count, int dest_index)
629 CustomData_interp(&source->vertData, &dest->vertData, src_indices,
630 weights, NULL, count, dest_index);
633 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
635 float *weights, EdgeVertWeight *vert_weights,
636 int count, int dest_index)
638 CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
639 weights, (float*)vert_weights, count, dest_index);
642 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
644 float *weights, FaceVertWeight *vert_weights,
645 int count, int dest_index)
647 CustomData_interp(&source->faceData, &dest->faceData, src_indices,
648 weights, (float*)vert_weights, count, dest_index);
651 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
653 CustomData_swap(&dm->faceData, index, corner_indices);
656 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
658 float *weights, int count, int dest_index)
660 CustomData_interp(&source->loopData, &dest->loopData, src_indices,
661 weights, NULL, count, dest_index);
664 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
666 float *weights, int count, int dest_index)
668 CustomData_interp(&source->polyData, &dest->polyData, src_indices,
669 weights, NULL, count, dest_index);
673 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
675 DerivedMesh *dm = CDDM_from_mesh(me, ob);
681 CDDM_apply_vert_coords(dm, vertCos);
683 CDDM_calc_normals(dm);
690 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
691 ModifierData *md, int build_shapekey_layers)
694 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
699 if (!(md->mode&eModifierMode_Realtime)) return NULL;
700 if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
702 if (build_shapekey_layers && me->key && ob->shapenr <= BLI_countlist(&me->key->block)) {
703 key_to_mesh(BLI_findlink(&me->key->block, ob->shapenr-1), me);
706 if (mti->type==eModifierTypeType_OnlyDeform) {
708 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
710 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
711 dm = mesh_create_derived(me, ob, deformedVerts);
713 if (build_shapekey_layers)
714 add_shapekey_layers(dm, me, ob);
716 MEM_freeN(deformedVerts);
718 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
720 if (build_shapekey_layers)
721 add_shapekey_layers(tdm, me, ob);
723 dm = mti->applyModifier(md, ob, tdm, 0, 0);
725 if(tdm != dm) tdm->release(tdm);
731 static float *get_editbmesh_orco_verts(BMEditMesh *em)
738 /* these may not really be the orco's, but it's only for preview.
739 * could be solver better once, but isn't simple */
741 totvert= em->bm->totvert;
743 orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
745 eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
746 for (a=0; eve; eve=BMIter_Step(&iter), a+=3) {
747 copy_v3_v3(orco+a, eve->co);
753 /* orco custom data layer */
754 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
758 if(layer == CD_ORCO) {
759 /* get original coordinates */
763 return (float(*)[3])get_editbmesh_orco_verts(em);
765 return (float(*)[3])get_mesh_orco_verts(ob);
767 else if(layer == CD_CLOTH_ORCO) {
768 /* apply shape key for cloth, this should really be solved
769 by a more flexible customdata system, but not simple */
771 ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
772 KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
784 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
790 if(em) dm= CDDM_from_BMEditMesh(em, me, 0);
791 else dm= CDDM_from_mesh(me, ob);
793 orco= get_orco_coords_dm(ob, em, layer, &free);
796 CDDM_apply_vert_coords(dm, orco);
797 if(free) MEM_freeN(orco);
800 CDDM_calc_normals(dm);
805 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
806 DerivedMesh *orcodm, int layer)
808 float (*orco)[3], (*layerorco)[3];
811 totvert= dm->getNumVerts(dm);
814 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
817 if(orcodm->getNumVerts(orcodm) == totvert)
818 orcodm->getVertCos(orcodm, orco);
820 dm->getVertCos(dm, orco);
823 orco= get_orco_coords_dm(ob, em, layer, &free);
827 transform_mesh_orco_verts(ob->data, orco, totvert, 0);
829 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
830 DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
831 layerorco = DM_get_vert_data_layer(dm, layer);
834 memcpy(layerorco, orco, sizeof(float)*3*totvert);
835 if(free) MEM_freeN(orco);
839 /* weight paint colors */
841 /* Something of a hack, at the moment deal with weightpaint
842 * by tucking into colors during modifier eval, only in
843 * wpaint mode. Works ok but need to make sure recalc
844 * happens on enter/exit wpaint.
847 void weight_to_rgb(float r_rgb[3], const float weight)
849 const float blend= ((weight/2.0f)+0.5f);
851 if (weight<=0.25f){ // blue->cyan
853 r_rgb[1]= blend*weight*4.0f;
856 else if (weight<=0.50f){ // cyan->green
859 r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
861 else if (weight <= 0.75f){ // green->yellow
862 r_rgb[0]= blend * ((weight-0.50f)*4.0f);
866 else if (weight <= 1.0f){ // yellow->red
868 r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
872 /* exceptional value, unclamped or nan,
873 * avoid uninitialized memory use */
880 /* draw_flag's for calc_weightpaint_vert_color */
882 CALC_WP_MULTIPAINT= (1<<0),
883 CALC_WP_AUTO_NORMALIZE= (1<<1)
886 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
890 if(coba) do_colorband(coba, input, colf);
891 else weight_to_rgb(colf, input);
893 r_col[3] = (unsigned char)(colf[0] * 255.0f);
894 r_col[2] = (unsigned char)(colf[1] * 255.0f);
895 r_col[1] = (unsigned char)(colf[2] * 255.0f);
900 static void calc_weightpaint_vert_color(
901 unsigned char r_col[4],
902 MDeformVert *dv, ColorBand *coba,
903 const int defbase_tot, const int defbase_act,
904 const char *dg_flags,
905 const int selected, const int draw_flag)
909 int make_black= FALSE;
911 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
912 int was_a_nonzero= FALSE;
915 MDeformWeight *dw= dv->dw;
916 for (i = dv->totweight; i != 0; i--, dw++) {
917 /* in multipaint, get the average if auto normalize is inactive
918 * get the sum if it is active */
919 if (dw->def_nr < defbase_tot) {
920 if (dg_flags[dw->def_nr]) {
929 /* make it black if the selected groups have no weight on a vertex */
930 if (was_a_nonzero == FALSE) {
933 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
934 input /= selected; /* get the average */
938 /* default, non tricky behavior */
939 input= defvert_find_weight(dv, defbase_act);
942 if (make_black) { /* TODO, theme color */
949 CLAMP(input, 0.0f, 1.0f);
950 weightpaint_color(r_col, coba, input);
954 static ColorBand *stored_cb= NULL;
956 void vDM_ColorBand_store(ColorBand *coba)
961 /* return an array of vertex weight colors, caller must free.
963 * note that we could save some memory and allocate RGB only but then we'd need to
964 * re-arrange the colors when copying to the face since MCol has odd ordering,
965 * so leave this as is - campbell */
966 static unsigned char *calc_weightpaint_vert_array(Object *ob, int const draw_flag, ColorBand *coba)
969 unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * me->totvert * 4, "weightmap_v");
972 unsigned char *wc = wtcol_v;
973 MDeformVert *dv= me->dvert;
976 /* varisbles for multipaint */
977 const int defbase_tot = BLI_countlist(&ob->defbase);
978 const int defbase_act = ob->actdef-1;
979 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
980 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
981 /* const int unselected = defbase_tot - selected; */ /* UNUSED */
983 for (i = me->totvert; i != 0; i--, wc += 4, dv++) {
984 calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
991 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
992 fill_vn_i((int *)wtcol_v, me->totvert, col_i);
998 static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
1000 ColorBand *coba= stored_cb; /* warning, not a local var */
1001 unsigned char *wtcol_v = calc_weightpaint_vert_array(ob, draw_flag, coba);
1002 unsigned char *wtcol_f;
1003 unsigned char(*wtcol_l)[4] = NULL;
1004 BLI_array_declare(wtcol_l);
1005 MFace *mf = dm->getTessFaceArray(dm);
1006 MLoop *mloop = dm->getLoopArray(dm), *ml;
1007 MPoly *mp = dm->getPolyArray(dm);
1008 int i, j, totface=dm->getNumTessFaces(dm), totloop;
1009 int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
1011 wtcol_f = MEM_mallocN(sizeof (unsigned char) * totface*4*4, "weightmap_f");
1013 /*first add colors to the tesselation faces*/
1014 for (i=0; i<totface; i++, mf++) {
1015 /*origindex being NULL means we're operating on original mesh data*/
1016 unsigned int fidx= mf->v4 ? 3:2;
1018 copy_v4_v4_char((char *)&wtcol_f[(4 * i + fidx) * 4],
1019 (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
1023 CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol_f, totface);
1025 /*now add to loops, so the data can be passed through the modifier stack*/
1027 for (i=0; i<dm->numPolyData; i++, mp++) {
1028 ml = mloop + mp->loopstart;
1030 for (j=0; j<mp->totloop; j++, ml++, totloop++) {
1031 BLI_array_growone(wtcol_l);
1032 copy_v4_v4_char((char *)&wtcol_l[totloop],
1033 (char *)&wtcol_v[4 * (origIndex ? origIndex[ml->v] : ml->v)]);
1039 CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1043 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1051 tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1052 for (i=0; i<tot; i++) {
1053 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1054 float (*cos)[3], (*kbcos)[3];
1056 for (kb=me->key->block.first; kb; kb=kb->next) {
1057 if (kb->uid == layer->uid)
1062 kb = add_keyblock(me->key, layer->name);
1063 kb->uid = layer->uid;
1067 MEM_freeN(kb->data);
1069 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1070 kb->totelem = dm->numVertData;
1072 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1073 if (kb->uid == actshape_uid) {
1074 MVert *mvert = dm->getVertArray(dm);
1076 for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1077 copy_v3_v3(*kbcos, mvert->co);
1080 for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1081 copy_v3_v3(*kbcos, *cos);
1086 for (kb=me->key->block.first; kb; kb=kb->next) {
1087 if (kb->totelem != dm->numVertData) {
1089 MEM_freeN(kb->data);
1091 kb->totelem = dm->numVertData;
1092 kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1093 fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1098 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1107 if (dm->numVertData != me->totvert) {
1108 printf("error in add_shapekey_layers: dm isn't the same size as me\n");
1112 for (a=0, kb=key->block.first; kb; kb=kb->next, a++) {
1113 float (*cos)[3] = CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_CALLOC, NULL, dm->numVertData, kb->name);
1114 int ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, a);
1116 dm->vertData.layers[ci].uid = kb->uid;
1117 if (kb->totelem != dm->numVertData) {
1118 printf("error in add_shapekey_layers: totelem and totvert don't match");
1122 for (b=0; b<kb->totelem; b++, cos++) {
1123 copy_v3_v3((float *)cos, ((float*)kb->data)+b*3);
1128 /* new value for useDeform -1 (hack for the gameengine):
1129 * - apply only the modifier stack of the object, skipping the virtual modifiers,
1130 * - don't apply the key
1131 * - apply deform modifiers and input vertexco
1133 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1134 DerivedMesh **deform_r, DerivedMesh **final_r,
1135 int useRenderParams, int useDeform,
1136 int needMapping, CustomDataMask dataMask,
1137 int index, int useCache, int build_shapekey_layers)
1139 Mesh *me = ob->data;
1140 ModifierData *firstmd, *md;
1141 LinkNode *datamasks, *curr;
1142 CustomDataMask mask, nextmask, append_mask = 0;
1143 float (*deformedVerts)[3] = NULL;
1144 DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1145 int numVerts = me->totvert;
1147 int isPrevDeform= FALSE;
1148 int skipVirtualArmature = (useDeform < 0);
1149 MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1150 int has_multires = mmd != NULL, multires_applied = 0;
1151 int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1153 int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1154 (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1156 if(mmd && !mmd->sculptlvl)
1159 if(!skipVirtualArmature) {
1160 firstmd = modifiers_getVirtualModifierList(ob);
1163 /* game engine exception */
1164 firstmd = ob->modifiers.first;
1165 if(firstmd && firstmd->type == eModifierType_Armature)
1166 firstmd = firstmd->next;
1171 modifiers_clearErrors(ob);
1173 if(useRenderParams) required_mode = eModifierMode_Render;
1174 else required_mode = eModifierMode_Realtime;
1176 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1179 if(deform_r) *deform_r = NULL;
1184 deformedVerts = inputVertexCos;
1186 /* Apply all leading deforming modifiers */
1187 for(;md; md = md->next, curr = curr->next) {
1188 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1192 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1193 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1195 if(mti->type == eModifierTypeType_OnlyDeform) {
1197 deformedVerts = mesh_getVertexCos(me, &numVerts);
1199 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1204 /* grab modifiers until index i */
1205 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1209 /* Result of all leading deforming modifiers is cached for
1210 * places that wish to use the original mesh but with deformed
1211 * coordinates (vpaint, etc.)
1214 *deform_r = CDDM_from_mesh(me, ob);
1216 if (build_shapekey_layers)
1217 add_shapekey_layers(dm, me, ob);
1220 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1221 CDDM_calc_normals(*deform_r);
1225 /* default behaviour for meshes */
1227 deformedVerts = inputVertexCos;
1229 deformedVerts = mesh_getVertexCos(me, &numVerts);
1233 /* Now apply all remaining modifiers. If useDeform is off then skip
1240 for(;md; md = md->next, curr = curr->next) {
1241 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1245 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1246 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1247 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1248 modifier_setError(md, "Modifier requires original data, bad stack position.");
1251 if(sculpt_mode && (!has_multires || multires_applied)) {
1254 if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1255 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1257 unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1258 unsupported|= multires_applied;
1261 modifier_setError(md, "Not supported in sculpt mode.");
1265 if(needMapping && !modifier_supportsMapping(md)) continue;
1266 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1268 /* add an orco layer if needed by this modifier */
1269 if(mti->requiredDataMask)
1270 mask = mti->requiredDataMask(ob, md);
1274 if(dm && (mask & CD_MASK_ORCO))
1275 add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1277 /* How to apply modifier depends on (a) what we already have as
1278 * a result of previous modifiers (could be a DerivedMesh or just
1279 * deformed vertices) and (b) what type the modifier is.
1282 if(mti->type == eModifierTypeType_OnlyDeform) {
1283 /* No existing verts to deform, need to build them. */
1284 if(!deformedVerts) {
1286 /* Deforming a derived mesh, read the vertex locations
1287 * out of the mesh and deform them. Once done with this
1288 * run of deformers verts will be written back.
1290 numVerts = dm->getNumVerts(dm);
1292 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1293 dm->getVertCos(dm, deformedVerts);
1295 deformedVerts = mesh_getVertexCos(me, &numVerts);
1299 /* if this is not the last modifier in the stack then recalculate the normals
1300 * to avoid giving bogus normals to the next modifier see: [#23673] */
1301 if(dm && isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1302 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1303 if(dm && dm->type == DM_TYPE_CDDM) {
1304 CDDM_apply_vert_coords(dm, deformedVerts);
1305 CDDM_calc_normals(dm);
1309 mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1313 /* determine which data layers are needed by following modifiers */
1315 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1319 /* apply vertex coordinates or build a DerivedMesh as necessary */
1322 DerivedMesh *tdm = CDDM_copy(dm, 0);
1326 CDDM_apply_vert_coords(dm, deformedVerts);
1327 CDDM_calc_normals(dm);
1330 dm = CDDM_from_mesh(me, ob);
1332 if (build_shapekey_layers)
1333 add_shapekey_layers(dm, me, ob);
1336 CDDM_apply_vert_coords(dm, deformedVerts);
1337 CDDM_calc_normals(dm);
1340 /* Constructive modifiers need to have an origindex
1341 * otherwise they wont have anywhere to copy the data from.
1343 * Also create ORIGINDEX data if any of the following modifiers
1344 * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1345 * data by using generic DM_copy_vert_data() functions.
1347 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1349 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1350 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1351 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1353 range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1354 range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1355 range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1358 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1359 add_weight_mcol_dm(ob, dm, draw_flag);
1364 /* set the DerivedMesh to only copy needed data */
1365 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1366 /* needMapping check here fixes bug [#28112], otherwise its
1367 * possible that it wont be copied */
1368 mask |= append_mask;
1369 DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1371 /* add cloth rest shape key if need */
1372 if(mask & CD_MASK_CLOTH_ORCO)
1373 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1375 /* add an origspace layer if needed */
1376 if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
1377 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1378 DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1380 ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1383 /* if the modifier returned a new dm, release the old one */
1384 if(dm && dm != ndm) dm->release(dm);
1389 if(deformedVerts != inputVertexCos)
1390 MEM_freeN(deformedVerts);
1392 deformedVerts = NULL;
1396 /* create an orco derivedmesh in parallel */
1397 if(nextmask & CD_MASK_ORCO) {
1399 orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1401 nextmask &= ~CD_MASK_ORCO;
1402 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1403 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1406 /* if the modifier returned a new dm, release the old one */
1407 if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1412 /* create cloth orco derivedmesh in parallel */
1413 if(nextmask & CD_MASK_CLOTH_ORCO) {
1415 clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1417 nextmask &= ~CD_MASK_CLOTH_ORCO;
1418 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1419 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1422 /* if the modifier returned a new dm, release the old one */
1423 if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1428 /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1429 if (md->type == eModifierType_DynamicPaint)
1430 append_mask |= CD_MASK_WEIGHT_MCOL;
1433 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1435 /* grab modifiers until index i */
1436 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1439 if(sculpt_mode && md->type == eModifierType_Multires)
1440 multires_applied = 1;
1443 for(md=firstmd; md; md=md->next)
1444 modifier_freeTemporaryData(md);
1446 /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1447 * need to apply these back onto the DerivedMesh. If we have no
1448 * DerivedMesh then we need to build one.
1450 if(dm && deformedVerts) {
1451 finaldm = CDDM_copy(dm, 0);
1455 CDDM_apply_vert_coords(finaldm, deformedVerts);
1457 CDDM_calc_normals(finaldm);
1459 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1460 add_weight_mcol_dm(ob, finaldm, draw_flag);
1465 int recalc_normals= 0;
1467 finaldm = CDDM_from_mesh(me, ob);
1469 if(build_shapekey_layers) {
1470 add_shapekey_layers(finaldm, me, ob);
1475 CDDM_apply_vert_coords(finaldm, deformedVerts);
1480 CDDM_calc_normals(finaldm);
1482 if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
1483 add_weight_mcol_dm(ob, finaldm, draw_flag);
1486 /* add an orco layer if needed */
1487 if(dataMask & CD_MASK_ORCO) {
1488 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1490 if(deform_r && *deform_r)
1491 add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1494 #ifdef WITH_GAMEENGINE
1495 /* NavMesh - this is a hack but saves having a NavMesh modifier */
1496 if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1498 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1499 if (finaldm != tdm) {
1500 finaldm->release(finaldm);
1504 #endif /* WITH_GAMEENGINE */
1507 /* --------------------------------------------------------------------- */
1508 /* Re-tesselation is necessary to push render data (uvs, textures, colors)
1509 * from loops and polys onto the tessfaces. This may be currently be
1510 * redundantin cases where the render mode doesn't use these inputs, but
1511 * ideally eventually tesselation would happen on-demand, and this is one
1512 * of the primary places it would be needed. */
1513 finaldm->recalcTesselation(finaldm);
1514 /* if we have no modifiers applied we'lll still want the tessface normals
1515 * to be calculated from the polygon noramals,
1516 * 'CDDM_calc_normals' checks for this case - campbell */
1517 finaldm->calcNormals(finaldm);
1518 /* Need to watch this, it can cause issues, see bug [#29338] */
1519 /* take care with this block, we really need testing frameworks */
1520 /* --------------------------------------------------------------------- */
1526 orcodm->release(orcodm);
1528 clothorcodm->release(clothorcodm);
1530 if(deformedVerts && deformedVerts != inputVertexCos)
1531 MEM_freeN(deformedVerts);
1533 BLI_linklist_free(datamasks, NULL);
1536 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1538 int i, numVerts = *numVerts_r = em->bm->totvert;
1543 cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1545 eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1546 for (i=0; eve; eve=BMIter_Step(&iter), i++) {
1547 copy_v3_v3(cos[i], eve->co);
1553 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1555 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1556 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1558 if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1559 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1560 modifier_setError(md, "Modifier requires original data, bad stack position.");
1567 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1568 DerivedMesh **final_r,
1569 CustomDataMask dataMask)
1572 float (*deformedVerts)[3] = NULL;
1573 CustomDataMask mask;
1574 DerivedMesh *dm = NULL, *orcodm = NULL, *finaldm = NULL;
1575 int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1576 LinkNode *datamasks, *curr;
1577 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1579 modifiers_clearErrors(ob);
1581 if(cage_r && cageIndex == -1) {
1582 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1585 md = modifiers_getVirtualModifierList(ob);
1587 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1590 for(i = 0; md; i++, md = md->next, curr = curr->next) {
1591 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1595 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1598 /* add an orco layer if needed by this modifier */
1599 if(dm && mti->requiredDataMask) {
1600 mask = mti->requiredDataMask(ob, md);
1601 if(mask & CD_MASK_ORCO)
1602 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1605 /* How to apply modifier depends on (a) what we already have as
1606 * a result of previous modifiers (could be a DerivedMesh or just
1607 * deformed vertices) and (b) what type the modifier is.
1610 if(mti->type == eModifierTypeType_OnlyDeform) {
1611 /* No existing verts to deform, need to build them. */
1612 if(!deformedVerts) {
1614 /* Deforming a derived mesh, read the vertex locations
1615 * out of the mesh and deform them. Once done with this
1616 * run of deformers verts will be written back.
1618 numVerts = dm->getNumVerts(dm);
1620 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1621 dm->getVertCos(dm, deformedVerts);
1623 deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1627 if (mti->deformVertsEM)
1628 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1629 else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1633 /* apply vertex coordinates or build a DerivedMesh as necessary */
1636 DerivedMesh *tdm = CDDM_copy(dm, 0);
1637 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1640 CDDM_apply_vert_coords(dm, deformedVerts);
1641 CDDM_calc_normals(dm);
1642 } else if(cage_r && dm == *cage_r) {
1643 /* dm may be changed by this modifier, so we need to copy it
1645 dm = CDDM_copy(dm, 0);
1649 dm = CDDM_from_BMEditMesh(em, ob->data, 0);
1652 CDDM_apply_vert_coords(dm, deformedVerts);
1653 CDDM_calc_normals(dm);
1657 /* create an orco derivedmesh in parallel */
1658 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1659 if(mask & CD_MASK_ORCO) {
1661 orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1663 mask &= ~CD_MASK_ORCO;
1664 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1666 if (mti->applyModifierEM)
1667 ndm = mti->applyModifierEM(md, ob, em, orcodm);
1669 ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1672 /* if the modifier returned a new dm, release the old one */
1673 if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1678 /* set the DerivedMesh to only copy needed data */
1679 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1681 DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1683 if(mask & CD_MASK_ORIGSPACE)
1684 if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
1685 DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
1687 if (mti->applyModifierEM)
1688 ndm = mti->applyModifierEM(md, ob, em, dm);
1690 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1698 if (deformedVerts) {
1699 MEM_freeN(deformedVerts);
1700 deformedVerts = NULL;
1705 if(cage_r && i == cageIndex) {
1706 if(dm && deformedVerts) {
1707 *cage_r = CDDM_copy(dm, 0);
1708 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1713 getEditDerivedBMesh(em, ob,
1714 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1719 BLI_linklist_free(datamasks, NULL);
1721 /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1722 * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1723 * then we need to build one.
1725 if(dm && deformedVerts) {
1726 finaldm = CDDM_copy(dm, 0);
1728 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1730 CDDM_apply_vert_coords(*final_r, deformedVerts);
1733 } else if (!deformedVerts && cage_r && *cage_r) {
1736 finaldm = getEditDerivedBMesh(em, ob, deformedVerts);
1737 deformedVerts = NULL;
1740 finaldm->calcNormals(finaldm);
1744 /* add an orco layer if needed */
1745 if(dataMask & CD_MASK_ORCO)
1746 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1749 orcodm->release(orcodm);
1752 MEM_freeN(deformedVerts);
1755 static void clear_mesh_caches(Object *ob)
1759 /* also serves as signal to remake texspace */
1769 freedisplist(&ob->disp);
1771 if (ob->derivedFinal) {
1772 ob->derivedFinal->needsFree = 1;
1773 ob->derivedFinal->release(ob->derivedFinal);
1774 ob->derivedFinal= NULL;
1776 if (ob->derivedDeform) {
1777 ob->derivedDeform->needsFree = 1;
1778 ob->derivedDeform->release(ob->derivedDeform);
1779 ob->derivedDeform= NULL;
1783 object_sculpt_modifiers_changed(ob);
1787 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1788 int build_shapekey_layers)
1790 Object *obact = scene->basact?scene->basact->object:NULL;
1791 int editing = paint_facesel_test(ob);
1792 /* weight paint and face select need original indices because of selection buffer drawing */
1793 int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1795 clear_mesh_caches(ob);
1797 mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1798 &ob->derivedFinal, 0, 1,
1799 needMapping, dataMask, -1, 1, build_shapekey_layers);
1801 DM_set_object_boundbox (ob, ob->derivedFinal);
1803 ob->derivedFinal->needsFree = 0;
1804 ob->derivedDeform->needsFree = 0;
1805 ob->lastDataMask = dataMask;
1808 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1810 clear_mesh_caches(obedit);
1812 if (em->derivedFinal) {
1813 if (em->derivedFinal!=em->derivedCage) {
1814 em->derivedFinal->needsFree = 1;
1815 em->derivedFinal->release(em->derivedFinal);
1817 em->derivedFinal = NULL;
1819 if (em->derivedCage) {
1820 em->derivedCage->needsFree = 1;
1821 em->derivedCage->release(em->derivedCage);
1822 em->derivedCage = NULL;
1825 editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
1826 DM_set_object_boundbox (obedit, em->derivedFinal);
1828 em->lastDataMask = dataMask;
1829 em->derivedFinal->needsFree = 0;
1830 em->derivedCage->needsFree = 0;
1833 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
1834 CustomDataMask dataMask, int build_shapekey_layers)
1837 editbmesh_build_data(scene, ob, em, dataMask);
1839 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
1845 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
1847 /* if there's no derived mesh or the last data mask used doesn't include
1848 * the data we need, rebuild the derived mesh
1850 if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
1851 mesh_build_data(scene, ob, dataMask, 0);
1853 return ob->derivedFinal;
1856 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
1858 /* if there's no derived mesh or the last data mask used doesn't include
1859 * the data we need, rebuild the derived mesh
1861 if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
1862 mesh_build_data(scene, ob, dataMask, 0);
1864 return ob->derivedDeform;
1867 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
1871 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
1876 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
1880 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
1885 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
1889 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
1894 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
1895 CustomDataMask dataMask)
1899 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
1904 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
1905 CustomDataMask dataMask)
1909 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
1914 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
1915 CustomDataMask dataMask)
1919 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
1924 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
1925 float (*vertCos)[3],
1926 CustomDataMask dataMask)
1930 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
1937 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
1938 CustomDataMask dataMask)
1940 /* if there's no derived mesh or the last data mask used doesn't include
1941 * the data we need, rebuild the derived mesh
1943 if(!em->derivedCage ||
1944 (em->lastDataMask & dataMask) != dataMask)
1945 editbmesh_build_data(scene, obedit, em, dataMask);
1947 *final_r = em->derivedFinal;
1948 return em->derivedCage;
1951 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
1953 /* if there's no derived mesh or the last data mask used doesn't include
1954 * the data we need, rebuild the derived mesh
1956 if(!em->derivedCage ||
1957 (em->lastDataMask & dataMask) != dataMask)
1958 editbmesh_build_data(scene, obedit, em, dataMask);
1960 return em->derivedCage;
1963 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
1965 return getEditDerivedBMesh(em, obedit, NULL);
1969 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
1971 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
1973 float *vec = userData;
1977 /* check if we've been here before (normal should not be 0) */
1978 if(vec[3] || vec[4] || vec[5]) return;
1980 copy_v3_v3(vec, co);
1983 copy_v3_v3(vec, no_f);
1986 normal_short_to_float_v3(vec, no_s);
1990 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
1991 /* this is needed for all code using vertexgroups (no subsurf support) */
1992 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
1993 /* in use now by vertex/weight paint and particle generating */
1995 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
1999 float *vertexcosnos;
2001 /* lets prevent crashing... */
2002 if(ob->type!=OB_MESH || me->totvert==0)
2005 dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2006 vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2008 if(dm->foreachMappedVert) {
2009 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2012 float *fp= vertexcosnos;
2015 for(a=0; a< me->totvert; a++, fp+=6) {
2016 dm->getVertCo(dm, a, fp);
2017 dm->getVertNo(dm, a, fp+3);
2022 return vertexcosnos;
2025 /* ******************* GLSL ******************** */
2029 float * precomputedFaceNormals;
2030 MTFace * mtface; // texture coordinates
2031 MFace * mface; // indices
2032 MVert * mvert; // vertices & normals
2034 float (*tangent)[4]; // destination
2037 } SGLSLMeshToTangent;
2040 #include "mikktspace.h"
2042 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2044 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2045 return pMesh->numTessFaces;
2048 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2050 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2051 return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2054 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2056 //assert(vert_index>=0 && vert_index<4);
2057 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2058 const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2059 copy_v3_v3(fPos, co);
2062 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2064 //assert(vert_index>=0 && vert_index<4);
2065 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2067 if(pMesh->mtface!=NULL) {
2068 float * uv = pMesh->mtface[face_num].uv[vert_index];
2069 fUV[0]=uv[0]; fUV[1]=uv[1];
2072 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2073 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2077 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2079 //assert(vert_index>=0 && vert_index<4);
2080 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2082 const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2083 if(!smoothnormal) { // flat
2084 if(pMesh->precomputedFaceNormals) {
2085 copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2088 MFace *mf= &pMesh->mface[face_num];
2089 float *p0= pMesh->mvert[mf->v1].co;
2090 float *p1= pMesh->mvert[mf->v2].co;
2091 float *p2= pMesh->mvert[mf->v3].co;
2094 float *p3 = pMesh->mvert[mf->v4].co;
2095 normal_quad_v3(fNorm, p0, p1, p2, p3);
2098 normal_tri_v3(fNorm, p0, p1, p2);
2103 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2104 normal_short_to_float_v3(fNorm, no);
2107 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2109 //assert(vert_index>=0 && vert_index<4);
2110 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2111 float * pRes = pMesh->tangent[4*face_num+iVert];
2112 copy_v3_v3(pRes, fvTangent);
2117 void DM_add_tangent_layer(DerivedMesh *dm)
2120 MTFace *mtface, *tf;
2122 MVert *mvert, *v1, *v2, *v3, *v4;
2123 MemArena *arena= NULL;
2124 VertexTangent **vtangents= NULL;
2125 float (*orco)[3]= NULL, (*tangent)[4];
2126 float *uv1, *uv2, *uv3, *uv4, *vtang;
2127 float fno[3], tang[3], uv[4][2];
2128 int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2131 if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2134 nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2136 /* check we have all the needed layers */
2137 totvert= dm->getNumVerts(dm);
2138 totface= dm->getNumTessFaces(dm);
2140 mvert= dm->getVertArray(dm);
2141 mface= dm->getTessFaceArray(dm);
2142 mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2145 orco= dm->getVertDataArray(dm, CD_ORCO);
2150 /* create tangent layer */
2151 DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2152 tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2154 /* allocate some space */
2155 arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2156 BLI_memarena_use_calloc(arena);
2157 vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2159 // new computation method
2161 if(iCalcNewMethod != 0) {
2162 SGLSLMeshToTangent mesh2tangent= {0};
2163 SMikkTSpaceContext sContext= {0};
2164 SMikkTSpaceInterface sInterface= {0};
2166 mesh2tangent.precomputedFaceNormals = nors;
2167 mesh2tangent.mtface = mtface;
2168 mesh2tangent.mface = mface;
2169 mesh2tangent.mvert = mvert;
2170 mesh2tangent.orco = orco;
2171 mesh2tangent.tangent = tangent;
2172 mesh2tangent.numTessFaces = totface;
2174 sContext.m_pUserData = &mesh2tangent;
2175 sContext.m_pInterface = &sInterface;
2176 sInterface.m_getNumFaces = GetNumFaces;
2177 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2178 sInterface.m_getPosition = GetPosition;
2179 sInterface.m_getTexCoord = GetTextureCoordinate;
2180 sInterface.m_getNormal = GetNormal;
2181 sInterface.m_setTSpaceBasic = SetTSpace;
2184 iCalcNewMethod = genTangSpaceDefault(&sContext);
2187 if(!iCalcNewMethod) {
2188 /* sum tangents at connected vertices */
2189 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2196 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2200 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2210 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2211 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2212 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2213 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2215 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2218 tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2219 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2220 sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2221 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2226 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2227 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2228 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2229 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2233 /* write tangent to layer */
2234 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2235 len= (mf->v4)? 4 : 3;
2237 if(mtface == NULL) {
2238 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2239 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2240 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2242 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2250 for(j=0; j<len; j++) {
2251 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2252 normalize_v3_v3(tangent[j], vtang);
2253 ((float *) tangent[j])[3]=1.0f;
2258 BLI_memarena_free(arena);
2259 MEM_freeN(vtangents);
2262 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2264 /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2265 int totface= dm->getNumTessFaces(dm);
2267 MVert * mvert = dm->getVertArray(dm);
2268 MFace * mface = dm->getTessFaceArray(dm);
2269 MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2274 int nr_accumulated = 0;
2277 for ( f=0; f<totface; f++ )
2280 float * verts[4], * tex_coords[4];
2281 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2282 int i, is_degenerate;
2284 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2285 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2288 verts[3]=mvert[mface[f].v4].co;
2289 tex_coords[3]=mtface[f].uv[3];
2292 // discard degenerate faces
2294 if( equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2295 equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2300 // verify last vertex as well if this is a quad
2301 if ( is_degenerate==0 && nr_verts==4 )
2303 if( equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2304 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2309 // verify the winding is consistent
2310 if ( is_degenerate==0 )
2314 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2317 while ( is_degenerate==0 && i<4 )
2319 float cur_edge[2], signed_area;
2320 sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2321 signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2322 if ( i==0 ) is_signed = signed_area<0.0f ? 1 : 0;
2323 else if((is_signed!=0)!=(signed_area<0.0f)) is_degenerate=1;
2325 if ( is_degenerate==0 )
2327 copy_v2_v2(prev_edge, cur_edge);
2334 // proceed if not a degenerate face
2335 if ( is_degenerate==0 )
2337 int nr_tris_to_pile=0;
2338 // quads split at shortest diagonal
2339 int offs = 0; // initial triangulation is 0,1,2 and 0, 2, 3
2342 float pos_len_diag0, pos_len_diag1;
2344 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2345 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2346 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2347 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2349 if(pos_len_diag1<pos_len_diag0)
2350 offs=1; // alter split
2351 else if(pos_len_diag0==pos_len_diag1) // do UV check instead
2353 float tex_len_diag0, tex_len_diag1;
2355 sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2356 tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2357 sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2358 tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2360 if(tex_len_diag1<tex_len_diag0)
2362 offs=1; // alter split
2366 nr_tris_to_pile = nr_verts-2 ;
2367 if ( nr_tris_to_pile==1 || nr_tris_to_pile==2 )
2369 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2371 for ( t=0; t<nr_tris_to_pile; t++ )
2374 float * p0 = verts[indices[t*3+0]];
2375 float * p1 = verts[indices[t*3+1]];
2376 float * p2 = verts[indices[t*3+2]];
2378 float edge_t0[2], edge_t1[2];
2379 sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2380 sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2382 f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2383 if ( f2x_area_uv>FLT_EPSILON )
2385 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2386 sub_v3_v3v3(v0, p1, p0);
2387 sub_v3_v3v3(v1, p2, p0);
2388 cross_v3_v3v3(norm, v0, v1);
2390 f2x_surf_area = len_v3(norm);
2391 fsurf_ratio = f2x_surf_area/f2x_area_uv; // tri area divided by texture area
2394 dsum += (double)(fsurf_ratio);
2404 const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2405 const float use_as_render_bump_scale = sqrtf(avg_area_ratio); // use width of average surface ratio as your bump scale
2406 dm->auto_bump_scale = use_as_render_bump_scale;
2411 dm->auto_bump_scale = 1.0f;
2415 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2417 CustomData *vdata, *fdata, *tfdata = NULL;
2420 /* From the layers requested by the GLSL shader, figure out which ones are
2421 * actually available for this derivedmesh, and retrieve the pointers */
2423 memset(attribs, 0, sizeof(DMVertexAttribs));
2425 vdata = &dm->vertData;
2426 fdata = tfdata = dm->getTessFaceDataLayout(dm);
2428 /* calc auto bump scale if necessary */
2429 if(dm->auto_bump_scale<=0.0f)
2430 DM_calc_auto_bump_scale(dm);
2432 /* add a tangent layer if necessary */
2433 for(b = 0; b < gattribs->totlayer; b++)
2434 if(gattribs->layer[b].type == CD_TANGENT)
2435 if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2436 DM_add_tangent_layer(dm);
2438 for(b = 0; b < gattribs->totlayer; b++) {
2439 if(gattribs->layer[b].type == CD_MTFACE) {
2440 /* uv coordinates */
2441 if(gattribs->layer[b].name[0])
2442 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2443 gattribs->layer[b].name);
2445 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2448 a = attribs->tottface++;
2450 attribs->tface[a].array = tfdata->layers[layer].data;
2451 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2452 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2453 /* attribs->tface[a].glTexco = gattribs->layer[b].gltexco; */ /* BMESH_TODO, trunk has this but not bmesh, need to investigate whats going on here - campbell */
2455 /* BMESH ONLY, may need to get this working?, otherwise remove */
2458 CustomData *pdata = dm->getPolyDataLayout(dm);
2460 if(gattribs->layer[b].name[0])
2461 player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2462 gattribs->layer[b].name);
2464 player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2467 a = attribs->tottface++;
2469 attribs->tface[a].array = NULL;
2470 attribs->tface[a].emOffset = pdata->layers[layer].offset;
2471 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2472 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2478 else if(gattribs->layer[b].type == CD_MCOL) {
2480 if(gattribs->layer[b].name[0])
2481 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2482 gattribs->layer[b].name);
2484 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2487 a = attribs->totmcol++;
2489 attribs->mcol[a].array = tfdata->layers[layer].data;
2490 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2491 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2494 else if(gattribs->layer[b].type == CD_TANGENT) {
2496 layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2499 attribs->tottang = 1;
2501 attribs->tang.array = fdata->layers[layer].data;
2502 attribs->tang.emOffset = fdata->layers[layer].offset;
2503 attribs->tang.glIndex = gattribs->layer[b].glindex;
2506 else if(gattribs->layer[b].type == CD_ORCO) {
2507 /* original coordinates */
2508 layer = CustomData_get_layer_index(vdata, CD_ORCO);
2511 attribs->totorco = 1;
2513 attribs->orco.array = vdata->layers[layer].data;
2514 attribs->orco.emOffset = vdata->layers[layer].offset;
2515 attribs->orco.glIndex = gattribs->layer[b].glindex;
2516 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2522 /* Set object's bounding box based on DerivedMesh min/max data */
2523 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2525 float min[3], max[3];
2527 INIT_MINMAX(min, max);
2529 dm->getMinMax(dm, min, max);
2532 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2534 boundbox_set_from_min_max(ob->bb, min, max);
2537 /* --- NAVMESH (begin) --- */
2538 #ifdef WITH_GAMEENGINE
2540 BM_INLINE int navmesh_bit(int a, int b)
2542 return (a & (1 << b)) >> b;
2545 BM_INLINE void navmesh_intToCol(int i, float col[3])
2547 int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2548 int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2549 int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2550 col[0] = 1 - r*63.0f/255.0f;
2551 col[1] = 1 - g*63.0f/255.0f;
2552 col[2] = 1 - b*63.0f/255.0f;
2555 static void navmesh_drawColored(DerivedMesh *dm)
2558 MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2559 MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2560 int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2567 //UI_ThemeColor(TH_WIRE);
2568 glDisable(GL_LIGHTING);
2570 dm->drawEdges(dm, 0, 1);
2572 glEnable(GL_LIGHTING);*/
2574 glDisable(GL_LIGHTING);
2575 /* if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2576 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2577 //glShadeModel(GL_SMOOTH);
2578 glBegin(glmode = GL_QUADS);
2579 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2580 int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2581 int pi = polygonIdx[a];
2586 navmesh_intToCol(pi, col);
2589 if(new_glmode != glmode) {
2591 glBegin(glmode = new_glmode);
2594 glVertex3fv(mvert[mface->v1].co);
2595 glVertex3fv(mvert[mface->v2].co);
2596 glVertex3fv(mvert[mface->v3].co);
2598 glVertex3fv(mvert[mface->v4].co);
2603 glEnable(GL_LIGHTING);
2606 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2607 int (*setDrawOptions)(MTFace *tface, int has_mcol, int matnr),
2608 int (*compareDrawOptions)(void *userData, int cur_index, int next_index),
2611 (void) setDrawOptions;
2612 (void) compareDrawOptions;
2615 navmesh_drawColored(dm);
2618 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2619 float (*partial_redraw_planes)[4],
2620 int UNUSED(fast), int (*setMaterial)(int, void *attribs))
2622 (void) partial_redraw_planes;
2625 //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2626 navmesh_drawColored(dm);
2629 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2631 DerivedMesh *result;
2632 int maxFaces = dm->getNumPolys(dm);
2634 int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2636 unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2637 int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2640 result = CDDM_copy(dm, 0);
2641 if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2642 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2643 if (sourceRecastData) {
2644 CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2645 sourceRecastData, maxFaces, "recastData");
2648 recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2650 /* note: This is not good design! - really should not be doing this */
2651 result->drawFacesTex = navmesh_DM_drawFacesTex;
2652 result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2656 res = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2657 &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2662 /* invalidate concave polygon */
2663 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2664 unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2665 if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2666 /* set negative polygon idx to all faces */
2667 unsigned short *dmesh = &dmeshes[4*polyIdx];
2668 unsigned short tbase = dmesh[2];
2669 unsigned short tnum = dmesh[3];
2672 for (ti=0; ti<tnum; ti++) {
2673 unsigned short triidx = dtrisToTrisMap[tbase+ti];
2674 unsigned short faceidx = trisToFacesMap[triidx];
2675 if (recastData[faceidx] > 0) {
2676 recastData[faceidx] = -recastData[faceidx];
2683 printf("Error during creation polygon infos\n");
2695 if (dtrisToPolysMap!=NULL)
2696 MEM_freeN(dtrisToPolysMap);
2697 if (dtrisToTrisMap!=NULL)
2698 MEM_freeN(dtrisToTrisMap);
2699 if (trisToFacesMap!=NULL)
2700 MEM_freeN(trisToFacesMap);
2705 #endif /* WITH_GAMEENGINE */
2707 /* --- NAVMESH (end) --- */