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_material_types.h"
41 #include "DNA_mesh_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_bitmap.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_linklist.h"
52 #include "BKE_cdderivedmesh.h"
53 #include "BKE_editmesh.h"
55 #include "BKE_material.h"
56 #include "BKE_modifier.h"
58 #include "BKE_mesh_mapping.h"
59 #include "BKE_object.h"
60 #include "BKE_object_deform.h"
61 #include "BKE_paint.h"
62 #include "BKE_texture.h"
63 #include "BKE_multires.h"
64 #include "BKE_bvhutils.h"
65 #include "BKE_deform.h"
66 #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */
68 #ifdef WITH_GAMEENGINE
69 #include "BKE_navmesh_conversion.h"
70 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
73 #include "BLI_sys_types.h" /* for intptr_t support */
75 #include "GPU_buffers.h"
76 #include "GPU_extensions.h"
79 /* very slow! enable for testing only! */
80 //#define USE_MODIFIER_VALIDATE
82 #ifdef USE_MODIFIER_VALIDATE
83 # define ASSERT_IS_VALID_DM(dm) (BLI_assert((dm == NULL) || (DM_is_valid(dm) == true)))
85 # define ASSERT_IS_VALID_DM(dm)
88 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
89 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
92 /* -------------------------------------------------------------------- */
94 static MVert *dm_getVertArray(DerivedMesh *dm)
96 MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
99 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
100 dm->getNumVerts(dm));
101 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
102 dm->copyVertArray(dm, mvert);
108 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
110 MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
113 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
114 dm->getNumEdges(dm));
115 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
116 dm->copyEdgeArray(dm, medge);
122 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
124 MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
127 int numTessFaces = dm->getNumTessFaces(dm);
130 /* Do not add layer if there's no elements in it, this leads to issues later when
131 * this layer is needed with non-zero size, but currently CD stuff does not check
132 * for requested layer size on creation and just returns layer which was previously
137 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
138 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
139 dm->copyTessFaceArray(dm, mface);
145 static MLoop *dm_getLoopArray(DerivedMesh *dm)
147 MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
150 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
151 dm->getNumLoops(dm));
152 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
153 dm->copyLoopArray(dm, mloop);
159 static MPoly *dm_getPolyArray(DerivedMesh *dm)
161 MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
164 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
165 dm->getNumPolys(dm));
166 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
167 dm->copyPolyArray(dm, mpoly);
173 static MVert *dm_dupVertArray(DerivedMesh *dm)
175 MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm),
176 "dm_dupVertArray tmp");
178 if (tmp) dm->copyVertArray(dm, tmp);
183 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
185 MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm),
186 "dm_dupEdgeArray tmp");
188 if (tmp) dm->copyEdgeArray(dm, tmp);
193 static MFace *dm_dupFaceArray(DerivedMesh *dm)
195 MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
196 "dm_dupFaceArray tmp");
198 if (tmp) dm->copyTessFaceArray(dm, tmp);
203 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
205 MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm),
206 "dm_dupLoopArray tmp");
208 if (tmp) dm->copyLoopArray(dm, tmp);
213 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
215 MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm),
216 "dm_dupPolyArray tmp");
218 if (tmp) dm->copyPolyArray(dm, tmp);
223 static CustomData *dm_getVertCData(DerivedMesh *dm)
225 return &dm->vertData;
228 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
230 return &dm->edgeData;
233 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
235 return &dm->faceData;
238 static CustomData *dm_getLoopCData(DerivedMesh *dm)
240 return &dm->loopData;
243 static CustomData *dm_getPolyCData(DerivedMesh *dm)
245 return &dm->polyData;
248 void DM_init_funcs(DerivedMesh *dm)
250 /* default function implementations */
251 dm->getVertArray = dm_getVertArray;
252 dm->getEdgeArray = dm_getEdgeArray;
253 dm->getTessFaceArray = dm_getTessFaceArray;
254 dm->getLoopArray = dm_getLoopArray;
255 dm->getPolyArray = dm_getPolyArray;
256 dm->dupVertArray = dm_dupVertArray;
257 dm->dupEdgeArray = dm_dupEdgeArray;
258 dm->dupTessFaceArray = dm_dupFaceArray;
259 dm->dupLoopArray = dm_dupLoopArray;
260 dm->dupPolyArray = dm_dupPolyArray;
262 dm->getVertDataLayout = dm_getVertCData;
263 dm->getEdgeDataLayout = dm_getEdgeCData;
264 dm->getTessFaceDataLayout = dm_getTessFaceCData;
265 dm->getLoopDataLayout = dm_getLoopCData;
266 dm->getPolyDataLayout = dm_getPolyCData;
268 dm->getVertData = DM_get_vert_data;
269 dm->getEdgeData = DM_get_edge_data;
270 dm->getTessFaceData = DM_get_tessface_data;
271 dm->getPolyData = DM_get_poly_data;
272 dm->getVertDataArray = DM_get_vert_data_layer;
273 dm->getEdgeDataArray = DM_get_edge_data_layer;
274 dm->getTessFaceDataArray = DM_get_tessface_data_layer;
275 dm->getPolyDataArray = DM_get_poly_data_layer;
276 dm->getLoopDataArray = DM_get_loop_data_layer;
278 bvhcache_init(&dm->bvhCache);
281 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
282 int numTessFaces, int numLoops, int numPolys)
285 dm->numVertData = numVerts;
286 dm->numEdgeData = numEdges;
287 dm->numTessFaceData = numTessFaces;
288 dm->numLoopData = numLoops;
289 dm->numPolyData = numPolys;
294 dm->auto_bump_scale = -1.0f;
297 /* don't use CustomData_reset(...); because we dont want to touch customdata */
298 fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1);
299 fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1);
300 fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1);
301 fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1);
302 fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1);
305 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
306 int numVerts, int numEdges, int numTessFaces,
307 int numLoops, int numPolys)
309 CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
310 CD_CALLOC, numVerts);
311 CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
312 CD_CALLOC, numEdges);
313 CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
314 CD_CALLOC, numTessFaces);
315 CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
316 CD_CALLOC, numLoops);
317 CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
318 CD_CALLOC, numPolys);
320 dm->cd_flag = source->cd_flag;
323 dm->numVertData = numVerts;
324 dm->numEdgeData = numEdges;
325 dm->numTessFaceData = numTessFaces;
326 dm->numLoopData = numLoops;
327 dm->numPolyData = numPolys;
335 int DM_release(DerivedMesh *dm)
338 bvhcache_free(&dm->bvhCache);
339 GPU_drawobject_free(dm);
340 CustomData_free(&dm->vertData, dm->numVertData);
341 CustomData_free(&dm->edgeData, dm->numEdgeData);
342 CustomData_free(&dm->faceData, dm->numTessFaceData);
343 CustomData_free(&dm->loopData, dm->numLoopData);
344 CustomData_free(&dm->polyData, dm->numPolyData);
355 CustomData_free_temporary(&dm->vertData, dm->numVertData);
356 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
357 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
358 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
359 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
365 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
367 CustomData_free(&target->loopData, source->numLoopData);
368 CustomData_free(&target->polyData, source->numPolyData);
370 CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
371 CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
373 target->numLoopData = source->numLoopData;
374 target->numPolyData = source->numPolyData;
376 if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
380 mloop = source->dupLoopArray(source);
381 mpoly = source->dupPolyArray(source);
382 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
383 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
387 void DM_ensure_normals(DerivedMesh *dm)
389 if (dm->dirty & DM_DIRTY_NORMALS) {
392 BLI_assert((dm->dirty & DM_DIRTY_NORMALS) == 0);
395 static void DM_calc_loop_normals(DerivedMesh *dm, const bool use_split_normals, float split_angle)
397 dm->calcLoopNormals(dm, use_split_normals, split_angle);
398 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
401 /* note: until all modifiers can take MPoly's as input,
402 * use this at the start of modifiers */
403 void DM_ensure_tessface(DerivedMesh *dm)
405 const int numTessFaces = dm->getNumTessFaces(dm);
406 const int numPolys = dm->getNumPolys(dm);
408 if ((numTessFaces == 0) && (numPolys != 0)) {
409 dm->recalcTessellation(dm);
411 if (dm->getNumTessFaces(dm) != 0) {
412 /* printf("info %s: polys -> ngons calculated\n", __func__); */
415 printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
416 __func__, numPolys, dm->type);
420 else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) {
421 BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX) || numTessFaces == 0);
422 DM_update_tessface_data(dm);
425 dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
428 /* Update tessface CD data from loop/poly ones. Needed when not retessellating after modstack evaluation. */
429 /* NOTE: Assumes dm has valid tessellated data! */
430 void DM_update_tessface_data(DerivedMesh *dm)
432 MFace *mf, *mface = dm->getTessFaceArray(dm);
433 MPoly *mp = dm->getPolyArray(dm);
434 MLoop *ml = dm->getLoopArray(dm);
436 CustomData *fdata = dm->getTessFaceDataLayout(dm);
437 CustomData *pdata = dm->getPolyDataLayout(dm);
438 CustomData *ldata = dm->getLoopDataLayout(dm);
440 const int totface = dm->getNumTessFaces(dm);
443 int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX);
444 unsigned int (*loopindex)[4];
446 /* Should never occure, but better abort than segfault! */
450 CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
452 if (CustomData_has_layer(fdata, CD_MTFACE) ||
453 CustomData_has_layer(fdata, CD_MCOL) ||
454 CustomData_has_layer(fdata, CD_PREVIEW_MCOL) ||
455 CustomData_has_layer(fdata, CD_ORIGSPACE) ||
456 CustomData_has_layer(fdata, CD_TESSLOOPNORMAL))
458 loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__);
460 for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
461 const int mf_len = mf->v4 ? 4 : 3;
462 unsigned int *ml_idx = loopindex[mf_idx];
465 /* Find out loop indices. */
466 /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */
467 for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
468 const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v);
476 /* NOTE: quad detection issue - forth vertidx vs forth loopidx:
477 * Here, our tfaces' forth vertex index is never 0 for a quad. However, we know our forth loop index may be
478 * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code).
479 * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test.
481 BKE_mesh_loops_to_tessdata(fdata, ldata, pdata, mface, polyindex, loopindex, totface);
483 MEM_freeN(loopindex);
486 if (G.debug & G_DEBUG)
487 printf("%s: Updated tessellated customdata of dm %p\n", __func__, dm);
489 dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
492 void DM_update_materials(DerivedMesh *dm, Object *ob)
494 int i, totmat = ob->totcol + 1; /* materials start from 1, default material is 0 */
497 /* invalidate old materials */
501 dm->mat = MEM_callocN(totmat * sizeof(*dm->mat), "DerivedMesh.mat");
503 /* we leave last material as empty - rationale here is being able to index
504 * the materials by using the mf->mat_nr directly and leaving the last
505 * material as NULL in case no materials exist on mesh, so indexing will not fail */
506 for (i = 0; i < totmat - 1; i++) {
507 dm->mat[i] = give_current_material(ob, i + 1);
511 MTFace *DM_paint_uvlayer_active_get(DerivedMesh *dm, int mat_nr)
515 BLI_assert(mat_nr < dm->totmat);
517 if (dm->mat[mat_nr] && dm->mat[mat_nr]->texpaintslot &&
518 dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname)
520 tf_base = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
521 dm->mat[mat_nr]->texpaintslot[dm->mat[mat_nr]->paint_active_slot].uvname);
522 /* This can fail if we have changed the name in the UV layer list and have assigned the old name in the material
525 tf_base = CustomData_get_layer(&dm->faceData, CD_MTFACE);
528 tf_base = CustomData_get_layer(&dm->faceData, CD_MTFACE);
534 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool take_ownership)
536 /* dm might depend on me, so we need to do everything with a local copy */
538 int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
539 int did_shapekeys = 0;
540 int alloctype = CD_DUPLICATE;
542 if (take_ownership && dm->type == DM_TYPE_CDDM && dm->needsFree) {
543 bool has_any_referenced_layers =
544 CustomData_has_referenced(&dm->vertData) ||
545 CustomData_has_referenced(&dm->edgeData) ||
546 CustomData_has_referenced(&dm->loopData) ||
547 CustomData_has_referenced(&dm->faceData) ||
548 CustomData_has_referenced(&dm->polyData);
549 if (!has_any_referenced_layers) {
550 alloctype = CD_ASSIGN;
554 CustomData_reset(&tmp.vdata);
555 CustomData_reset(&tmp.edata);
556 CustomData_reset(&tmp.fdata);
557 CustomData_reset(&tmp.ldata);
558 CustomData_reset(&tmp.pdata);
560 DM_ensure_normals(dm);
562 totvert = tmp.totvert = dm->getNumVerts(dm);
563 totedge = tmp.totedge = dm->getNumEdges(dm);
564 totloop = tmp.totloop = dm->getNumLoops(dm);
565 totpoly = tmp.totpoly = dm->getNumPolys(dm);
568 CustomData_copy(&dm->vertData, &tmp.vdata, mask, alloctype, totvert);
569 CustomData_copy(&dm->edgeData, &tmp.edata, mask, alloctype, totedge);
570 CustomData_copy(&dm->loopData, &tmp.ldata, mask, alloctype, totloop);
571 CustomData_copy(&dm->polyData, &tmp.pdata, mask, alloctype, totpoly);
572 tmp.cd_flag = dm->cd_flag;
574 if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
579 kb = BLI_findlink(&me->key->block, ob->shapenr - 1);
584 printf("%s: error - could not find active shapekey %d!\n",
585 __func__, ob->shapenr - 1);
591 /* if no object, set to INT_MAX so we don't mess up any shapekey layers */
595 shapekey_layers_to_keyblocks(dm, me, uid);
599 /* copy texture space */
601 BKE_mesh_texspace_copy_from_object(&tmp, ob);
604 /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
605 * we set them here in case they are missing */
606 if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) {
607 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN,
608 (alloctype == CD_ASSIGN) ? dm->getVertArray(dm) : dm->dupVertArray(dm),
611 if (!CustomData_has_layer(&tmp.edata, CD_MEDGE)) {
612 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN,
613 (alloctype == CD_ASSIGN) ? dm->getEdgeArray(dm) : dm->dupEdgeArray(dm),
616 if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
617 tmp.mloop = (alloctype == CD_ASSIGN) ? dm->getLoopArray(dm) : dm->dupLoopArray(dm);
618 tmp.mpoly = (alloctype == CD_ASSIGN) ? dm->getPolyArray(dm) : dm->dupPolyArray(dm);
620 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
621 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
624 /* object had got displacement layer, should copy this layer to save sculpted data */
625 /* NOTE: maybe some other layers should be copied? nazgul */
626 if (CustomData_has_layer(&me->ldata, CD_MDISPS)) {
627 if (totloop == me->totloop) {
628 MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
629 CustomData_add_layer(&tmp.ldata, CD_MDISPS, alloctype, mdisps, totloop);
633 /* yes, must be before _and_ after tessellate */
634 BKE_mesh_update_customdata_pointers(&tmp, false);
636 /* since 2.65 caller must do! */
637 // BKE_mesh_tessface_calc(&tmp);
639 CustomData_free(&me->vdata, me->totvert);
640 CustomData_free(&me->edata, me->totedge);
641 CustomData_free(&me->fdata, me->totface);
642 CustomData_free(&me->ldata, me->totloop);
643 CustomData_free(&me->pdata, me->totpoly);
645 /* ok, this should now use new CD shapekey data,
646 * which should be fed through the modifier
648 if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
649 printf("%s: YEEK! this should be recoded! Shape key loss!: ID '%s'\n", __func__, tmp.id.name);
650 if (tmp.key) tmp.key->id.us--;
654 /* Clear selection history */
658 MEM_freeN(me->mselect);
661 /* skip the listbase */
662 MEMCPY_STRUCT_OFS(me, &tmp, id.prev);
664 if (take_ownership) {
665 if (alloctype == CD_ASSIGN) {
666 CustomData_free_typemask(&dm->vertData, dm->numVertData, ~mask);
667 CustomData_free_typemask(&dm->edgeData, dm->numEdgeData, ~mask);
668 CustomData_free_typemask(&dm->loopData, dm->numLoopData, ~mask);
669 CustomData_free_typemask(&dm->polyData, dm->numPolyData, ~mask);
675 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
677 int a, totvert = dm->getNumVerts(dm);
681 if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) return;
683 if (kb->data) MEM_freeN(kb->data);
684 kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data");
685 kb->totelem = totvert;
688 mvert = dm->getVertDataArray(dm, CD_MVERT);
690 for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) {
691 copy_v3_v3(fp, mvert->co);
695 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
697 CustomData_set_only_copy(&dm->vertData, mask);
698 CustomData_set_only_copy(&dm->edgeData, mask);
699 CustomData_set_only_copy(&dm->faceData, mask);
700 /* this wasn't in 2.63 and is disabled for 2.64 because it gives problems with
701 * weight paint mode when there are modifiers applied, needs further investigation,
702 * see replies to r50969, Campbell */
704 CustomData_set_only_copy(&dm->loopData, mask);
705 CustomData_set_only_copy(&dm->polyData, mask);
709 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
711 CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
714 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
716 CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
719 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
721 CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
724 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
726 CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
729 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
731 CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
734 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
736 BLI_assert(index >= 0 && index < dm->getNumVerts(dm));
737 return CustomData_get(&dm->vertData, index, type);
740 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
742 BLI_assert(index >= 0 && index < dm->getNumEdges(dm));
743 return CustomData_get(&dm->edgeData, index, type);
746 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
748 BLI_assert(index >= 0 && index < dm->getNumTessFaces(dm));
749 return CustomData_get(&dm->faceData, index, type);
752 void *DM_get_poly_data(DerivedMesh *dm, int index, int type)
754 BLI_assert(index >= 0 && index < dm->getNumPolys(dm));
755 return CustomData_get(&dm->polyData, index, type);
759 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
761 if (type == CD_MVERT)
762 return dm->getVertArray(dm);
764 return CustomData_get_layer(&dm->vertData, type);
767 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
769 if (type == CD_MEDGE)
770 return dm->getEdgeArray(dm);
772 return CustomData_get_layer(&dm->edgeData, type);
775 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
777 if (type == CD_MFACE)
778 return dm->getTessFaceArray(dm);
780 return CustomData_get_layer(&dm->faceData, type);
783 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
785 return CustomData_get_layer(&dm->polyData, type);
788 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
790 return CustomData_get_layer(&dm->loopData, type);
793 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
795 CustomData_set(&dm->vertData, index, type, data);
798 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
800 CustomData_set(&dm->edgeData, index, type, data);
803 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
805 CustomData_set(&dm->faceData, index, type, data);
808 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
809 int source_index, int dest_index, int count)
811 CustomData_copy_data(&source->vertData, &dest->vertData,
812 source_index, dest_index, count);
815 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
816 int source_index, int dest_index, int count)
818 CustomData_copy_data(&source->edgeData, &dest->edgeData,
819 source_index, dest_index, count);
822 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
823 int source_index, int dest_index, int count)
825 CustomData_copy_data(&source->faceData, &dest->faceData,
826 source_index, dest_index, count);
829 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
830 int source_index, int dest_index, int count)
832 CustomData_copy_data(&source->loopData, &dest->loopData,
833 source_index, dest_index, count);
836 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
837 int source_index, int dest_index, int count)
839 CustomData_copy_data(&source->polyData, &dest->polyData,
840 source_index, dest_index, count);
843 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
845 CustomData_free_elem(&dm->vertData, index, count);
848 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
850 CustomData_free_elem(&dm->edgeData, index, count);
853 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
855 CustomData_free_elem(&dm->faceData, index, count);
858 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
860 CustomData_free_elem(&dm->loopData, index, count);
863 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
865 CustomData_free_elem(&dm->polyData, index, count);
868 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
869 int *src_indices, float *weights,
870 int count, int dest_index)
872 CustomData_interp(&source->vertData, &dest->vertData, src_indices,
873 weights, NULL, count, dest_index);
876 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
878 float *weights, EdgeVertWeight *vert_weights,
879 int count, int dest_index)
881 CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
882 weights, (float *)vert_weights, count, dest_index);
885 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
887 float *weights, FaceVertWeight *vert_weights,
888 int count, int dest_index)
890 CustomData_interp(&source->faceData, &dest->faceData, src_indices,
891 weights, (float *)vert_weights, count, dest_index);
894 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
896 CustomData_swap(&dm->faceData, index, corner_indices);
899 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
901 float *weights, int count, int dest_index)
903 CustomData_interp(&source->loopData, &dest->loopData, src_indices,
904 weights, NULL, count, dest_index);
907 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
909 float *weights, int count, int dest_index)
911 CustomData_interp(&source->polyData, &dest->polyData, src_indices,
912 weights, NULL, count, dest_index);
916 DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3])
918 DerivedMesh *dm = CDDM_from_mesh(me);
924 CDDM_apply_vert_coords(dm, vertCos);
930 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob,
931 ModifierData *md, int build_shapekey_layers)
934 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
940 if (!(md->mode & eModifierMode_Realtime)) return NULL;
941 if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
943 if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) {
944 BKE_keyblock_convert_to_mesh(kb, me);
947 if (mti->type == eModifierTypeType_OnlyDeform) {
949 float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts);
951 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, 0);
952 dm = mesh_create_derived(me, deformedVerts);
954 if (build_shapekey_layers)
955 add_shapekey_layers(dm, me, ob);
957 MEM_freeN(deformedVerts);
960 DerivedMesh *tdm = mesh_create_derived(me, NULL);
962 if (build_shapekey_layers)
963 add_shapekey_layers(tdm, me, ob);
965 dm = modwrap_applyModifier(md, ob, tdm, 0);
966 ASSERT_IS_VALID_DM(dm);
968 if (tdm != dm) tdm->release(tdm);
974 static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
981 /* these may not really be the orco's, but it's only for preview.
982 * could be solver better once, but isn't simple */
984 orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
986 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
987 copy_v3_v3(orco[i], eve->co);
993 /* orco custom data layer */
994 static float (*get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free))[3]
998 if (layer == CD_ORCO) {
999 /* get original coordinates */
1003 return get_editbmesh_orco_verts(em);
1005 return BKE_mesh_orco_verts_get(ob);
1007 else if (layer == CD_CLOTH_ORCO) {
1008 /* apply shape key for cloth, this should really be solved
1009 * by a more flexible customdata system, but not simple */
1011 ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
1012 KeyBlock *kb = BKE_keyblock_from_key(BKE_key_from_object(ob), clmd->sim_parms->shapekey_rest);
1024 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
1030 if (em) dm = CDDM_from_editbmesh(em, false, false);
1031 else dm = CDDM_from_mesh(me);
1033 orco = get_orco_coords_dm(ob, em, layer, &free);
1036 CDDM_apply_vert_coords(dm, orco);
1037 if (free) MEM_freeN(orco);
1043 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
1044 DerivedMesh *orcodm, int layer)
1046 float (*orco)[3], (*layerorco)[3];
1049 totvert = dm->getNumVerts(dm);
1052 orco = MEM_callocN(sizeof(float[3]) * totvert, "dm orco");
1055 if (orcodm->getNumVerts(orcodm) == totvert)
1056 orcodm->getVertCos(orcodm, orco);
1058 dm->getVertCos(dm, orco);
1061 orco = get_orco_coords_dm(ob, em, layer, &free);
1064 if (layer == CD_ORCO)
1065 BKE_mesh_orco_verts_transform(ob->data, orco, totvert, 0);
1067 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
1068 DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
1069 layerorco = DM_get_vert_data_layer(dm, layer);
1072 memcpy(layerorco, orco, sizeof(float) * 3 * totvert);
1073 if (free) MEM_freeN(orco);
1077 /* weight paint colors */
1079 /* Something of a hack, at the moment deal with weightpaint
1080 * by tucking into colors during modifier eval, only in
1081 * wpaint mode. Works ok but need to make sure recalc
1082 * happens on enter/exit wpaint.
1085 void weight_to_rgb(float r_rgb[3], const float weight)
1087 const float blend = ((weight / 2.0f) + 0.5f);
1089 if (weight <= 0.25f) { /* blue->cyan */
1091 r_rgb[1] = blend * weight * 4.0f;
1094 else if (weight <= 0.50f) { /* cyan->green */
1097 r_rgb[2] = blend * (1.0f - ((weight - 0.25f) * 4.0f));
1099 else if (weight <= 0.75f) { /* green->yellow */
1100 r_rgb[0] = blend * ((weight - 0.50f) * 4.0f);
1104 else if (weight <= 1.0f) { /* yellow->red */
1106 r_rgb[1] = blend * (1.0f - ((weight - 0.75f) * 4.0f));
1110 /* exceptional value, unclamped or nan,
1111 * avoid uninitialized memory use */
1118 /* draw_flag's for calc_weightpaint_vert_color */
1120 /* only one of these should be set, keep first (for easy bit-shifting) */
1121 CALC_WP_GROUP_USER_ACTIVE = (1 << 1),
1122 CALC_WP_GROUP_USER_ALL = (1 << 2),
1124 CALC_WP_MULTIPAINT = (1 << 3),
1125 CALC_WP_AUTO_NORMALIZE = (1 << 4)
1128 typedef struct DMWeightColorInfo {
1129 const ColorBand *coba;
1130 const char *alert_color;
1131 } DMWeightColorInfo;
1134 static int dm_drawflag_calc(const ToolSettings *ts)
1136 return ((ts->multipaint ? CALC_WP_MULTIPAINT :
1137 /* CALC_WP_GROUP_USER_ACTIVE or CALC_WP_GROUP_USER_ALL*/
1138 (1 << ts->weightuser)) |
1139 (ts->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1142 static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcinfo, const float input)
1146 if (dm_wcinfo && dm_wcinfo->coba) {
1147 do_colorband(dm_wcinfo->coba, input, colf);
1150 weight_to_rgb(colf, input);
1153 /* don't use rgb_float_to_uchar() here because
1154 * the resulting float doesn't need 0-1 clamp check */
1155 r_col[0] = (unsigned char)(colf[0] * 255.0f);
1156 r_col[1] = (unsigned char)(colf[1] * 255.0f);
1157 r_col[2] = (unsigned char)(colf[2] * 255.0f);
1162 static void calc_weightpaint_vert_color(
1163 unsigned char r_col[4],
1164 const MDeformVert *dv,
1165 DMWeightColorInfo *dm_wcinfo,
1166 const int defbase_tot, const int defbase_act,
1167 const bool *defbase_sel, const int defbase_sel_tot,
1168 const int draw_flag)
1172 bool show_alert_color = false;
1174 if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1175 /* Multi-Paint feature */
1176 bool was_a_nonzero = false;
1179 const MDeformWeight *dw = dv->dw;
1180 for (i = dv->totweight; i != 0; i--, dw++) {
1181 /* in multipaint, get the average if auto normalize is inactive
1182 * get the sum if it is active */
1183 if (dw->def_nr < defbase_tot) {
1184 if (defbase_sel[dw->def_nr]) {
1186 input += dw->weight;
1187 was_a_nonzero = true;
1193 /* make it black if the selected groups have no weight on a vertex */
1194 if (was_a_nonzero == false) {
1195 show_alert_color = true;
1197 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == false) {
1198 input /= defbase_sel_tot; /* get the average */
1202 /* default, non tricky behavior */
1203 input = defvert_find_weight(dv, defbase_act);
1205 if (draw_flag & CALC_WP_GROUP_USER_ACTIVE) {
1206 if (input == 0.0f) {
1207 show_alert_color = true;
1210 else if (draw_flag & CALC_WP_GROUP_USER_ALL) {
1211 if (input == 0.0f) {
1212 show_alert_color = defvert_is_weight_zero(dv, defbase_tot);
1217 if (show_alert_color == false) {
1218 CLAMP(input, 0.0f, 1.0f);
1219 weightpaint_color(r_col, dm_wcinfo, input);
1222 copy_v3_v3_char((char *)r_col, dm_wcinfo->alert_color);
1227 static DMWeightColorInfo G_dm_wcinfo;
1229 void vDM_ColorBand_store(const ColorBand *coba, const char alert_color[4])
1231 G_dm_wcinfo.coba = coba;
1232 G_dm_wcinfo.alert_color = alert_color;
1235 /* return an array of vertex weight colors, caller must free.
1237 * note that we could save some memory and allocate RGB only but then we'd need to
1238 * re-arrange the colors when copying to the face since MCol has odd ordering,
1239 * so leave this as is - campbell */
1240 static void calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, DMWeightColorInfo *dm_wcinfo,
1241 unsigned char (*r_wtcol_v)[4])
1243 MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1244 int numVerts = dm->getNumVerts(dm);
1247 unsigned char (*wc)[4] = r_wtcol_v;
1250 /* variables for multipaint */
1251 const int defbase_tot = BLI_listbase_count(&ob->defbase);
1252 const int defbase_act = ob->actdef - 1;
1254 int defbase_sel_tot = 0;
1255 bool *defbase_sel = NULL;
1257 if (draw_flag & CALC_WP_MULTIPAINT) {
1258 defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_sel_tot);
1261 for (i = numVerts; i != 0; i--, wc++, dv++) {
1262 calc_weightpaint_vert_color((unsigned char *)wc, dv, dm_wcinfo, defbase_tot, defbase_act, defbase_sel, defbase_sel_tot, draw_flag);
1266 MEM_freeN(defbase_sel);
1270 unsigned char col[4];
1271 if (draw_flag & (CALC_WP_GROUP_USER_ACTIVE | CALC_WP_GROUP_USER_ALL)) {
1272 copy_v3_v3_char((char *)col, dm_wcinfo->alert_color);
1276 weightpaint_color(col, dm_wcinfo, 0.0f);
1278 fill_vn_i((int *)r_wtcol_v, numVerts, *((int *)col));
1282 /* return an array of vertex weight colors from given weights, caller must free.
1284 * note that we could save some memory and allocate RGB only but then we'd need to
1285 * re-arrange the colors when copying to the face since MCol has odd ordering,
1286 * so leave this as is - campbell */
1287 static void calc_colors_from_weights_array(const int num, const float *weights,
1288 unsigned char (*r_wtcol_v)[4])
1290 unsigned char (*wc)[4] = r_wtcol_v;
1293 for (i = 0; i < num; i++, wc++, weights++) {
1294 weightpaint_color((unsigned char *)wc, NULL, *weights);
1298 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1299 float *weights, int num, const int *indices)
1301 BMEditMesh *em = (dm->type == DM_TYPE_EDITBMESH) ? BKE_editmesh_from_object(ob) : NULL;
1302 unsigned char (*wtcol_v)[4];
1303 int numVerts = dm->getNumVerts(dm);
1307 BKE_editmesh_color_ensure(em, BM_VERT);
1308 wtcol_v = em->derivedVertColor;
1311 wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__);
1314 /* Weights are given by caller. */
1317 /* If indices is not NULL, it means we do not have weights for all vertices,
1318 * so we must create them (and set them to zero)... */
1320 w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
1323 w[indices[i]] = weights[i];
1326 /* Convert float weights to colors. */
1327 calc_colors_from_weights_array(numVerts, w, wtcol_v);
1333 /* No weights given, take them from active vgroup(s). */
1334 calc_weightpaint_vert_array(ob, dm, draw_flag, &G_dm_wcinfo, wtcol_v);
1337 if (dm->type == DM_TYPE_EDITBMESH) {
1338 /* editmesh draw function checks specifically for this */
1341 const int dm_totpoly = dm->getNumPolys(dm);
1342 const int dm_totloop = dm->getNumLoops(dm);
1343 unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1344 MLoop *mloop = dm->getLoopArray(dm), *ml;
1345 MPoly *mp = dm->getPolyArray(dm);
1349 /* now add to loops, so the data can be passed through the modifier stack */
1350 /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1352 wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__);
1353 CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
1357 for (i = 0; i < dm_totpoly; i++, mp++) {
1358 ml = mloop + mp->loopstart;
1360 for (j = 0; j < mp->totloop; j++, ml++, l_index++) {
1361 copy_v4_v4_char((char *)&wtcol_l[l_index],
1362 (char *)&wtcol_v[ml->v]);
1367 dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1371 static void DM_update_statvis_color(const Scene *scene, Object *ob, DerivedMesh *dm)
1373 BMEditMesh *em = BKE_editmesh_from_object(ob);
1375 BKE_editmesh_statvis_calc(em, dm, &scene->toolsettings->statvis);
1378 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1386 tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1387 for (i = 0; i < tot; i++) {
1388 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1389 float (*cos)[3], (*kbcos)[3];
1391 for (kb = me->key->block.first; kb; kb = kb->next) {
1392 if (kb->uid == layer->uid)
1397 kb = BKE_keyblock_add(me->key, layer->name);
1398 kb->uid = layer->uid;
1402 MEM_freeN(kb->data);
1404 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1405 kb->totelem = dm->numVertData;
1407 kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
1408 if (kb->uid == actshape_uid) {
1409 MVert *mvert = dm->getVertArray(dm);
1411 for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) {
1412 copy_v3_v3(*kbcos, mvert->co);
1416 for (j = 0; j < kb->totelem; j++, cos++, kbcos++) {
1417 copy_v3_v3(*kbcos, *cos);
1422 for (kb = me->key->block.first; kb; kb = kb->next) {
1423 if (kb->totelem != dm->numVertData) {
1425 MEM_freeN(kb->data);
1427 kb->totelem = dm->numVertData;
1428 kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
1429 fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
1434 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1439 const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1444 /* ensure we can use mesh vertex count for derived mesh custom data */
1445 if (me->totvert != dm->getNumVerts(dm)) {
1447 "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1448 __func__, me->id.name + 2, me->totvert, dm->getNumVerts(dm));
1452 for (i = 0, kb = key->block.first; kb; kb = kb->next, i++) {
1456 if (me->totvert != kb->totelem) {
1458 "%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
1459 __func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
1460 array = MEM_callocN(shape_alloc_len, __func__);
1463 array = MEM_mallocN(shape_alloc_len, __func__);
1464 memcpy(array, kb->data, shape_alloc_len);
1467 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1468 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1470 dm->vertData.layers[ci].uid = kb->uid;
1475 * Called after calculating all modifiers.
1477 * \note tessfaces should already be calculated.
1479 static void dm_ensure_display_normals(DerivedMesh *dm)
1481 /* Note: dm *may* have a poly CD_NORMAL layer (generated by a modifier needing poly normals e.g.).
1482 * We do not use it here, though. And it should be tagged as temp!
1484 /* BLI_assert((CustomData_has_layer(&dm->polyData, CD_NORMAL) == false)); */
1486 if ((dm->type == DM_TYPE_CDDM) &&
1487 ((dm->dirty & DM_DIRTY_NORMALS) || CustomData_has_layer(&dm->faceData, CD_NORMAL) == false))
1489 /* if normals are dirty we want to calculate vertex normals too */
1490 CDDM_calc_normals_mapping_ex(dm, (dm->dirty & DM_DIRTY_NORMALS) ? false : true);
1493 /* new value for useDeform -1 (hack for the gameengine):
1494 * - apply only the modifier stack of the object, skipping the virtual modifiers,
1495 * - don't apply the key
1496 * - apply deform modifiers and input vertexco
1498 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1499 DerivedMesh **deform_r, DerivedMesh **final_r,
1500 int useRenderParams, int useDeform,
1501 int needMapping, CustomDataMask dataMask,
1502 int index, int useCache, int build_shapekey_layers)
1504 Mesh *me = ob->data;
1505 ModifierData *firstmd, *md, *previewmd = NULL;
1506 CDMaskLink *datamasks, *curr;
1507 /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1508 CustomDataMask mask, nextmask, previewmask = 0, append_mask = CD_MASK_ORIGINDEX;
1509 float (*deformedVerts)[3] = NULL;
1510 DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm;
1511 int numVerts = me->totvert;
1513 bool isPrevDeform = false;
1514 const bool skipVirtualArmature = (useDeform < 0);
1515 MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
1516 const bool has_multires = (mmd && mmd->sculptlvl != 0);
1517 bool multires_applied = false;
1518 const bool sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt && !useRenderParams;
1519 const bool sculpt_dyntopo = (sculpt_mode && ob->sculpt->bm) && !useRenderParams;
1520 const int draw_flag = dm_drawflag_calc(scene->toolsettings);
1522 /* Generic preview only in object mode! */
1523 const bool do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1524 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1525 const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1527 const bool do_final_wmcol = false;
1528 const bool do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1529 /* XXX Same as above... For now, only weights preview in WPaint mode. */
1530 const bool do_mod_wmcol = do_init_wmcol;
1532 const bool do_loop_normals = (me->flag & ME_AUTOSMOOTH) != 0;
1533 const float loop_normals_split_angle = me->smoothresh;
1535 VirtualModifierData virtualModifierData;
1537 ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0;
1538 ModifierApplyFlag deform_app_flags = app_flags;
1540 app_flags |= MOD_APPLY_USECACHE;
1542 deform_app_flags |= MOD_APPLY_USECACHE;
1544 if (!skipVirtualArmature) {
1545 firstmd = modifiers_getVirtualModifierList(ob, &virtualModifierData);
1548 /* game engine exception */
1549 firstmd = ob->modifiers.first;
1550 if (firstmd && firstmd->type == eModifierType_Armature)
1551 firstmd = firstmd->next;
1556 modifiers_clearErrors(ob);
1558 if (useRenderParams) required_mode = eModifierMode_Render;
1559 else required_mode = eModifierMode_Realtime;
1561 if (do_mod_wmcol || do_mod_mcol) {
1562 /* Find the last active modifier generating a preview, or NULL if none. */
1563 /* XXX Currently, DPaint modifier just ignores this.
1564 * Needs a stupid hack...
1565 * The whole "modifier preview" thing has to be (re?)designed, anyway! */
1566 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1568 /* even if the modifier doesn't need the data, to make a preview it may */
1571 previewmask = CD_MASK_MDEFORMVERT;
1576 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
1579 if (deform_r) *deform_r = NULL;
1584 deformedVerts = inputVertexCos;
1586 /* Apply all leading deforming modifiers */
1587 for (; md; md = md->next, curr = curr->next) {
1588 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1592 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1593 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1595 if (mti->type == eModifierTypeType_OnlyDeform && !sculpt_dyntopo) {
1597 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1599 modwrap_deformVerts(md, ob, NULL, deformedVerts, numVerts, deform_app_flags);
1605 /* grab modifiers until index i */
1606 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1610 /* Result of all leading deforming modifiers is cached for
1611 * places that wish to use the original mesh but with deformed
1612 * coordinates (vpaint, etc.)
1615 *deform_r = CDDM_from_mesh(me);
1617 if (build_shapekey_layers)
1618 add_shapekey_layers(dm, me, ob);
1620 if (deformedVerts) {
1621 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1626 /* default behavior for meshes */
1628 deformedVerts = inputVertexCos;
1630 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1634 /* Now apply all remaining modifiers. If useDeform is off then skip
1641 for (; md; md = md->next, curr = curr->next) {
1642 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1646 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1647 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1648 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1649 modifier_setError(md, "Modifier requires original data, bad stack position");
1653 (!has_multires || multires_applied || sculpt_dyntopo))
1655 bool unsupported = false;
1657 if (md->type == eModifierType_Multires && ((MultiresModifierData *)md)->sculptlvl == 0) {
1658 /* If multires is on level 0 skip it silently without warning message. */
1659 if (!sculpt_dyntopo)
1663 if (sculpt_dyntopo && !useRenderParams)
1666 if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1667 unsupported |= (mti->type != eModifierTypeType_OnlyDeform);
1669 unsupported |= multires_applied;
1673 modifier_setError(md, "Not supported in dyntopo");
1675 modifier_setError(md, "Not supported in sculpt mode");
1679 modifier_setError(md, "Hide, Mask and optimized display disabled");
1682 if (needMapping && !modifier_supportsMapping(md)) continue;
1683 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1685 /* add an orco layer if needed by this modifier */
1686 if (mti->requiredDataMask)
1687 mask = mti->requiredDataMask(ob, md);
1691 if (dm && (mask & CD_MASK_ORCO))
1692 add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1694 /* How to apply modifier depends on (a) what we already have as
1695 * a result of previous modifiers (could be a DerivedMesh or just
1696 * deformed vertices) and (b) what type the modifier is.
1699 if (mti->type == eModifierTypeType_OnlyDeform) {
1700 /* No existing verts to deform, need to build them. */
1701 if (!deformedVerts) {
1703 /* Deforming a derived mesh, read the vertex locations
1704 * out of the mesh and deform them. Once done with this
1705 * run of deformers verts will be written back.
1707 numVerts = dm->getNumVerts(dm);
1709 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1710 dm->getVertCos(dm, deformedVerts);
1713 deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts);
1717 /* if this is not the last modifier in the stack then recalculate the normals
1718 * to avoid giving bogus normals to the next modifier see: [#23673] */
1719 if (isPrevDeform && mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1720 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1721 if (dm && dm->type == DM_TYPE_CDDM) {
1722 CDDM_apply_vert_coords(dm, deformedVerts);
1726 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, deform_app_flags);
1731 /* determine which data layers are needed by following modifiers */
1733 nextmask = curr->next->mask;
1735 nextmask = dataMask;
1737 /* apply vertex coordinates or build a DerivedMesh as necessary */
1739 if (deformedVerts) {
1740 DerivedMesh *tdm = CDDM_copy(dm);
1744 CDDM_apply_vert_coords(dm, deformedVerts);
1748 dm = CDDM_from_mesh(me);
1749 ASSERT_IS_VALID_DM(dm);
1751 if (build_shapekey_layers)
1752 add_shapekey_layers(dm, me, ob);
1754 if (deformedVerts) {
1755 CDDM_apply_vert_coords(dm, deformedVerts);
1759 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1761 /* Constructive modifiers need to have an origindex
1762 * otherwise they wont have anywhere to copy the data from.
1764 * Also create ORIGINDEX data if any of the following modifiers
1765 * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1766 * data by using generic DM_copy_vert_data() functions.
1768 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1770 DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1771 DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1772 DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1774 #pragma omp parallel sections if (dm->numVertData + dm->numEdgeData + dm->numPolyData >= BKE_MESH_OMP_LIMIT)
1777 { range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0); }
1779 { range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0); }
1781 { range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0); }
1787 /* set the DerivedMesh to only copy needed data */
1789 /* needMapping check here fixes bug [#28112], otherwise its
1790 * possible that it wont be copied */
1791 mask |= append_mask;
1792 DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1794 /* add cloth rest shape key if need */
1795 if (mask & CD_MASK_CLOTH_ORCO)
1796 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1798 /* add an origspace layer if needed */
1799 if ((curr->mask) & CD_MASK_ORIGSPACE_MLOOP) {
1800 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1801 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1802 DM_init_origspace(dm);
1806 ndm = modwrap_applyModifier(md, ob, dm, app_flags);
1807 ASSERT_IS_VALID_DM(ndm);
1810 /* if the modifier returned a new dm, release the old one */
1811 if (dm && dm != ndm) dm->release(dm);
1815 if (deformedVerts) {
1816 if (deformedVerts != inputVertexCos)
1817 MEM_freeN(deformedVerts);
1819 deformedVerts = NULL;
1823 /* create an orco derivedmesh in parallel */
1824 if (nextmask & CD_MASK_ORCO) {
1826 orcodm = create_orco_dm(ob, me, NULL, CD_ORCO);
1828 nextmask &= ~CD_MASK_ORCO;
1829 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX |
1830 (mti->requiredDataMask ?
1831 mti->requiredDataMask(ob, md) : 0));
1833 ndm = modwrap_applyModifier(md, ob, orcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1834 ASSERT_IS_VALID_DM(ndm);
1837 /* if the modifier returned a new dm, release the old one */
1838 if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1843 /* create cloth orco derivedmesh in parallel */
1844 if (nextmask & CD_MASK_CLOTH_ORCO) {
1846 clothorcodm = create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1848 nextmask &= ~CD_MASK_CLOTH_ORCO;
1849 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1851 ndm = modwrap_applyModifier(md, ob, clothorcodm, (app_flags & ~MOD_APPLY_USECACHE) | MOD_APPLY_ORCO);
1852 ASSERT_IS_VALID_DM(ndm);
1855 /* if the modifier returned a new dm, release the old one */
1856 if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1861 /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1862 /* XXX Temp and hackish solution! */
1863 if (md->type == eModifierType_DynamicPaint)
1864 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1865 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1866 else if ((md == previewmd) && (do_mod_wmcol)) {
1867 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1868 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1872 isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
1874 /* grab modifiers until index i */
1875 if ((index >= 0) && (BLI_findindex(&ob->modifiers, md) >= index))
1878 if (sculpt_mode && md->type == eModifierType_Multires) {
1879 multires_applied = true;
1883 for (md = firstmd; md; md = md->next)
1884 modifier_freeTemporaryData(md);
1886 /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1887 * need to apply these back onto the DerivedMesh. If we have no
1888 * DerivedMesh then we need to build one.
1890 if (dm && deformedVerts) {
1891 finaldm = CDDM_copy(dm);
1895 CDDM_apply_vert_coords(finaldm, deformedVerts);
1897 #if 0 /* For later nice mod preview! */
1898 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1900 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1906 #if 0 /* For later nice mod preview! */
1907 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1909 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1913 finaldm = CDDM_from_mesh(me);
1915 if (build_shapekey_layers) {
1916 add_shapekey_layers(finaldm, me, ob);
1919 if (deformedVerts) {
1920 CDDM_apply_vert_coords(finaldm, deformedVerts);
1923 /* In this case, we should never have weight-modifying modifiers in stack... */
1925 DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1928 /* add an orco layer if needed */
1929 if (dataMask & CD_MASK_ORCO) {
1930 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1932 if (deform_r && *deform_r)
1933 add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1936 if (do_loop_normals) {
1937 /* Compute loop normals (note: will compute poly and vert normals as well, if needed!) */
1938 DM_calc_loop_normals(finaldm, do_loop_normals, loop_normals_split_angle);
1942 DM_ensure_tessface(finaldm);
1944 /* without this, drawing ngon tri's faces will show ugly tessellated face
1945 * normals and will also have to calculate normals on the fly, try avoid
1946 * this where possible since calculating polygon normals isn't fast,
1947 * note that this isn't a problem for subsurf (only quads) or editmode
1948 * which deals with drawing differently.
1950 * Only calc vertex normals if they are flagged as dirty.
1951 * If using loop normals, poly nors have already been computed.
1953 if (!do_loop_normals) {
1954 dm_ensure_display_normals(finaldm);
1958 #ifdef WITH_GAMEENGINE
1959 /* NavMesh - this is a hack but saves having a NavMesh modifier */
1960 if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1962 tdm = navmesh_dm_createNavMeshForVisualization(finaldm);
1963 if (finaldm != tdm) {
1964 finaldm->release(finaldm);
1968 #endif /* WITH_GAMEENGINE */
1973 orcodm->release(orcodm);
1975 clothorcodm->release(clothorcodm);
1977 if (deformedVerts && deformedVerts != inputVertexCos)
1978 MEM_freeN(deformedVerts);
1980 BLI_linklist_free((LinkNode *)datamasks, NULL);
1983 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *r_numVerts))[3]
1990 *r_numVerts = em->bm->totvert;
1992 cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
1994 BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
1995 copy_v3_v3(cos[i], eve->co);
2001 bool editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
2003 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2004 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2006 if (!modifier_isEnabled(scene, md, required_mode)) return 0;
2007 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
2008 modifier_setError(md, "Modifier requires original data, bad stack position");
2015 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
2016 DerivedMesh **final_r,
2017 CustomDataMask dataMask)
2019 ModifierData *md, *previewmd = NULL;
2020 float (*deformedVerts)[3] = NULL;
2021 CustomDataMask mask, previewmask = 0, append_mask = 0;
2022 DerivedMesh *dm = NULL, *orcodm = NULL;
2023 int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
2024 CDMaskLink *datamasks, *curr;
2025 int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
2026 int draw_flag = dm_drawflag_calc(scene->toolsettings);
2028 // const bool do_mod_mcol = true; // (ob->mode == OB_MODE_OBJECT);
2029 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
2030 const bool do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
2032 const bool do_final_wmcol = false;
2033 const bool do_init_wmcol = ((((Mesh *)ob->data)->drawflag & ME_DRAWEIGHT) && !do_final_wmcol);
2034 const bool do_init_statvis = ((((Mesh *)ob->data)->drawflag & ME_DRAW_STATVIS) && !do_init_wmcol);
2035 const bool do_mod_wmcol = do_init_wmcol;
2036 VirtualModifierData virtualModifierData;
2038 const bool do_loop_normals = (((Mesh *)(ob->data))->flag & ME_AUTOSMOOTH) != 0;
2039 const float loop_normals_split_angle = ((Mesh *)(ob->data))->smoothresh;
2041 modifiers_clearErrors(ob);
2043 if (cage_r && cageIndex == -1) {
2044 *cage_r = getEditDerivedBMesh(em, ob, NULL);
2047 md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
2049 /* copied from mesh_calc_modifiers */
2051 previewmd = modifiers_getLastPreview(scene, md, required_mode);
2052 /* even if the modifier doesn't need the data, to make a preview it may */
2054 previewmask = CD_MASK_MDEFORMVERT;
2058 datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode, previewmd, previewmask);
2061 for (i = 0; md; i++, md = md->next, curr = curr->next) {
2062 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
2066 if (!editbmesh_modifier_is_enabled(scene, md, dm))
2069 /* add an orco layer if needed by this modifier */
2070 if (dm && mti->requiredDataMask) {
2071 mask = mti->requiredDataMask(ob, md);
2072 if (mask & CD_MASK_ORCO)
2073 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
2076 /* How to apply modifier depends on (a) what we already have as
2077 * a result of previous modifiers (could be a DerivedMesh or just
2078 * deformed vertices) and (b) what type the modifier is.
2081 if (mti->type == eModifierTypeType_OnlyDeform) {
2082 /* No existing verts to deform, need to build them. */
2083 if (!deformedVerts) {
2085 /* Deforming a derived mesh, read the vertex locations
2086 * out of the mesh and deform them. Once done with this
2087 * run of deformers verts will be written back.
2089 numVerts = dm->getNumVerts(dm);
2091 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
2092 dm->getVertCos(dm, deformedVerts);
2095 deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
2099 if (mti->deformVertsEM)
2100 modwrap_deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
2102 modwrap_deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
2107 /* apply vertex coordinates or build a DerivedMesh as necessary */
2109 if (deformedVerts) {
2110 DerivedMesh *tdm = CDDM_copy(dm);
2111 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2114 CDDM_apply_vert_coords(dm, deformedVerts);
2116 else if (cage_r && dm == *cage_r) {
2117 /* dm may be changed by this modifier, so we need to copy it
2124 dm = CDDM_from_editbmesh(em, false, false);
2125 ASSERT_IS_VALID_DM(dm);
2127 if (deformedVerts) {
2128 CDDM_apply_vert_coords(dm, deformedVerts);
2131 if (do_init_wmcol) {
2132 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2136 /* create an orco derivedmesh in parallel */
2138 if (mask & CD_MASK_ORCO) {
2140 orcodm = create_orco_dm(ob, ob->data, em, CD_ORCO);
2142 mask &= ~CD_MASK_ORCO;
2143 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
2145 if (mti->applyModifierEM) {
2146 ndm = modwrap_applyModifierEM(md, ob, em, orcodm, MOD_APPLY_ORCO);
2149 ndm = modwrap_applyModifier(md, ob, orcodm, MOD_APPLY_ORCO);
2151 ASSERT_IS_VALID_DM(ndm);
2154 /* if the modifier returned a new dm, release the old one */
2155 if (orcodm && orcodm != ndm) orcodm->release(orcodm);
2160 /* set the DerivedMesh to only copy needed data */
2161 mask |= append_mask;
2162 mask = curr->mask; /* CD_MASK_ORCO may have been cleared above */
2164 DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
2166 if (mask & CD_MASK_ORIGSPACE_MLOOP) {
2167 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
2168 DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
2169 DM_init_origspace(dm);
2173 if (mti->applyModifierEM)
2174 ndm = modwrap_applyModifierEM(md, ob, em, dm, MOD_APPLY_USECACHE);
2176 ndm = modwrap_applyModifier(md, ob, dm, MOD_APPLY_USECACHE);
2177 ASSERT_IS_VALID_DM(ndm);
2180 if (dm && dm != ndm)
2185 if (deformedVerts) {
2186 MEM_freeN(deformedVerts);
2187 deformedVerts = NULL;
2192 /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
2193 if ((md == previewmd) && (do_mod_wmcol)) {
2194 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
2195 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
2198 if (cage_r && i == cageIndex) {
2199 if (dm && deformedVerts) {
2200 *cage_r = CDDM_copy(dm);
2201 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2208 getEditDerivedBMesh(em, ob,
2209 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2214 BLI_linklist_free((LinkNode *)datamasks, NULL);
2216 /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2217 * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2218 * then we need to build one.
2220 if (dm && deformedVerts) {
2221 *final_r = CDDM_copy(dm);
2223 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2225 CDDM_apply_vert_coords(*final_r, deformedVerts);
2230 else if (!deformedVerts && cage_r && *cage_r) {
2231 /* cage should already have up to date normals */
2234 /* In this case, we should never have weight-modifying modifiers in stack... */
2236 DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2237 if (do_init_statvis)
2238 DM_update_statvis_color(scene, ob, *final_r);
2241 /* this is just a copy of the editmesh, no need to calc normals */
2242 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2243 deformedVerts = NULL;
2245 /* In this case, we should never have weight-modifying modifiers in stack... */
2247 DM_update_weight_mcol(ob, *final_r, draw_flag, NULL, 0, NULL);
2248 if (do_init_statvis)
2249 DM_update_statvis_color(scene, ob, *final_r);
2252 if (do_loop_normals) {
2253 /* Compute loop normals */
2254 DM_calc_loop_normals(*final_r, do_loop_normals, loop_normals_split_angle);
2255 if (cage_r && *cage_r && (*cage_r != *final_r)) {
2256 DM_calc_loop_normals(*cage_r, do_loop_normals, loop_normals_split_angle);
2261 /* BMESH_ONLY, ensure tessface's used for drawing,
2262 * but don't recalculate if the last modifier in the stack gives us tessfaces
2263 * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2264 * but quiets annoying error messages since tessfaces wont be created. */
2265 if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2266 DM_ensure_tessface(*final_r);
2268 if (cage_r && *cage_r) {
2269 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2270 if (*cage_r != *final_r) {
2271 DM_ensure_tessface(*cage_r);
2277 /* same as mesh_calc_modifiers (if using loop normals, poly nors have already been computed). */
2278 if (!do_loop_normals) {
2279 dm_ensure_display_normals(*final_r);
2282 /* add an orco layer if needed */
2283 if (dataMask & CD_MASK_ORCO)
2284 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2287 orcodm->release(orcodm);
2290 MEM_freeN(deformedVerts);
2293 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2294 int build_shapekey_layers)
2296 Object *obact = scene->basact ? scene->basact->object : NULL;
2297 bool editing = BKE_paint_select_face_test(ob);
2298 /* weight paint and face select need original indices because of selection buffer drawing */
2299 int needMapping = (ob == obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_TEXTURE_PAINT)));
2301 BLI_assert(ob->type == OB_MESH);
2303 BKE_object_free_derived_caches(ob);
2304 BKE_object_sculpt_modifiers_changed(ob);
2306 mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2307 &ob->derivedFinal, 0, 1,
2308 needMapping, dataMask, -1, 1, build_shapekey_layers);
2310 DM_set_object_boundbox(ob, ob->derivedFinal);
2312 ob->derivedFinal->needsFree = 0;
2313 ob->derivedDeform->needsFree = 0;
2314 ob->lastDataMask = dataMask;
2316 if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2317 /* create PBVH immediately (would be created on the fly too,
2318 * but this avoids waiting on first stroke) */
2320 BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
2323 BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS));
2326 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2328 BKE_object_free_derived_caches(obedit);
2329 BKE_object_sculpt_modifiers_changed(obedit);
2331 BKE_editmesh_free_derivedmesh(em);
2333 editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2334 DM_set_object_boundbox(obedit, em->derivedFinal);
2336 em->lastDataMask = dataMask;
2337 em->derivedFinal->needsFree = 0;
2338 em->derivedCage->needsFree = 0;
2340 BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS));
2343 static CustomDataMask object_get_datamask(const Scene *scene, Object *ob)
2345 Object *actob = scene->basact ? scene->basact->object : NULL;
2346 CustomDataMask mask = ob->customdata_mask;
2349 /* check if we need tfaces & mcols due to face select or texture paint */
2350 if (BKE_paint_select_face_test(ob) || (ob->mode & OB_MODE_TEXTURE_PAINT)) {
2351 mask |= CD_MASK_MTFACE | CD_MASK_MCOL;
2354 /* check if we need mcols due to vertex paint or weightpaint */
2355 if (ob->mode & OB_MODE_VERTEX_PAINT) {
2356 mask |= CD_MASK_MCOL;
2359 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
2360 mask |= CD_MASK_PREVIEW_MCOL;
2363 if (ob->mode & OB_MODE_EDIT)
2364 mask |= CD_MASK_MVERT_SKIN;
2370 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2371 CustomDataMask dataMask, int build_shapekey_layers)
2373 dataMask |= object_get_datamask(scene, ob);
2376 editbmesh_build_data(scene, ob, em, dataMask);
2379 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2385 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2387 /* if there's no derived mesh or the last data mask used doesn't include
2388 * the data we need, rebuild the derived mesh
2390 dataMask |= object_get_datamask(scene, ob);
2392 if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2393 mesh_build_data(scene, ob, dataMask, 0);
2395 if (ob->derivedFinal) { BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2396 return ob->derivedFinal;
2399 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2401 /* if there's no derived mesh or the last data mask used doesn't include
2402 * the data we need, rebuild the derived mesh
2404 dataMask |= object_get_datamask(scene, ob);
2406 if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2407 mesh_build_data(scene, ob, dataMask, 0);
2409 return ob->derivedDeform;
2412 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2416 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2421 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2425 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2430 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2435 * psys modifier updates particle state when called during dupli-list generation,
2436 * which can lead to wrong transforms. This disables particle system modifier execution.
2438 ob->transflag |= OB_NO_PSYS_UPDATE;
2440 mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2442 ob->transflag &= ~OB_NO_PSYS_UPDATE;
2447 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2448 CustomDataMask dataMask)
2452 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2457 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2458 CustomDataMask dataMask)
2462 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2467 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2468 CustomDataMask dataMask)
2472 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2477 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2478 float (*vertCos)[3],
2479 CustomDataMask dataMask)
2483 mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2490 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **r_final,
2491 CustomDataMask dataMask)
2493 /* if there's no derived mesh or the last data mask used doesn't include
2494 * the data we need, rebuild the derived mesh
2496 dataMask |= object_get_datamask(scene, obedit);
2498 if (!em->derivedCage ||
2499 (em->lastDataMask & dataMask) != dataMask)
2501 editbmesh_build_data(scene, obedit, em, dataMask);
2504 *r_final = em->derivedFinal;
2505 if (em->derivedFinal) { BLI_assert(!(em->derivedFinal->dirty & DM_DIRTY_NORMALS)); }
2506 return em->derivedCage;
2509 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2511 /* if there's no derived mesh or the last data mask used doesn't include
2512 * the data we need, rebuild the derived mesh
2514 dataMask |= object_get_datamask(scene, obedit);
2516 if (!em->derivedCage ||
2517 (em->lastDataMask & dataMask) != dataMask)
2519 editbmesh_build_data(scene, obedit, em, dataMask);
2522 return em->derivedCage;
2525 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2527 return getEditDerivedBMesh(em, obedit, NULL);
2532 /* get derived mesh from an object, using editbmesh if available. */
2533 DerivedMesh *object_get_derived_final(Object *ob, const bool for_render)
2535 Mesh *me = ob->data;
2536 BMEditMesh *em = me->edit_btmesh;
2539 /* TODO(sergey): use proper derived render here in the future. */
2540 return ob->derivedFinal;
2543 /* only return the editmesh if its from this object because
2544 * we don't a mesh from another object's modifier stack: T43122 */
2545 if (em && (em->ob == ob)) {
2546 DerivedMesh *dm = em->derivedFinal;
2550 return ob->derivedFinal;
2557 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2559 static void make_vertexcosnos__mapFunc(void *userData, int index, const float co[3],
2560 const float no_f[3], const short no_s[3])
2562 DMCoNo *co_no = &((DMCoNo *)userData)[index];
2564 /* check if we've been here before (normal should not be 0) */
2565 if (!is_zero_v3(co_no->no)) {
2569 copy_v3_v3(co_no->co, co);
2571 copy_v3_v3(co_no->no, no_f);
2574 normal_short_to_float_v3(co_no->no, no_s);
2578 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2579 /* this is needed for all code using vertexgroups (no subsurf support) */
2580 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2581 /* in use now by vertex/weight paint and particle generating */
2583 DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2585 Mesh *me = ob->data;
2587 DMCoNo *vertexcosnos;
2589 /* lets prevent crashing... */
2590 if (ob->type != OB_MESH || me->totvert == 0)
2593 dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
2595 if (dm->foreachMappedVert) {
2596 vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2597 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2600 DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
2602 for (a = 0; a < me->totvert; a++, v_co_no++) {
2603 dm->getVertCo(dm, a, v_co_no->co);
2604 dm->getVertNo(dm, a, v_co_no->no);
2609 return vertexcosnos;
2614 /* same as above but for vert coords */
2616 float (*vertexcos)[3];
2617 BLI_bitmap *vertex_visit;
2620 static void make_vertexcos__mapFunc(void *userData, int index, const float co[3],
2621 const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
2623 MappedUserData *mappedData = (MappedUserData *)userData;
2625 if (BLI_BITMAP_TEST(mappedData->vertex_visit, index) == 0) {
2626 /* we need coord from prototype vertex, not from copies,
2627 * assume they stored in the beginning of vertex array stored in DM
2628 * (mirror modifier for eg does this) */
2629 copy_v3_v3(mappedData->vertexcos[index], co);
2630 BLI_BITMAP_ENABLE(mappedData->vertex_visit, index);
2634 void mesh_get_mapped_verts_coords(DerivedMesh *dm, float (*r_cos)[3], const int totcos)
2636 if (dm->foreachMappedVert) {
2637 MappedUserData userData;
2638 memset(r_cos, 0, sizeof(*r_cos) * totcos);
2639 userData.vertexcos = r_cos;
2640 userData.vertex_visit = BLI_BITMAP_NEW(totcos, "vertexcos flags");
2641 dm->foreachMappedVert(dm, make_vertexcos__mapFunc, &userData, DM_FOREACH_NOP);
2642 MEM_freeN(userData.vertex_visit);
2646 for (i = 0; i < totcos; i++) {
2647 dm->getVertCo(dm, i, r_cos[i]);
2652 /* ******************* GLSL ******************** */
2655 float (*precomputedFaceNormals)[3];
2656 short (*precomputedLoopNormals)[4][3];
2657 MTFace *mtface; /* texture coordinates */
2658 MFace *mface; /* indices */
2659 MVert *mvert; /* vertices & normals */
2661 float (*tangent)[4]; /* destination */
2664 } SGLSLMeshToTangent;
2667 #include "mikktspace.h"
2669 static int GetNumFaces(const SMikkTSpaceContext *pContext)
2671 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2672 return pMesh->numTessFaces;
2675 static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_num)
2677 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2678 return pMesh->mface[face_num].v4 != 0 ? 4 : 3;
2681 static void GetPosition(const SMikkTSpaceContext *pContext, float r_co[3], const int face_num, const int vert_index)
2683 //assert(vert_index >= 0 && vert_index < 4);
2684 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2685 const float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2686 copy_v3_v3(r_co, co);
2689 static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float r_uv[2], const int face_num, const int vert_index)
2691 //assert(vert_index >= 0 && vert_index < 4);
2692 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2694 if (pMesh->mtface != NULL) {
2695 const float *uv = pMesh->mtface[face_num].uv[vert_index];
2696 copy_v2_v2(r_uv, uv);
2699 const float *orco = pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2700 map_to_sphere(&r_uv[0], &r_uv[1], orco[0], orco[1], orco[2]);
2704 static void GetNormal(const SMikkTSpaceContext *pContext, float r_no[3], const int face_num, const int vert_index)
2706 //assert(vert_index >= 0 && vert_index < 4);
2707 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2708 const bool smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH) != 0;
2710 if (pMesh->precomputedLoopNormals) {
2711 normal_short_to_float_v3(r_no, pMesh->precomputedLoopNormals[face_num][vert_index]);
2713 else if (!smoothnormal) { // flat
2714 if (pMesh->precomputedFaceNormals) {
2715 copy_v3_v3(r_no, pMesh->precomputedFaceNormals[face_num]);
2718 MFace *mf = &pMesh->mface[face_num];
2719 const float *p0 = pMesh->mvert[mf->v1].co;
2720 const float *p1 = pMesh->mvert[mf->v2].co;
2721 const float *p2 = pMesh->mvert[mf->v3].co;
2724 const float *p3 = pMesh->mvert[mf->v4].co;
2725 normal_quad_v3(r_no, p0, p1, p2, p3);
2728 normal_tri_v3(r_no, p0, p1, p2);
2733 const short *no = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2734 normal_short_to_float_v3(r_no, no);
2738 static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[3], const float fSign, const int face_num, const int iVert)
2740 //assert(vert_index >= 0 && vert_index < 4);
2741 SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2742 float *pRes = pMesh->tangent[4 * face_num + iVert];
2743 copy_v3_v3(pRes, fvTangent);
2747 void DM_add_tangent_layer(DerivedMesh *dm)
2753 float (*orco)[3] = NULL, (*tangent)[4];
2754 int /* totvert, */ totface;
2756 short (*tlnors)[4][3];
2758 if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2761 fnors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2762 /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled),
2763 * have to check this is valid...
2765 tlnors = dm->getTessFaceDataArray(dm, CD_TESSLOOPNORMAL);
2767 /* check we have all the needed layers */
2768 /* totvert = dm->getNumVerts(dm); */ /* UNUSED */
2769 totface = dm->getNumTessFaces(dm);
2771 mvert = dm->getVertArray(dm);
2772 mface = dm->getTessFaceArray(dm);
2773 mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2776 orco = dm->getVertDataArray(dm, CD_ORCO);
2781 /* create tangent layer */
2782 DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2783 tangent = DM_get_tessface_data_layer(dm, CD_TANGENT);
2785 /* new computation method */
2787 SGLSLMeshToTangent mesh2tangent = {NULL};
2788 SMikkTSpaceContext sContext = {NULL};
2789 SMikkTSpaceInterface sInterface = {NULL};
2791 mesh2tangent.precomputedFaceNormals = fnors;
2792 mesh2tangent.precomputedLoopNormals = tlnors;
2793 mesh2tangent.mtface = mtface;
2794 mesh2tangent.mface = mface;
2795 mesh2tangent.mvert = mvert;
2796 mesh2tangent.orco = orco;
2797 mesh2tangent.tangent = tangent;
2798 mesh2tangent.numTessFaces = totface;
2800 sContext.m_pUserData = &mesh2tangent;
2801 sContext.m_pInterface = &sInterface;
2802 sInterface.m_getNumFaces = GetNumFaces;
2803 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2804 sInterface.m_getPosition = GetPosition;
2805 sInterface.m_getTexCoord = GetTextureCoordinate;
2806 sInterface.m_getNormal = GetNormal;
2807 sInterface.m_setTSpaceBasic = SetTSpace;
2810 genTangSpaceDefault(&sContext);
2814 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2816 /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */
2817 int totface = dm->getNumTessFaces(dm);
2819 MVert *mvert = dm->getVertArray(dm);
2820 MFace *mface = dm->getTessFaceArray(dm);
2821 MTFace *mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2825 int nr_accumulated = 0;
2828 for (f = 0; f < totface; f++) {
2830 float *verts[4], *tex_coords[4];
2831 const int nr_verts = mface[f].v4 != 0 ? 4 : 3;
2835 verts[0] = mvert[mface[f].v1].co; verts[1] = mvert[mface[f].v2].co; verts[2] = mvert[mface[f].v3].co;
2836 tex_coords[0] = mtface[f].uv[0]; tex_coords[1] = mtface[f].uv[1]; tex_coords[2] = mtface[f].uv[2];
2837 if (nr_verts == 4) {
2838 verts[3] = mvert[mface[f].v4].co;
2839 tex_coords[3] = mtface[f].uv[3];
2842 /* discard degenerate faces */
2844 if (equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2845 equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]))
2850 /* verify last vertex as well if this is a quad */
2851 if (is_degenerate == 0 && nr_verts == 4) {
2852 if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2853 equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]))
2858 /* verify the winding is consistent */
2859 if (is_degenerate == 0) {
2862 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2865 while (is_degenerate == 0 && i < 4) {
2866 float cur_edge[2], signed_area;
2867 sub_v2_v2v2(cur_edge, tex_coords[(i + 1) & 0x3], tex_coords[i]);
2868 signed_area = prev_edge[0] * cur_edge[1] - prev_edge[1] * cur_edge[0];
2871 is_signed = (signed_area < 0.0f) ? 1 : 0;
2873 else if ((is_signed != 0) != (signed_area < 0.0f)) {
2877 if (is_degenerate == 0) {
2878 copy_v2_v2(prev_edge, cur_edge);
2885 /* proceed if not a degenerate face */
2886 if (is_degenerate == 0) {
2887 int nr_tris_to_pile = 0;
2888 /* quads split at shortest diagonal */
2889 int offs = 0; /* initial triangulation is 0,1,2 and 0, 2, 3 */
2890 if (nr_verts == 4) {
2891 float pos_len_diag0, pos_len_diag1;
2893 pos_len_diag0 = len_squared_v3v3(verts[2], verts[0]);
2894 pos_len_diag1 = len_squared_v3v3(verts[3], verts[1]);
2896 if (pos_len_diag1 < pos_len_diag0) {
2897 offs = 1; // alter split
2899 else if (pos_len_diag0 == pos_len_diag1) { /* do UV check instead */
2900 float tex_len_diag0, tex_len_diag1;
2902 tex_len_diag0 = len_squared_v2v2(tex_coords[2], tex_coords[0]);
2903 tex_len_diag1 = len_squared_v2v2(tex_coords[3], tex_coords[1]);
2905 if (tex_len_diag1 < tex_len_diag0) {
2906 offs = 1; /* alter split */
2910 nr_tris_to_pile = nr_verts - 2;
2911 if (nr_tris_to_pile == 1 || nr_tris_to_pile == 2) {
2912 const int indices[6] = {offs + 0, offs + 1, offs + 2, offs + 0, offs + 2, (offs + 3) & 0x3 };
2914 for (t = 0; t < nr_tris_to_pile; t++) {
2916 const float *p0 = verts[indices[t * 3 + 0]];
2917 const float *p1 = verts[indices[t * 3 + 1]];
2918 const float *p2 = verts[indices[t * 3 + 2]];
2920 float edge_t0[2], edge_t1[2];
2921 sub_v2_v2v2(edge_t0, tex_coords[indices[t * 3 + 1]], tex_coords[indices[t * 3 + 0]]);
2922 sub_v2_v2v2(edge_t1, tex_coords[indices[t * 3 + 2]], tex_coords[indices[t * 3 + 0]]);
2924 f2x_area_uv = fabsf(edge_t0[0] * edge_t1[1] - edge_t0[1] * edge_t1[0]);
2925 if (f2x_area_uv > FLT_EPSILON) {
2926 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2927 sub_v3_v3v3(v0, p1, p0);
2928 sub_v3_v3v3(v1, p2, p0);
2929 cross_v3_v3v3(norm, v0, v1);
2931 f2x_surf_area = len_v3(norm);
2932 fsurf_ratio = f2x_surf_area / f2x_area_uv; /* tri area divided by texture area */
2935 dsum += (double)(fsurf_ratio);
2945 const float avg_area_ratio = (nr_accumulated > 0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2946 const float use_as_render_bump_scale = sqrtf(avg_area_ratio); // use width of average surface ratio as your bump scale
2947 dm->auto_bump_scale = use_as_render_bump_scale;
2951 dm->auto_bump_scale = 1.0f;
2955 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2957 CustomData *vdata, *fdata, *tfdata = NULL;
2960 /* From the layers requested by the GLSL shader, figure out which ones are
2961 * actually available for this derivedmesh, and retrieve the pointers */
2963 memset(attribs, 0, sizeof(DMVertexAttribs));
2965 vdata = &dm->vertData;
2966 fdata = tfdata = dm->getTessFaceDataLayout(dm);
2968 /* calc auto bump scale if necessary */
2969 if (dm->auto_bump_scale <= 0.0f)
2970 DM_calc_auto_bump_scale(dm);
2972 /* add a tangent layer if necessary */
2973 for (b = 0; b < gattribs->totlayer; b++)
2974 if (gattribs->layer[b].type == CD_TANGENT)
2975 if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2976 DM_add_tangent_layer(dm);
2978 for (b = 0; b < gattribs->totlayer; b++) {
2979 if (gattribs->layer[b].type == CD_MTFACE) {
2980 /* uv coordinates */
2981 if (dm->type == DM_TYPE_EDITBMESH) {
2983 CustomData *ldata = dm->getLoopDataLayout(dm);
2985 if (gattribs->layer[b].name[0])
2986 layer = CustomData_get_named_layer_index(ldata, CD_MLOOPUV,
2987 gattribs->layer[b].name);
2989 layer = CustomData_get_active_layer_index(ldata, CD_MLOOPUV);
2991 a = attribs->tottface++;
2994 attribs->tface[a].array = NULL;
2995 attribs->tface[a].em_offset = ldata->layers[layer].offset;
2998 attribs->tface[a].array = NULL;
2999 attribs->tface[a].em_offset = -1;
3002 attribs->tface[a].gl_index = gattribs->layer[b].glindex;
3003 attribs->tface[a].gl_texco = gattribs->layer[b].gltexco;
3006 if (gattribs->layer[b].name[0])
3007 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
3008 gattribs->layer[b].name);
3010 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
3012 a = attribs->tottface++;
3015 attribs->tface[a].array = tfdata->layers[layer].data;
3016 attribs->tface[a].em_offset = tfdata->layers[layer].offset;
3019 attribs->tface[a].array = NULL;