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_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h" // N_T
46 #include "BLI_blenlib.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 /* note: until all modifiers can take MPoly's as input,
356 * use this at the start of modifiers */
357 void DM_ensure_tessface(DerivedMesh *dm)
359 const int numTessFaces = dm->getNumTessFaces(dm);
360 const int numPolys = dm->getNumPolys(dm);
362 if ( (numTessFaces == 0) && (numPolys != 0)) {
363 dm->recalcTessellation(dm);
365 if (dm->getNumTessFaces(dm) != 0) {
366 /* printf("info %s: polys -> ngons calculated\n", __func__); */
369 printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
370 __func__, numPolys, dm->type);
375 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
377 /* dm might depend on me, so we need to do everything with a local copy */
379 int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
382 memset(&tmp.vdata, 0, sizeof(tmp.vdata));
383 memset(&tmp.edata, 0, sizeof(tmp.edata));
384 memset(&tmp.fdata, 0, sizeof(tmp.fdata));
385 memset(&tmp.ldata, 0, sizeof(tmp.ldata));
386 memset(&tmp.pdata, 0, sizeof(tmp.pdata));
388 totvert = tmp.totvert = dm->getNumVerts(dm);
389 totedge = tmp.totedge = dm->getNumEdges(dm);
390 totloop = tmp.totloop = dm->getNumLoops(dm);
391 totpoly = tmp.totpoly = dm->getNumPolys(dm);
393 CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
394 CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
395 CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
396 CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
398 if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
403 kb = BLI_findlink(&me->key->block, ob->shapenr-1);
408 printf("%s: error - could not find active shapekey %d!\n",
409 __func__, ob->shapenr-1);
415 /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
419 shapekey_layers_to_keyblocks(dm, me, uid);
423 /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
424 we set them here in case they are missing */
425 if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
426 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
427 if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
428 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
429 if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
430 tmp.mloop = dm->dupLoopArray(dm);
431 tmp.mpoly = dm->dupPolyArray(dm);
433 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
434 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
437 /* object had got displacement layer, should copy this layer to save sculpted data */
438 /* NOTE: maybe some other layers should be copied? nazgul */
439 if(CustomData_has_layer(&me->ldata, CD_MDISPS)) {
440 if (totloop == me->totloop) {
441 MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
442 CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
446 /* yes, must be before _and_ after tesselate */
447 mesh_update_customdata_pointers(&tmp, TRUE);
449 BKE_mesh_tessface_calc(&tmp);
451 CustomData_free(&me->vdata, me->totvert);
452 CustomData_free(&me->edata, me->totedge);
453 CustomData_free(&me->fdata, me->totface);
454 CustomData_free(&me->ldata, me->totloop);
455 CustomData_free(&me->pdata, me->totpoly);
457 /* ok, this should now use new CD shapekey data,
458 which shouuld be fed through the modifier
460 if(tmp.totvert != me->totvert && !did_shapekeys && me->key) {
461 printf("YEEK! this should be recoded! Shape key loss!!!\n");
462 if(tmp.key) tmp.key->id.us--;
469 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
471 int a, totvert = dm->getNumVerts(dm);
475 if(totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
477 if(kb->data) MEM_freeN(kb->data);
478 kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
479 kb->totelem= totvert;
482 mvert=dm->getVertDataArray(dm, CD_MVERT);
484 for(a=0; a<kb->totelem; a++, fp+=3, mvert++) {
485 copy_v3_v3(fp, mvert->co);
489 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
491 CustomData_set_only_copy(&dm->vertData, mask);
492 CustomData_set_only_copy(&dm->edgeData, mask);
493 CustomData_set_only_copy(&dm->faceData, mask);
496 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
498 CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
501 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
503 CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
506 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
508 CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
511 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
513 CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
516 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
518 CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
521 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
523 return CustomData_get(&dm->vertData, index, type);
526 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
528 return CustomData_get(&dm->edgeData, index, type);
531 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
533 return CustomData_get(&dm->faceData, index, type);
536 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
539 return dm->getVertArray(dm);
541 return CustomData_get_layer(&dm->vertData, type);
544 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
547 return dm->getEdgeArray(dm);
549 return CustomData_get_layer(&dm->edgeData, type);
552 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
554 if (type == CD_MFACE)
555 return dm->getTessFaceArray(dm);
557 return CustomData_get_layer(&dm->faceData, type);
560 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
562 return CustomData_get_layer(&dm->polyData, type);
565 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
567 return CustomData_get_layer(&dm->loopData, type);
570 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
572 CustomData_set(&dm->vertData, index, type, data);
575 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
577 CustomData_set(&dm->edgeData, index, type, data);
580 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
582 CustomData_set(&dm->faceData, index, type, data);
585 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
586 int source_index, int dest_index, int count)
588 CustomData_copy_data(&source->vertData, &dest->vertData,
589 source_index, dest_index, count);
592 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
593 int source_index, int dest_index, int count)
595 CustomData_copy_data(&source->edgeData, &dest->edgeData,
596 source_index, dest_index, count);
599 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
600 int source_index, int dest_index, int count)
602 CustomData_copy_data(&source->faceData, &dest->faceData,
603 source_index, dest_index, count);
606 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
607 int source_index, int dest_index, int count)
609 CustomData_copy_data(&source->loopData, &dest->loopData,
610 source_index, dest_index, count);
613 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
614 int source_index, int dest_index, int count)
616 CustomData_copy_data(&source->polyData, &dest->polyData,
617 source_index, dest_index, count);
620 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
622 CustomData_free_elem(&dm->vertData, index, count);
625 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
627 CustomData_free_elem(&dm->edgeData, index, count);
630 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
632 CustomData_free_elem(&dm->faceData, index, count);
635 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
637 CustomData_free_elem(&dm->loopData, index, count);
640 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
642 CustomData_free_elem(&dm->polyData, index, count);
645 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
646 int *src_indices, float *weights,
647 int count, int dest_index)
649 CustomData_interp(&source->vertData, &dest->vertData, src_indices,
650 weights, NULL, count, dest_index);
653 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
655 float *weights, EdgeVertWeight *vert_weights,
656 int count, int dest_index)
658 CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
659 weights, (float*)vert_weights, count, dest_index);
662 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
664 float *weights, FaceVertWeight *vert_weights,
665 int count, int dest_index)
667 CustomData_interp(&source->faceData, &dest->faceData, src_indices,
668 weights, (float*)vert_weights, count, dest_index);
671 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
673 CustomData_swap(&dm->faceData, index, corner_indices);
676 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
678 float *weights, int count, int dest_index)
680 CustomData_interp(&source->loopData, &dest->loopData, src_indices,
681 weights, NULL, count, dest_index);
684 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
686 float *weights, int count, int dest_index)
688 CustomData_interp(&source->polyData, &dest->polyData, src_indices,
689 weights, NULL, count, dest_index);
693 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
695 DerivedMesh *dm = CDDM_from_mesh(me, ob);
701 CDDM_apply_vert_coords(dm, vertCos);
703 CDDM_calc_normals(dm);
710 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
711 ModifierData *md, int build_shapekey_layers)
714 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
720 if (!(md->mode&eModifierMode_Realtime)) return NULL;
721 if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
723 if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr-1))) {
727 if (mti->type==eModifierTypeType_OnlyDeform) {
729 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
731 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
732 dm = mesh_create_derived(me, ob, deformedVerts);
734 if (build_shapekey_layers)
735 add_shapekey_layers(dm, me, ob);
737 MEM_freeN(deformedVerts);
739 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
741 if (build_shapekey_layers)
742 add_shapekey_layers(tdm, me, ob);
744 dm = mti->applyModifier(md, ob, tdm, 0, 0);
746 if(tdm != dm) tdm->release(tdm);
752 static float *get_editbmesh_orco_verts(BMEditMesh *em)
759 /* these may not really be the orco's, but it's only for preview.
760 * could be solver better once, but isn't simple */
762 totvert= em->bm->totvert;
764 orco = MEM_mallocN(sizeof(float)*3*totvert, "BMEditMesh Orco");
766 eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
767 for (a=0; eve; eve=BM_iter_step(&iter), a+=3) {
768 copy_v3_v3(orco+a, eve->co);
774 /* orco custom data layer */
775 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
779 if(layer == CD_ORCO) {
780 /* get original coordinates */
784 return (float(*)[3])get_editbmesh_orco_verts(em);
786 return (float(*)[3])get_mesh_orco_verts(ob);
788 else if(layer == CD_CLOTH_ORCO) {
789 /* apply shape key for cloth, this should really be solved
790 by a more flexible customdata system, but not simple */
792 ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
793 KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
805 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
811 if(em) dm= CDDM_from_BMEditMesh(em, me, FALSE, FALSE);
812 else dm= CDDM_from_mesh(me, ob);
814 orco= get_orco_coords_dm(ob, em, layer, &free);
817 CDDM_apply_vert_coords(dm, orco);
818 if(free) MEM_freeN(orco);
821 CDDM_calc_normals(dm);
826 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
827 DerivedMesh *orcodm, int layer)
829 float (*orco)[3], (*layerorco)[3];
832 totvert= dm->getNumVerts(dm);
835 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
838 if(orcodm->getNumVerts(orcodm) == totvert)
839 orcodm->getVertCos(orcodm, orco);
841 dm->getVertCos(dm, orco);
844 orco= get_orco_coords_dm(ob, em, layer, &free);
848 transform_mesh_orco_verts(ob->data, orco, totvert, 0);
850 if(!(layerorco = DM_get_vert_data_layer(dm, layer))) {
851 DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
852 layerorco = DM_get_vert_data_layer(dm, layer);
855 memcpy(layerorco, orco, sizeof(float)*3*totvert);
856 if(free) MEM_freeN(orco);
860 /* weight paint colors */
862 /* Something of a hack, at the moment deal with weightpaint
863 * by tucking into colors during modifier eval, only in
864 * wpaint mode. Works ok but need to make sure recalc
865 * happens on enter/exit wpaint.
868 void weight_to_rgb(float r_rgb[3], const float weight)
870 const float blend= ((weight/2.0f)+0.5f);
872 if (weight<=0.25f) { // blue->cyan
874 r_rgb[1]= blend*weight*4.0f;
877 else if (weight<=0.50f) { // cyan->green
880 r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
882 else if (weight <= 0.75f) { // green->yellow
883 r_rgb[0]= blend * ((weight-0.50f)*4.0f);
887 else if (weight <= 1.0f) { // yellow->red
889 r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
893 /* exceptional value, unclamped or nan,
894 * avoid uninitialized memory use */
901 /* draw_flag's for calc_weightpaint_vert_color */
903 CALC_WP_MULTIPAINT= (1<<0),
904 CALC_WP_AUTO_NORMALIZE= (1<<1)
907 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
911 if(coba) do_colorband(coba, input, colf);
912 else weight_to_rgb(colf, input);
914 r_col[3] = (unsigned char)(colf[0] * 255.0f);
915 r_col[2] = (unsigned char)(colf[1] * 255.0f);
916 r_col[1] = (unsigned char)(colf[2] * 255.0f);
921 static void calc_weightpaint_vert_color(
922 unsigned char r_col[4],
923 MDeformVert *dv, ColorBand *coba,
924 const int defbase_tot, const int defbase_act,
925 const char *dg_flags,
926 const int selected, const int draw_flag)
930 int make_black= FALSE;
932 if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
933 int was_a_nonzero= FALSE;
936 MDeformWeight *dw= dv->dw;
937 for (i = dv->totweight; i != 0; i--, dw++) {
938 /* in multipaint, get the average if auto normalize is inactive
939 * get the sum if it is active */
940 if (dw->def_nr < defbase_tot) {
941 if (dg_flags[dw->def_nr]) {
950 /* make it black if the selected groups have no weight on a vertex */
951 if (was_a_nonzero == FALSE) {
954 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
955 input /= selected; /* get the average */
959 /* default, non tricky behavior */
960 input= defvert_find_weight(dv, defbase_act);
963 if (make_black) { /* TODO, theme color */
970 CLAMP(input, 0.0f, 1.0f);
971 weightpaint_color(r_col, coba, input);
975 static ColorBand *stored_cb= NULL;
977 void vDM_ColorBand_store(ColorBand *coba)
982 /* return an array of vertex weight colors, caller must free.
984 * note that we could save some memory and allocate RGB only but then we'd need to
985 * re-arrange the colors when copying to the face since MCol has odd ordering,
986 * so leave this as is - campbell */
987 static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, ColorBand *coba)
989 MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
990 int numVerts = dm->getNumVerts(dm);
991 unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * numVerts * 4, "weightmap_v");
994 unsigned char *wc = wtcol_v;
997 /* variables for multipaint */
998 const int defbase_tot = BLI_countlist(&ob->defbase);
999 const int defbase_act = ob->actdef-1;
1000 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
1001 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
1003 for (i = numVerts; i != 0; i--, wc += 4, dv++) {
1004 calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
1007 MEM_freeN(dg_flags);
1011 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
1012 fill_vn_i((int *)wtcol_v, numVerts, col_i);
1018 /* return an array of vertex weight colors from given weights, caller must free.
1020 * note that we could save some memory and allocate RGB only but then we'd need to
1021 * re-arrange the colors when copying to the face since MCol has odd ordering,
1022 * so leave this as is - campbell */
1023 static unsigned char *calc_colors_from_weights_array(const int num, float *weights)
1025 unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * num * 4, "weightmap_v");
1026 unsigned char *wc = wtcol_v;
1029 for (i = 0; i < num; i++, wc += 4, weights++)
1030 weightpaint_color((unsigned char *) wc, NULL, *weights);
1035 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1036 float *weights, int num, const int *indices)
1038 ColorBand *coba= stored_cb; /* warning, not a local var */
1040 unsigned char *wtcol_v;
1041 #if 0 /* See coment below. */
1042 unsigned char *wtcol_f = dm->getTessFaceDataArray(dm, CD_WEIGHT_MCOL);
1044 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_WEIGHT_MLOOPCOL);
1045 #if 0 /* See coment below. */
1046 MFace *mf = dm->getTessFaceArray(dm);
1048 MLoop *mloop = dm->getLoopArray(dm), *ml;
1049 MPoly *mp = dm->getPolyArray(dm);
1050 int numFaces = dm->getNumTessFaces(dm);
1051 int numVerts = dm->getNumVerts(dm);
1055 #if 0 /* See comment below */
1056 /* If no CD_WEIGHT_MCOL existed yet, add a new one! */
1058 wtcol_f = CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_CALLOC, NULL, numFaces);
1061 unsigned char *wtcol_f_step = wtcol_f;
1063 /* XXX We have to create a CD_WEIGHT_MCOL, else it might sigsev (after a SubSurf mod, eg)... */
1064 if(!dm->getTessFaceDataArray(dm, CD_WEIGHT_MCOL))
1065 CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_CALLOC, NULL, numFaces);
1070 /* Weights are given by caller. */
1073 /* If indices is not NULL, it means we do not have weights for all vertices,
1074 * so we must create them (and set them to zero)... */
1076 w = MEM_callocN(sizeof(float)*numVerts, "Temp weight array DM_update_weight_mcol");
1079 w[indices[i]] = weights[i];
1082 /* Convert float weights to colors. */
1083 wtcol_v = calc_colors_from_weights_array(numVerts, w);
1089 /* No weights given, take them from active vgroup(s). */
1091 wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
1093 /* Now copy colors in all face verts. */
1094 /*first add colors to the tessellation faces*/
1095 /* XXX Why update that layer? We have to update WEIGHT_MLOOPCOL anyway,
1096 * and tessellation recreates mface layers from mloop/mpoly ones, so no
1097 * need to fill WEIGHT_MCOL here. */
1099 for (i = 0; i < numFaces; i++, mf++, wtcol_f_step += (4 * 4)) {
1100 /*origindex being NULL means we're operating on original mesh data*/
1102 unsigned int fidx= mf->v4 ? 3:2;
1104 #else /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
1111 *(int *)(&wtcol_f_step[3 * 4]) = 0;
1116 copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
1117 (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
1121 /*now add to loops, so the data can be passed through the modifier stack*/
1122 /* If no CD_WEIGHT_MLOOPCOL existed yet, we have to add a new one! */
1124 BLI_array_declare(wtcol_l);
1126 for (i=0; i<dm->numPolyData; i++, mp++) {
1127 ml = mloop + mp->loopstart;
1129 BLI_array_growitems(wtcol_l, mp->totloop);
1130 for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
1131 copy_v4_v4_char((char *)&wtcol_l[totloop],
1132 (char *)&wtcol_v[4 * ml->v]);
1135 CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1139 for (i=0; i < dm->numPolyData; i++, mp++) {
1140 ml = mloop + mp->loopstart;
1142 for (j=0; j < mp->totloop; j++, ml++, totloop++) {
1143 copy_v4_v4_char((char *)&wtcol_l[totloop],
1144 (char *)&wtcol_v[4 * ml->v]);
1153 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1161 tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1162 for (i=0; i<tot; i++) {
1163 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1164 float (*cos)[3], (*kbcos)[3];
1166 for (kb=me->key->block.first; kb; kb=kb->next) {
1167 if (kb->uid == layer->uid)
1172 kb = add_keyblock(me->key, layer->name);
1173 kb->uid = layer->uid;
1177 MEM_freeN(kb->data);
1179 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1180 kb->totelem = dm->numVertData;
1182 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1183 if (kb->uid == actshape_uid) {
1184 MVert *mvert = dm->getVertArray(dm);
1186 for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1187 copy_v3_v3(*kbcos, mvert->co);
1190 for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1191 copy_v3_v3(*kbcos, *cos);
1196 for (kb=me->key->block.first; kb; kb=kb->next) {
1197 if (kb->totelem != dm->numVertData) {
1199 MEM_freeN(kb->data);
1201 kb->totelem = dm->numVertData;
1202 kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1203 fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1208 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1213 const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1218 /* ensure we can use mesh vertex count for derived mesh custom data */
1219 if (me->totvert != dm->getNumVerts(dm)) {
1221 "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1222 __func__, me->id.name+2, me->totvert, dm->getNumVerts(dm));
1226 for (i=0, kb=key->block.first; kb; kb=kb->next, i++) {
1230 if (me->totvert != kb->totelem) {
1232 "%s: vertex size mismatch (mesh/keyblock) '%s' (%d != %d)\n",
1233 __func__, me->id.name+2, me->totvert, kb->totelem);
1234 array = MEM_callocN(shape_alloc_len, __func__);
1237 array = MEM_mallocN(shape_alloc_len, __func__);
1238 memcpy(array, kb->data, shape_alloc_len);
1241 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1242 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1244 dm->vertData.layers[ci].uid = kb->uid;
1248 /* new value for useDeform -1 (hack for the gameengine):
1249 * - apply only the modifier stack of the object, skipping the virtual modifiers,
1250 * - don't apply the key
1251 * - apply deform modifiers and input vertexco
1253 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1254 DerivedMesh **deform_r, DerivedMesh **final_r,
1255 int useRenderParams, int useDeform,
1256 int needMapping, CustomDataMask dataMask,
1257 int index, int useCache, int build_shapekey_layers)
1259 Mesh *me = ob->data;
1260 ModifierData *firstmd, *md, *previewmd = NULL;
1261 LinkNode *datamasks, *curr;
1262 CustomDataMask mask, nextmask, append_mask = 0;
1263 float (*deformedVerts)[3] = NULL;
1264 DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1265 int numVerts = me->totvert;
1267 int isPrevDeform= FALSE;
1268 int skipVirtualArmature = (useDeform < 0);
1269 MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1270 int has_multires = mmd != NULL, multires_applied = 0;
1271 int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1273 const int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1274 (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1275 /* Generic preview only in object mode! */
1276 const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1277 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1278 const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1280 const int do_final_wmcol = FALSE;
1281 int do_init_wmcol = ((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1282 /* XXX Same as above... For now, only weights preview in WPaint mode. */
1283 const int do_mod_wmcol = do_init_wmcol;
1285 if(mmd && !mmd->sculptlvl)
1288 if(!skipVirtualArmature) {
1289 firstmd = modifiers_getVirtualModifierList(ob);
1292 /* game engine exception */
1293 firstmd = ob->modifiers.first;
1294 if(firstmd && firstmd->type == eModifierType_Armature)
1295 firstmd = firstmd->next;
1300 modifiers_clearErrors(ob);
1302 if(useRenderParams) required_mode = eModifierMode_Render;
1303 else required_mode = eModifierMode_Realtime;
1305 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1308 if(do_mod_wmcol || do_mod_mcol) {
1309 /* Find the last active modifier generating a preview, or NULL if none. */
1310 /* XXX Currently, DPaint modifier just ignores this.
1311 * Needs a stupid hack...
1312 * The whole "modifier preview" thing has to be (re?)designed, anyway! */
1313 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1316 if(deform_r) *deform_r = NULL;
1321 deformedVerts = inputVertexCos;
1323 /* Apply all leading deforming modifiers */
1324 for(;md; md = md->next, curr = curr->next) {
1325 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1329 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1330 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1332 if(mti->type == eModifierTypeType_OnlyDeform) {
1334 deformedVerts = mesh_getVertexCos(me, &numVerts);
1336 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1341 /* grab modifiers until index i */
1342 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1346 /* Result of all leading deforming modifiers is cached for
1347 * places that wish to use the original mesh but with deformed
1348 * coordinates (vpaint, etc.)
1351 *deform_r = CDDM_from_mesh(me, ob);
1353 if (build_shapekey_layers)
1354 add_shapekey_layers(dm, me, ob);
1357 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1358 CDDM_calc_normals(*deform_r);
1362 /* default behavior for meshes */
1364 deformedVerts = inputVertexCos;
1366 deformedVerts = mesh_getVertexCos(me, &numVerts);
1370 /* Now apply all remaining modifiers. If useDeform is off then skip
1377 for(;md; md = md->next, curr = curr->next) {
1378 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1382 if(!modifier_isEnabled(scene, md, required_mode)) continue;
1383 if(mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1384 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1385 modifier_setError(md, "Modifier requires original data, bad stack position.");
1388 if(sculpt_mode && (!has_multires || multires_applied)) {
1391 if(scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1392 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1394 unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1395 unsupported|= multires_applied;
1398 modifier_setError(md, "Not supported in sculpt mode.");
1402 if(needMapping && !modifier_supportsMapping(md)) continue;
1403 if(useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1405 /* add an orco layer if needed by this modifier */
1406 if(mti->requiredDataMask)
1407 mask = mti->requiredDataMask(ob, md);
1411 if(dm && (mask & CD_MASK_ORCO))
1412 add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1414 /* How to apply modifier depends on (a) what we already have as
1415 * a result of previous modifiers (could be a DerivedMesh or just
1416 * deformed vertices) and (b) what type the modifier is.
1419 if(mti->type == eModifierTypeType_OnlyDeform) {
1420 /* No existing verts to deform, need to build them. */
1421 if(!deformedVerts) {
1423 /* Deforming a derived mesh, read the vertex locations
1424 * out of the mesh and deform them. Once done with this
1425 * run of deformers verts will be written back.
1427 numVerts = dm->getNumVerts(dm);
1429 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1430 dm->getVertCos(dm, deformedVerts);
1432 deformedVerts = mesh_getVertexCos(me, &numVerts);
1436 /* if this is not the last modifier in the stack then recalculate the normals
1437 * to avoid giving bogus normals to the next modifier see: [#23673] */
1438 if(isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1439 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1440 if(dm && dm->type == DM_TYPE_CDDM) {
1441 CDDM_apply_vert_coords(dm, deformedVerts);
1442 CDDM_calc_normals(dm);
1446 mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1450 /* determine which data layers are needed by following modifiers */
1452 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1456 /* apply vertex coordinates or build a DerivedMesh as necessary */
1459 DerivedMesh *tdm = CDDM_copy(dm);
1463 CDDM_apply_vert_coords(dm, deformedVerts);
1464 CDDM_calc_normals(dm);
1467 dm = CDDM_from_mesh(me, ob);
1469 if (build_shapekey_layers)
1470 add_shapekey_layers(dm, me, ob);
1473 CDDM_apply_vert_coords(dm, deformedVerts);
1474 CDDM_calc_normals(dm);
1478 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1480 /* Constructive modifiers need to have an origindex
1481 * otherwise they wont have anywhere to copy the data from.
1483 * Also create ORIGINDEX data if any of the following modifiers
1484 * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1485 * data by using generic DM_copy_vert_data() functions.
1487 if(needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1489 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1490 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1491 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1493 range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1494 range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1495 range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1500 /* set the DerivedMesh to only copy needed data */
1501 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1502 /* needMapping check here fixes bug [#28112], otherwise its
1503 * possible that it wont be copied */
1504 mask |= append_mask;
1505 DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1507 /* add cloth rest shape key if need */
1508 if(mask & CD_MASK_CLOTH_ORCO)
1509 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1511 /* add an origspace layer if needed */
1512 if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE_MLOOP) {
1513 if(!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1514 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1515 DM_init_origspace(dm);
1519 ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1522 /* if the modifier returned a new dm, release the old one */
1523 if(dm && dm != ndm) dm->release(dm);
1528 if(deformedVerts != inputVertexCos)
1529 MEM_freeN(deformedVerts);
1531 deformedVerts = NULL;
1535 /* create an orco derivedmesh in parallel */
1536 if(nextmask & CD_MASK_ORCO) {
1538 orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1540 nextmask &= ~CD_MASK_ORCO;
1541 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1542 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1545 /* if the modifier returned a new dm, release the old one */
1546 if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1551 /* create cloth orco derivedmesh in parallel */
1552 if(nextmask & CD_MASK_CLOTH_ORCO) {
1554 clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1556 nextmask &= ~CD_MASK_CLOTH_ORCO;
1557 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1558 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1561 /* if the modifier returned a new dm, release the old one */
1562 if(clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1567 /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1568 /* XXX Temp and hackish solution! */
1569 if (md->type == eModifierType_DynamicPaint)
1570 append_mask |= CD_MASK_WEIGHT_MCOL;
1571 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1572 else if ((md == previewmd) && (do_mod_wmcol)) {
1573 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1574 append_mask |= CD_MASK_WEIGHT_MCOL;
1578 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1580 /* grab modifiers until index i */
1581 if((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1584 if(sculpt_mode && md->type == eModifierType_Multires)
1585 multires_applied = 1;
1588 for(md=firstmd; md; md=md->next)
1589 modifier_freeTemporaryData(md);
1591 /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1592 * need to apply these back onto the DerivedMesh. If we have no
1593 * DerivedMesh then we need to build one.
1595 if(dm && deformedVerts) {
1596 finaldm = CDDM_copy(dm);
1600 CDDM_apply_vert_coords(finaldm, deformedVerts);
1601 CDDM_calc_normals(finaldm);
1603 #if 0 /* For later nice mod preview! */
1604 /* In case we need modified weights in CD_WEIGHT_MCOL, we have to re-compute it. */
1606 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1611 #if 0 /* For later nice mod preview! */
1612 /* In case we need modified weights in CD_WEIGHT_MCOL, we have to re-compute it. */
1614 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1617 int recalc_normals= 0;
1619 finaldm = CDDM_from_mesh(me, ob);
1621 if(build_shapekey_layers) {
1622 add_shapekey_layers(finaldm, me, ob);
1627 CDDM_apply_vert_coords(finaldm, deformedVerts);
1631 if(recalc_normals) {
1632 CDDM_calc_normals(finaldm);
1635 /* In this case, we should never have weight-modifying modifiers in stack... */
1637 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1640 /* add an orco layer if needed */
1641 if(dataMask & CD_MASK_ORCO) {
1642 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1644 if(deform_r && *deform_r)
1645 add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1648 #ifdef WITH_GAMEENGINE
1649 /* NavMesh - this is a hack but saves having a NavMesh modifier */
1650 if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1652 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1653 if (finaldm != tdm) {
1654 finaldm->release(finaldm);
1658 #endif /* WITH_GAMEENGINE */
1661 /* calculating normals can re-calculate tessfaces in some cases */
1662 int num_tessface = finaldm->getNumTessFaces(finaldm);
1663 /* --------------------------------------------------------------------- */
1664 /* First calculate the polygon and vertex normals, re-tessellation
1665 * copies these into the tessface's normal layer */
1668 /* comment because this causes a bug when deform is applied after a
1669 * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1670 * it also looks like this isn't even needed since code above recalc's
1671 * normals - campbell */
1673 finaldm->calcNormals(finaldm);
1676 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1677 * from loops and polys onto the tessfaces. This may be currently be
1678 * redundant in cases where the render mode doesn't use these inputs, but
1679 * ideally eventually tessellation would happen on-demand, and this is one
1680 * of the primary places it would be needed. */
1681 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0) {
1682 finaldm->recalcTessellation(finaldm);
1684 /* Need to watch this, it can cause issues, see bug [#29338] */
1685 /* take care with this block, we really need testing frameworks */
1686 /* --------------------------------------------------------------------- */
1693 orcodm->release(orcodm);
1695 clothorcodm->release(clothorcodm);
1697 if(deformedVerts && deformedVerts != inputVertexCos)
1698 MEM_freeN(deformedVerts);
1700 BLI_linklist_free(datamasks, NULL);
1703 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1705 int i, numVerts = *numVerts_r = em->bm->totvert;
1710 cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1712 eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1713 for (i=0; eve; eve=BM_iter_step(&iter), i++) {
1714 copy_v3_v3(cos[i], eve->co);
1720 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1722 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1723 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1725 if(!modifier_isEnabled(scene, md, required_mode)) return 0;
1726 if((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1727 modifier_setError(md, "Modifier requires original data, bad stack position.");
1734 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1735 DerivedMesh **final_r,
1736 CustomDataMask dataMask)
1739 float (*deformedVerts)[3] = NULL;
1740 CustomDataMask mask;
1741 DerivedMesh *dm, *orcodm = NULL;
1742 int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1743 LinkNode *datamasks, *curr;
1744 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1746 modifiers_clearErrors(ob);
1748 if(cage_r && cageIndex == -1) {
1749 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1753 md = modifiers_getVirtualModifierList(ob);
1755 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1758 for(i = 0; md; i++, md = md->next, curr = curr->next) {
1759 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1763 if(!editbmesh_modifier_is_enabled(scene, md, dm))
1766 /* add an orco layer if needed by this modifier */
1767 if(dm && mti->requiredDataMask) {
1768 mask = mti->requiredDataMask(ob, md);
1769 if(mask & CD_MASK_ORCO)
1770 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1773 /* How to apply modifier depends on (a) what we already have as
1774 * a result of previous modifiers (could be a DerivedMesh or just
1775 * deformed vertices) and (b) what type the modifier is.
1778 if(mti->type == eModifierTypeType_OnlyDeform) {
1779 /* No existing verts to deform, need to build them. */
1780 if(!deformedVerts) {
1782 /* Deforming a derived mesh, read the vertex locations
1783 * out of the mesh and deform them. Once done with this
1784 * run of deformers verts will be written back.
1786 numVerts = dm->getNumVerts(dm);
1788 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1789 dm->getVertCos(dm, deformedVerts);
1791 deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1795 if (mti->deformVertsEM)
1796 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1797 else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1801 /* apply vertex coordinates or build a DerivedMesh as necessary */
1804 DerivedMesh *tdm = CDDM_copy(dm);
1805 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1808 CDDM_apply_vert_coords(dm, deformedVerts);
1809 CDDM_calc_normals(dm);
1810 } else if(cage_r && dm == *cage_r) {
1811 /* dm may be changed by this modifier, so we need to copy it
1817 dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
1820 CDDM_apply_vert_coords(dm, deformedVerts);
1821 CDDM_calc_normals(dm);
1825 /* create an orco derivedmesh in parallel */
1826 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1827 if(mask & CD_MASK_ORCO) {
1829 orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1831 mask &= ~CD_MASK_ORCO;
1832 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1834 if (mti->applyModifierEM)
1835 ndm = mti->applyModifierEM(md, ob, em, orcodm);
1837 ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1840 /* if the modifier returned a new dm, release the old one */
1841 if(orcodm && orcodm != ndm) orcodm->release(orcodm);
1846 /* set the DerivedMesh to only copy needed data */
1847 mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1849 DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1851 if(mask & CD_MASK_ORIGSPACE_MLOOP) {
1852 if(!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1853 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1854 DM_init_origspace(dm);
1858 if (mti->applyModifierEM)
1859 ndm = mti->applyModifierEM(md, ob, em, dm);
1861 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1869 if (deformedVerts) {
1870 MEM_freeN(deformedVerts);
1871 deformedVerts = NULL;
1876 if(cage_r && i == cageIndex) {
1877 if(dm && deformedVerts) {
1878 *cage_r = CDDM_copy(dm);
1879 CDDM_apply_vert_coords(*cage_r, deformedVerts);
1884 getEditDerivedBMesh(em, ob,
1885 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
1890 BLI_linklist_free(datamasks, NULL);
1892 /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
1893 * to apply these back onto the DerivedMesh. If we have no DerivedMesh
1894 * then we need to build one.
1896 if(dm && deformedVerts) {
1897 *final_r = CDDM_copy(dm);
1899 if(!(cage_r && dm == *cage_r)) dm->release(dm);
1901 CDDM_apply_vert_coords(*final_r, deformedVerts);
1902 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
1906 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1908 else if (!deformedVerts && cage_r && *cage_r) {
1909 /* cage should already have up to date normals */
1911 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
1914 /* this is just a copy of the editmesh, no need to calc normals */
1915 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
1916 deformedVerts = NULL;
1920 /* BMESH_ONLY, ensure tessface's used for drawing,
1921 * but dont recalculate if the last modifier in the stack gives us tessfaces
1922 * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isnt essential
1923 * but quiets annoying error messages since tessfaces wont be created. */
1924 if ((*final_r)->type != DM_TYPE_EDITBMESH) {
1925 DM_ensure_tessface(*final_r);
1928 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
1929 if (*cage_r != *final_r) {
1930 DM_ensure_tessface(*cage_r);
1936 /* add an orco layer if needed */
1937 if(dataMask & CD_MASK_ORCO)
1938 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
1941 orcodm->release(orcodm);
1944 MEM_freeN(deformedVerts);
1947 static void clear_mesh_caches(Object *ob)
1951 /* also serves as signal to remake texspace */
1961 freedisplist(&ob->disp);
1963 if (ob->derivedFinal) {
1964 ob->derivedFinal->needsFree = 1;
1965 ob->derivedFinal->release(ob->derivedFinal);
1966 ob->derivedFinal= NULL;
1968 if (ob->derivedDeform) {
1969 ob->derivedDeform->needsFree = 1;
1970 ob->derivedDeform->release(ob->derivedDeform);
1971 ob->derivedDeform= NULL;
1975 object_sculpt_modifiers_changed(ob);
1979 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
1980 int build_shapekey_layers)
1982 Object *obact = scene->basact?scene->basact->object:NULL;
1983 int editing = paint_facesel_test(ob);
1984 /* weight paint and face select need original indices because of selection buffer drawing */
1985 int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
1987 clear_mesh_caches(ob);
1989 mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
1990 &ob->derivedFinal, 0, 1,
1991 needMapping, dataMask, -1, 1, build_shapekey_layers);
1993 DM_set_object_boundbox (ob, ob->derivedFinal);
1995 ob->derivedFinal->needsFree = 0;
1996 ob->derivedDeform->needsFree = 0;
1997 ob->lastDataMask = dataMask;
2000 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2002 clear_mesh_caches(obedit);
2004 if (em->derivedFinal) {
2005 if (em->derivedFinal!=em->derivedCage) {
2006 em->derivedFinal->needsFree = 1;
2007 em->derivedFinal->release(em->derivedFinal);
2009 em->derivedFinal = NULL;
2011 if (em->derivedCage) {
2012 em->derivedCage->needsFree = 1;
2013 em->derivedCage->release(em->derivedCage);
2014 em->derivedCage = NULL;
2017 editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2018 DM_set_object_boundbox (obedit, em->derivedFinal);
2020 em->lastDataMask = dataMask;
2021 em->derivedFinal->needsFree = 0;
2022 em->derivedCage->needsFree = 0;
2025 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2026 CustomDataMask dataMask, int build_shapekey_layers)
2029 editbmesh_build_data(scene, ob, em, dataMask);
2031 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2037 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2039 /* if there's no derived mesh or the last data mask used doesn't include
2040 * the data we need, rebuild the derived mesh
2042 if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2043 mesh_build_data(scene, ob, dataMask, 0);
2045 return ob->derivedFinal;
2048 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2050 /* if there's no derived mesh or the last data mask used doesn't include
2051 * the data we need, rebuild the derived mesh
2053 if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2054 mesh_build_data(scene, ob, dataMask, 0);
2056 return ob->derivedDeform;
2059 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2063 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2068 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2072 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2077 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2081 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2086 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2087 CustomDataMask dataMask)
2091 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2096 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2097 CustomDataMask dataMask)
2101 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2106 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2107 CustomDataMask dataMask)
2111 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2116 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2117 float (*vertCos)[3],
2118 CustomDataMask dataMask)
2122 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2129 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2130 CustomDataMask dataMask)
2132 /* if there's no derived mesh or the last data mask used doesn't include
2133 * the data we need, rebuild the derived mesh
2135 if(!em->derivedCage ||
2136 (em->lastDataMask & dataMask) != dataMask)
2137 editbmesh_build_data(scene, obedit, em, dataMask);
2139 *final_r = em->derivedFinal;
2140 return em->derivedCage;
2143 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2145 /* if there's no derived mesh or the last data mask used doesn't include
2146 * the data we need, rebuild the derived mesh
2148 if(!em->derivedCage ||
2149 (em->lastDataMask & dataMask) != dataMask)
2150 editbmesh_build_data(scene, obedit, em, dataMask);
2152 return em->derivedCage;
2155 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2157 return getEditDerivedBMesh(em, obedit, NULL);
2161 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2163 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2165 float *vec = userData;
2169 /* check if we've been here before (normal should not be 0) */
2170 if(vec[3] || vec[4] || vec[5]) return;
2172 copy_v3_v3(vec, co);
2175 copy_v3_v3(vec, no_f);
2178 normal_short_to_float_v3(vec, no_s);
2182 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2183 /* this is needed for all code using vertexgroups (no subsurf support) */
2184 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2185 /* in use now by vertex/weight paint and particle generating */
2187 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2191 float *vertexcosnos;
2193 /* lets prevent crashing... */
2194 if(ob->type!=OB_MESH || me->totvert==0)
2197 dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2198 vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2200 if(dm->foreachMappedVert) {
2201 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2204 float *fp= vertexcosnos;
2207 for(a=0; a< me->totvert; a++, fp+=6) {
2208 dm->getVertCo(dm, a, fp);
2209 dm->getVertNo(dm, a, fp+3);
2214 return vertexcosnos;
2217 /* ******************* GLSL ******************** */
2221 float * precomputedFaceNormals;
2222 MTFace * mtface; // texture coordinates
2223 MFace * mface; // indices
2224 MVert * mvert; // vertices & normals
2226 float (*tangent)[4]; // destination
2229 } SGLSLMeshToTangent;
2232 #include "mikktspace.h"
2234 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2236 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2237 return pMesh->numTessFaces;
2240 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2242 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2243 return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2246 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2248 //assert(vert_index>=0 && vert_index<4);
2249 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2250 const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2251 copy_v3_v3(fPos, co);
2254 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2256 //assert(vert_index>=0 && vert_index<4);
2257 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2259 if(pMesh->mtface!=NULL) {
2260 float * uv = pMesh->mtface[face_num].uv[vert_index];
2261 fUV[0]=uv[0]; fUV[1]=uv[1];
2264 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2265 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2269 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2271 //assert(vert_index>=0 && vert_index<4);
2272 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2274 const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2275 if(!smoothnormal) { // flat
2276 if(pMesh->precomputedFaceNormals) {
2277 copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2280 MFace *mf= &pMesh->mface[face_num];
2281 float *p0= pMesh->mvert[mf->v1].co;
2282 float *p1= pMesh->mvert[mf->v2].co;
2283 float *p2= pMesh->mvert[mf->v3].co;
2286 float *p3 = pMesh->mvert[mf->v4].co;
2287 normal_quad_v3(fNorm, p0, p1, p2, p3);
2290 normal_tri_v3(fNorm, p0, p1, p2);
2295 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2296 normal_short_to_float_v3(fNorm, no);
2299 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2301 //assert(vert_index>=0 && vert_index<4);
2302 SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2303 float * pRes = pMesh->tangent[4*face_num+iVert];
2304 copy_v3_v3(pRes, fvTangent);
2309 void DM_add_tangent_layer(DerivedMesh *dm)
2312 MTFace *mtface, *tf;
2314 MVert *mvert, *v1, *v2, *v3, *v4;
2315 MemArena *arena= NULL;
2316 VertexTangent **vtangents= NULL;
2317 float (*orco)[3]= NULL, (*tangent)[4];
2318 float *uv1, *uv2, *uv3, *uv4, *vtang;
2319 float fno[3], tang[3], uv[4][2];
2320 int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2323 if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2326 nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2328 /* check we have all the needed layers */
2329 totvert= dm->getNumVerts(dm);
2330 totface= dm->getNumTessFaces(dm);
2332 mvert= dm->getVertArray(dm);
2333 mface= dm->getTessFaceArray(dm);
2334 mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2337 orco= dm->getVertDataArray(dm, CD_ORCO);
2342 /* create tangent layer */
2343 DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2344 tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2346 /* allocate some space */
2347 arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2348 BLI_memarena_use_calloc(arena);
2349 vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2351 // new computation method
2353 if(iCalcNewMethod != 0) {
2354 SGLSLMeshToTangent mesh2tangent= {0};
2355 SMikkTSpaceContext sContext= {0};
2356 SMikkTSpaceInterface sInterface= {0};
2358 mesh2tangent.precomputedFaceNormals = nors;
2359 mesh2tangent.mtface = mtface;
2360 mesh2tangent.mface = mface;
2361 mesh2tangent.mvert = mvert;
2362 mesh2tangent.orco = orco;
2363 mesh2tangent.tangent = tangent;
2364 mesh2tangent.numTessFaces = totface;
2366 sContext.m_pUserData = &mesh2tangent;
2367 sContext.m_pInterface = &sInterface;
2368 sInterface.m_getNumFaces = GetNumFaces;
2369 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2370 sInterface.m_getPosition = GetPosition;
2371 sInterface.m_getTexCoord = GetTextureCoordinate;
2372 sInterface.m_getNormal = GetNormal;
2373 sInterface.m_setTSpaceBasic = SetTSpace;
2376 iCalcNewMethod = genTangSpaceDefault(&sContext);
2379 if(!iCalcNewMethod) {
2380 /* sum tangents at connected vertices */
2381 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2388 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2392 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2402 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2403 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2404 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2405 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2407 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2410 tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2411 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2412 sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2413 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2418 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2419 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2420 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2421 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2425 /* write tangent to layer */
2426 for(i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2427 len= (mf->v4)? 4 : 3;
2429 if(mtface == NULL) {
2430 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2431 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2432 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2434 map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2442 for(j=0; j<len; j++) {
2443 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2444 normalize_v3_v3(tangent[j], vtang);
2445 ((float *) tangent[j])[3]=1.0f;
2450 BLI_memarena_free(arena);
2451 MEM_freeN(vtangents);
2454 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2456 /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2457 int totface= dm->getNumTessFaces(dm);
2459 MVert * mvert = dm->getVertArray(dm);
2460 MFace * mface = dm->getTessFaceArray(dm);
2461 MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2465 int nr_accumulated = 0;
2468 for ( f=0; f < totface; f++ ) {
2470 float * verts[4], * tex_coords[4];
2471 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2472 int i, is_degenerate;
2474 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2475 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2477 verts[3]=mvert[mface[f].v4].co;
2478 tex_coords[3]=mtface[f].uv[3];
2481 // discard degenerate faces
2483 if( equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2484 equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2489 // verify last vertex as well if this is a quad
2490 if (is_degenerate == 0 && nr_verts == 4) {
2491 if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2492 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2497 // verify the winding is consistent
2498 if (is_degenerate == 0) {
2501 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2504 while (is_degenerate == 0 && i < 4) {
2505 float cur_edge[2], signed_area;
2506 sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2507 signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2510 is_signed = (signed_area < 0.0f) ? 1 : 0;
2512 else if((is_signed != 0) != (signed_area < 0.0f)) {
2516 if (is_degenerate == 0) {
2517 copy_v2_v2(prev_edge, cur_edge);
2524 // proceed if not a degenerate face
2525 if (is_degenerate == 0) {
2526 int nr_tris_to_pile=0;
2527 // quads split at shortest diagonal
2528 int offs = 0; // initial triangulation is 0,1,2 and 0, 2, 3
2529 if (nr_verts == 4) {
2530 float pos_len_diag0, pos_len_diag1;
2532 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2533 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2534 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2535 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2537 if(pos_len_diag1<pos_len_diag0) {
2538 offs=1; // alter split
2540 else if(pos_len_diag0==pos_len_diag1) { /* do UV check instead */
2541 float tex_len_diag0, tex_len_diag1;
2543 sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2544 tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2545 sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2546 tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2548 if (tex_len_diag1<tex_len_diag0) {
2549 offs=1; /* alter split */
2553 nr_tris_to_pile = nr_verts - 2;
2554 if (nr_tris_to_pile==1 || nr_tris_to_pile==2) {
2555 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2557 for ( t=0; t<nr_tris_to_pile; t++ )
2560 float * p0 = verts[indices[t*3+0]];
2561 float * p1 = verts[indices[t*3+1]];
2562 float * p2 = verts[indices[t*3+2]];
2564 float edge_t0[2], edge_t1[2];
2565 sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2566 sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2568 f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2569 if (f2x_area_uv>FLT_EPSILON) {
2570 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2571 sub_v3_v3v3(v0, p1, p0);
2572 sub_v3_v3v3(v1, p2, p0);
2573 cross_v3_v3v3(norm, v0, v1);
2575 f2x_surf_area = len_v3(norm);
2576 fsurf_ratio = f2x_surf_area/f2x_area_uv; // tri area divided by texture area
2579 dsum += (double)(fsurf_ratio);
2589 const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2590 const float use_as_render_bump_scale = sqrtf(avg_area_ratio); // use width of average surface ratio as your bump scale
2591 dm->auto_bump_scale = use_as_render_bump_scale;
2595 dm->auto_bump_scale = 1.0f;
2599 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2601 CustomData *vdata, *fdata, *tfdata = NULL;
2604 /* From the layers requested by the GLSL shader, figure out which ones are
2605 * actually available for this derivedmesh, and retrieve the pointers */
2607 memset(attribs, 0, sizeof(DMVertexAttribs));
2609 vdata = &dm->vertData;
2610 fdata = tfdata = dm->getTessFaceDataLayout(dm);
2612 /* calc auto bump scale if necessary */
2613 if(dm->auto_bump_scale<=0.0f)
2614 DM_calc_auto_bump_scale(dm);
2616 /* add a tangent layer if necessary */
2617 for(b = 0; b < gattribs->totlayer; b++)
2618 if(gattribs->layer[b].type == CD_TANGENT)
2619 if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2620 DM_add_tangent_layer(dm);
2622 for(b = 0; b < gattribs->totlayer; b++) {
2623 if(gattribs->layer[b].type == CD_MTFACE) {
2624 /* uv coordinates */
2625 if(gattribs->layer[b].name[0])
2626 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2627 gattribs->layer[b].name);
2629 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2632 a = attribs->tottface++;
2634 attribs->tface[a].array = tfdata->layers[layer].data;
2635 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2636 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2637 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2639 /* BMESH ONLY, may need to get this working?, otherwise remove */
2642 CustomData *pdata = dm->getPolyDataLayout(dm);
2644 if(gattribs->layer[b].name[0])
2645 player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2646 gattribs->layer[b].name);
2648 player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2651 a = attribs->tottface++;
2653 attribs->tface[a].array = NULL;
2654 attribs->tface[a].emOffset = pdata->layers[layer].offset;
2655 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2656 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2662 else if(gattribs->layer[b].type == CD_MCOL) {
2664 if(gattribs->layer[b].name[0])
2665 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2666 gattribs->layer[b].name);
2668 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2671 a = attribs->totmcol++;
2673 attribs->mcol[a].array = tfdata->layers[layer].data;
2674 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2675 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2678 else if(gattribs->layer[b].type == CD_TANGENT) {
2680 layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2683 attribs->tottang = 1;
2685 attribs->tang.array = fdata->layers[layer].data;
2686 attribs->tang.emOffset = fdata->layers[layer].offset;
2687 attribs->tang.glIndex = gattribs->layer[b].glindex;
2690 else if(gattribs->layer[b].type == CD_ORCO) {
2691 /* original coordinates */
2692 layer = CustomData_get_layer_index(vdata, CD_ORCO);
2695 attribs->totorco = 1;
2697 attribs->orco.array = vdata->layers[layer].data;
2698 attribs->orco.emOffset = vdata->layers[layer].offset;
2699 attribs->orco.glIndex = gattribs->layer[b].glindex;
2700 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2706 /* Set object's bounding box based on DerivedMesh min/max data */
2707 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2709 float min[3], max[3];
2711 INIT_MINMAX(min, max);
2713 dm->getMinMax(dm, min, max);
2716 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2718 boundbox_set_from_min_max(ob->bb, min, max);
2721 /* --- NAVMESH (begin) --- */
2722 #ifdef WITH_GAMEENGINE
2724 /* BMESH_TODO, navmesh is not working right currently
2725 * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2727 * Proposed solution, rather then copy CD_RECAST into the MFace array,
2728 * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2729 * data from the original me->mpoly layer. - campbell
2733 BM_INLINE int navmesh_bit(int a, int b)
2735 return (a & (1 << b)) >> b;
2738 BM_INLINE void navmesh_intToCol(int i, float col[3])
2740 int r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2741 int g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2742 int b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2743 col[0] = 1 - r*63.0f/255.0f;
2744 col[1] = 1 - g*63.0f/255.0f;
2745 col[2] = 1 - b*63.0f/255.0f;
2748 static void navmesh_drawColored(DerivedMesh *dm)
2751 MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2752 MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2753 int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2760 //UI_ThemeColor(TH_WIRE);
2761 glDisable(GL_LIGHTING);
2763 dm->drawEdges(dm, 0, 1);
2765 glEnable(GL_LIGHTING);*/
2767 glDisable(GL_LIGHTING);
2768 /* if(GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2769 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2770 //glShadeModel(GL_SMOOTH);
2771 glBegin(glmode = GL_QUADS);
2772 for(a = 0; a < dm->numTessFaceData; a++, mface++) {
2773 int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2774 int pi = polygonIdx[a];
2779 navmesh_intToCol(pi, col);
2782 if(new_glmode != glmode) {
2784 glBegin(glmode = new_glmode);
2787 glVertex3fv(mvert[mface->v1].co);
2788 glVertex3fv(mvert[mface->v2].co);
2789 glVertex3fv(mvert[mface->v3].co);
2791 glVertex3fv(mvert[mface->v4].co);
2796 glEnable(GL_LIGHTING);
2799 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2800 DMSetDrawOptionsTex setDrawOptions,
2801 DMCompareDrawOptions compareDrawOptions,
2804 (void) setDrawOptions;
2805 (void) compareDrawOptions;
2808 navmesh_drawColored(dm);
2811 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2812 float (*partial_redraw_planes)[4],
2813 int UNUSED(fast), DMSetMaterial setMaterial)
2815 (void) partial_redraw_planes;
2818 //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2819 navmesh_drawColored(dm);
2822 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2824 DerivedMesh *result;
2825 int maxFaces = dm->getNumPolys(dm);
2827 int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2829 unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2830 int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2833 result = CDDM_copy(dm);
2834 if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2835 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2836 if (sourceRecastData) {
2837 CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2838 sourceRecastData, maxFaces, "recastData");
2841 recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2843 /* note: This is not good design! - really should not be doing this */
2844 result->drawFacesTex = navmesh_DM_drawFacesTex;
2845 result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2849 res = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2850 &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2855 /* invalidate concave polygon */
2856 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2857 unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2858 if (!polyIsConvex(poly, vertsPerPoly, verts)) {
2859 /* set negative polygon idx to all faces */
2860 unsigned short *dmesh = &dmeshes[4*polyIdx];
2861 unsigned short tbase = dmesh[2];
2862 unsigned short tnum = dmesh[3];
2865 for (ti=0; ti<tnum; ti++) {
2866 unsigned short triidx = dtrisToTrisMap[tbase+ti];
2867 unsigned short faceidx = trisToFacesMap[triidx];
2868 if (recastData[faceidx] > 0) {
2869 recastData[faceidx] = -recastData[faceidx];
2876 printf("Error during creation polygon infos\n");
2888 if (dtrisToPolysMap!=NULL)
2889 MEM_freeN(dtrisToPolysMap);
2890 if (dtrisToTrisMap!=NULL)
2891 MEM_freeN(dtrisToTrisMap);
2892 if (trisToFacesMap!=NULL)
2893 MEM_freeN(trisToFacesMap);
2898 #endif /* WITH_GAMEENGINE */
2900 /* --- NAVMESH (end) --- */
2903 void DM_init_origspace(DerivedMesh *dm)
2905 static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
2907 OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
2909 const int numpoly = dm->getNumPolys(dm);
2910 // const int numloop = dm->getNumLoops(dm);
2911 MPoly *mp = dm->getPolyArray(dm);
2914 for (i = 0; i < numpoly; i++, mp++) {
2915 /* only quads/tri's for now */
2916 if (mp->totloop == 3 || mp->totloop == 4) {
2917 lof = lof_array + mp->loopstart;
2918 for (j = 0; j < mp->totloop; j++, lof++) {
2919 copy_v2_v2(lof->uv, default_osf[j]);
2927 /* derivedmesh info printing function,
2928 * to help track down differences DM output */
2931 #include "BLI_dynstr.h"
2933 static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
2937 for (type = 0; type < CD_NUMTYPES; type++) {
2938 /* note: doesnt account for multiple layers */
2939 void *pt = getElemDataArray(dm, type);
2941 const char *name = CustomData_layertype_name(type);
2942 const int size = CustomData_sizeof(type);
2943 const char *structname;
2945 CustomData_file_write_info(type, &structname, &structnum);
2946 BLI_dynstr_appendf(dynstr,
2947 " dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
2948 name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
2953 char *DM_debug_info(DerivedMesh *dm)
2955 DynStr *dynstr= BLI_dynstr_new();
2959 BLI_dynstr_appendf(dynstr, "{\n");
2960 BLI_dynstr_appendf(dynstr, " 'ptr': '%p',\n", (void *)dm);
2962 case DM_TYPE_CDDM: tstr = "DM_TYPE_CDDM"; break;
2963 case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH"; break;
2964 case DM_TYPE_CCGDM: tstr = "DM_TYPE_CCGDM"; break;
2965 default: tstr = "UNKNOWN"; break;
2967 BLI_dynstr_appendf(dynstr, " 'type': '%s',\n", tstr);
2968 BLI_dynstr_appendf(dynstr, " 'numVertData': %d,\n", dm->numVertData);
2969 BLI_dynstr_appendf(dynstr, " 'numEdgeData': %d,\n", dm->numEdgeData);
2970 BLI_dynstr_appendf(dynstr, " 'numTessFaceData': %d,\n", dm->numTessFaceData);
2971 BLI_dynstr_appendf(dynstr, " 'numPolyData': %d,\n", dm->numPolyData);
2972 BLI_dynstr_appendf(dynstr, " 'deformedOnly': %d,\n", dm->deformedOnly);
2974 BLI_dynstr_appendf(dynstr, " 'vertexLayers': (\n");
2975 dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
2976 BLI_dynstr_appendf(dynstr, " ),\n");
2978 BLI_dynstr_appendf(dynstr, " 'loopLayers': (\n");
2979 dm_debug_info_layers(dynstr, dm, DM_get_loop_data_layer);
2980 BLI_dynstr_appendf(dynstr, " ),\n");
2982 BLI_dynstr_appendf(dynstr, " 'edgeLayers': (\n");
2983 dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
2984 BLI_dynstr_appendf(dynstr, " ),\n");
2986 BLI_dynstr_appendf(dynstr, " 'tessFaceLayers': (\n");
2987 dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
2988 BLI_dynstr_appendf(dynstr, " ),\n");
2990 BLI_dynstr_appendf(dynstr, " 'polyLayers': (\n");
2991 dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
2992 BLI_dynstr_appendf(dynstr, " ),\n");
2994 BLI_dynstr_appendf(dynstr, "}\n");
2996 ret = BLI_dynstr_get_cstring(dynstr);
2997 BLI_dynstr_free(dynstr);
3001 void DM_debug_print(DerivedMesh *dm)
3003 char *str = DM_debug_info(dm);