Point Cache Refactoring
[blender-staging.git] / source / blender / blenkernel / intern / modifier.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) 2005 by the Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Daniel Dunbar
26 *                 Ton Roosendaal,
27 *                 Ben Batt,
28 *                 Brecht Van Lommel,
29 *                 Campbell Barton
30 *
31 * ***** END GPL LICENSE BLOCK *****
32 *
33 * Modifier stack implementation.
34 *
35 * BKE_modifier.h contains the function prototypes for this file.
36 *
37 */
38
39 #include "string.h"
40 #include "stdarg.h"
41 #include "math.h"
42 #include "float.h"
43
44 #include "BLI_arithb.h"
45 #include "BLI_blenlib.h"
46 #include "BLI_kdtree.h"
47 #include "BLI_linklist.h"
48 #include "BLI_rand.h"
49 #include "BLI_edgehash.h"
50 #include "BLI_ghash.h"
51 #include "BLI_memarena.h"
52
53 #include "MEM_guardedalloc.h"
54
55 #include "DNA_armature_types.h"
56 #include "DNA_cloth_types.h"
57 #include "DNA_effect_types.h"
58 #include "DNA_material_types.h"
59 #include "DNA_mesh_types.h"
60 #include "DNA_meshdata_types.h"
61 #include "DNA_modifier_types.h"
62 #include "DNA_object_types.h"
63 #include "DNA_object_force.h"
64 #include "DNA_particle_types.h"
65 #include "DNA_scene_types.h"
66 #include "DNA_texture_types.h"
67 #include "DNA_curve_types.h"
68 #include "DNA_camera_types.h"
69
70 #include "BLI_editVert.h"
71
72 #include "MTC_matrixops.h"
73 #include "MTC_vectorops.h"
74
75 #include "BKE_main.h"
76 #include "BKE_anim.h"
77 #include "BKE_bad_level_calls.h"
78 #include "BKE_cloth.h"
79 #include "BKE_curve.h"
80 #include "BKE_customdata.h"
81 #include "BKE_global.h"
82 #include "BKE_cdderivedmesh.h"
83 #include "BKE_DerivedMesh.h"
84 #include "BKE_booleanops.h"
85 #include "BKE_displist.h"
86 #include "BKE_modifier.h"
87 #include "BKE_lattice.h"
88 #include "BKE_library.h"
89 #include "BKE_subsurf.h"
90 #include "BKE_object.h"
91 #include "BKE_mesh.h"
92 #include "BKE_softbody.h"
93 #include "BKE_cloth.h"
94 #include "BKE_material.h"
95 #include "BKE_particle.h"
96 #include "BKE_pointcache.h"
97 #include "BKE_utildefines.h"
98 #include "depsgraph_private.h"
99 #include "BKE_bmesh.h"
100
101 #include "LOD_DependKludge.h"
102 #include "LOD_decimation.h"
103
104 #include "CCGSubSurf.h"
105
106 #include "RE_shader_ext.h"
107
108 /***/
109
110 static int noneModifier_isDisabled(ModifierData *md)
111 {
112         return 1;
113 }
114
115 /* Curve */
116
117 static void curveModifier_initData(ModifierData *md)
118 {
119         CurveModifierData *cmd = (CurveModifierData*) md;
120
121         cmd->defaxis = MOD_CURVE_POSX;
122 }
123
124 static void curveModifier_copyData(ModifierData *md, ModifierData *target)
125 {
126         CurveModifierData *cmd = (CurveModifierData*) md;
127         CurveModifierData *tcmd = (CurveModifierData*) target;
128
129         tcmd->defaxis = cmd->defaxis;
130         tcmd->object = cmd->object;
131         strncpy(tcmd->name, cmd->name, 32);
132 }
133
134 CustomDataMask curveModifier_requiredDataMask(ModifierData *md)
135 {
136         CurveModifierData *cmd = (CurveModifierData *)md;
137         CustomDataMask dataMask = 0;
138
139         /* ask for vertexgroups if we need them */
140         if(cmd->name[0]) dataMask |= (1 << CD_MDEFORMVERT);
141
142         return dataMask;
143 }
144
145 static int curveModifier_isDisabled(ModifierData *md)
146 {
147         CurveModifierData *cmd = (CurveModifierData*) md;
148
149         return !cmd->object;
150 }
151
152 static void curveModifier_foreachObjectLink(
153                                             ModifierData *md, Object *ob,
154          void (*walk)(void *userData, Object *ob, Object **obpoin),
155                 void *userData)
156 {
157         CurveModifierData *cmd = (CurveModifierData*) md;
158
159         walk(userData, ob, &cmd->object);
160 }
161
162 static void curveModifier_updateDepgraph(
163                                          ModifierData *md, DagForest *forest,
164       Object *ob, DagNode *obNode)
165 {
166         CurveModifierData *cmd = (CurveModifierData*) md;
167
168         if (cmd->object) {
169                 DagNode *curNode = dag_get_node(forest, cmd->object);
170
171                 dag_add_relation(forest, curNode, obNode,
172                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
173         }
174 }
175
176 static void curveModifier_deformVerts(
177                                       ModifierData *md, Object *ob, DerivedMesh *derivedData,
178           float (*vertexCos)[3], int numVerts)
179 {
180         CurveModifierData *cmd = (CurveModifierData*) md;
181
182         curve_deform_verts(cmd->object, ob, derivedData, vertexCos, numVerts,
183                            cmd->name, cmd->defaxis);
184 }
185
186 static void curveModifier_deformVertsEM(
187                                         ModifierData *md, Object *ob, EditMesh *editData,
188      DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
189 {
190         DerivedMesh *dm = derivedData;
191
192         if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
193
194         curveModifier_deformVerts(md, ob, dm, vertexCos, numVerts);
195
196         if(!derivedData) dm->release(dm);
197 }
198
199 /* Lattice */
200
201 static void latticeModifier_copyData(ModifierData *md, ModifierData *target)
202 {
203         LatticeModifierData *lmd = (LatticeModifierData*) md;
204         LatticeModifierData *tlmd = (LatticeModifierData*) target;
205
206         tlmd->object = lmd->object;
207         strncpy(tlmd->name, lmd->name, 32);
208 }
209
210 CustomDataMask latticeModifier_requiredDataMask(ModifierData *md)
211 {
212         LatticeModifierData *lmd = (LatticeModifierData *)md;
213         CustomDataMask dataMask = 0;
214
215         /* ask for vertexgroups if we need them */
216         if(lmd->name[0]) dataMask |= (1 << CD_MDEFORMVERT);
217
218         return dataMask;
219 }
220
221 static int latticeModifier_isDisabled(ModifierData *md)
222 {
223         LatticeModifierData *lmd = (LatticeModifierData*) md;
224
225         return !lmd->object;
226 }
227
228 static void latticeModifier_foreachObjectLink(
229                                               ModifierData *md, Object *ob,
230            void (*walk)(void *userData, Object *ob, Object **obpoin),
231                   void *userData)
232 {
233         LatticeModifierData *lmd = (LatticeModifierData*) md;
234
235         walk(userData, ob, &lmd->object);
236 }
237
238 static void latticeModifier_updateDepgraph(ModifierData *md, DagForest *forest,
239                                            Object *ob, DagNode *obNode)
240 {
241         LatticeModifierData *lmd = (LatticeModifierData*) md;
242
243         if(lmd->object) {
244                 DagNode *latNode = dag_get_node(forest, lmd->object);
245
246                 dag_add_relation(forest, latNode, obNode,
247                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
248         }
249 }
250
251 static void modifier_vgroup_cache(ModifierData *md, float (*vertexCos)[3])
252 {
253         md= md->next;
254         if(md) {
255                 if(md->type==eModifierType_Armature) {
256                         ArmatureModifierData *amd = (ArmatureModifierData*) md;
257                         if(amd->multi)
258                                 amd->prevCos= MEM_dupallocN(vertexCos);
259                 }
260                 /* lattice/mesh modifier too */
261         }
262 }
263
264
265 static void latticeModifier_deformVerts(
266                                         ModifierData *md, Object *ob, DerivedMesh *derivedData,
267      float (*vertexCos)[3], int numVerts)
268 {
269         LatticeModifierData *lmd = (LatticeModifierData*) md;
270
271
272         modifier_vgroup_cache(md, vertexCos); /* if next modifier needs original vertices */
273         
274         lattice_deform_verts(lmd->object, ob, derivedData,
275                              vertexCos, numVerts, lmd->name);
276 }
277
278 static void latticeModifier_deformVertsEM(
279                                           ModifierData *md, Object *ob, EditMesh *editData,
280        DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
281 {
282         DerivedMesh *dm = derivedData;
283
284         if(!derivedData) dm = CDDM_from_editmesh(editData, ob->data);
285
286         latticeModifier_deformVerts(md, ob, dm, vertexCos, numVerts);
287
288         if(!derivedData) dm->release(dm);
289 }
290
291 /* Subsurf */
292
293 static void subsurfModifier_initData(ModifierData *md)
294 {
295         SubsurfModifierData *smd = (SubsurfModifierData*) md;
296
297         smd->levels = 1;
298         smd->renderLevels = 2;
299         smd->flags |= eSubsurfModifierFlag_SubsurfUv;
300 }
301
302 static void subsurfModifier_copyData(ModifierData *md, ModifierData *target)
303 {
304         SubsurfModifierData *smd = (SubsurfModifierData*) md;
305         SubsurfModifierData *tsmd = (SubsurfModifierData*) target;
306
307         tsmd->flags = smd->flags;
308         tsmd->levels = smd->levels;
309         tsmd->renderLevels = smd->renderLevels;
310         tsmd->subdivType = smd->subdivType;
311 }
312
313 static void subsurfModifier_freeData(ModifierData *md)
314 {
315         SubsurfModifierData *smd = (SubsurfModifierData*) md;
316
317         if(smd->mCache) {
318                 ccgSubSurf_free(smd->mCache);
319         }
320         if(smd->emCache) {
321                 ccgSubSurf_free(smd->emCache);
322         }
323 }
324
325 static DerivedMesh *subsurfModifier_applyModifier(
326                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
327   int useRenderParams, int isFinalCalc)
328 {
329         SubsurfModifierData *smd = (SubsurfModifierData*) md;
330         DerivedMesh *result;
331
332         result = subsurf_make_derived_from_derived(derivedData, smd,
333                         useRenderParams, NULL,
334    isFinalCalc, 0);
335
336         return result;
337 }
338
339 static DerivedMesh *subsurfModifier_applyModifierEM(
340                 ModifierData *md, Object *ob, EditMesh *editData,
341   DerivedMesh *derivedData)
342 {
343         SubsurfModifierData *smd = (SubsurfModifierData*) md;
344         DerivedMesh *result;
345
346         result = subsurf_make_derived_from_derived(derivedData, smd, 0,
347                         NULL, 0, 1);
348
349         return result;
350 }
351
352 /* Build */
353
354 static void buildModifier_initData(ModifierData *md)
355 {
356         BuildModifierData *bmd = (BuildModifierData*) md;
357
358         bmd->start = 1.0;
359         bmd->length = 100.0;
360 }
361
362 static void buildModifier_copyData(ModifierData *md, ModifierData *target)
363 {
364         BuildModifierData *bmd = (BuildModifierData*) md;
365         BuildModifierData *tbmd = (BuildModifierData*) target;
366
367         tbmd->start = bmd->start;
368         tbmd->length = bmd->length;
369         tbmd->randomize = bmd->randomize;
370         tbmd->seed = bmd->seed;
371 }
372
373 static int buildModifier_dependsOnTime(ModifierData *md)
374 {
375         return 1;
376 }
377
378 static DerivedMesh *buildModifier_applyModifier(ModifierData *md, Object *ob,
379                 DerivedMesh *derivedData,
380   int useRenderParams, int isFinalCalc)
381 {
382         DerivedMesh *dm = derivedData;
383         DerivedMesh *result;
384         BuildModifierData *bmd = (BuildModifierData*) md;
385         int i;
386         int numFaces, numEdges;
387         int maxVerts, maxEdges, maxFaces;
388         int *vertMap, *edgeMap, *faceMap;
389         float frac;
390         GHashIterator *hashIter;
391         /* maps vert indices in old mesh to indices in new mesh */
392         GHash *vertHash = BLI_ghash_new(BLI_ghashutil_inthash,
393                                         BLI_ghashutil_intcmp);
394         /* maps edge indices in new mesh to indices in old mesh */
395         GHash *edgeHash = BLI_ghash_new(BLI_ghashutil_inthash,
396                                         BLI_ghashutil_intcmp);
397
398         maxVerts = dm->getNumVerts(dm);
399         vertMap = MEM_callocN(sizeof(*vertMap) * maxVerts,
400                               "build modifier vertMap");
401         for(i = 0; i < maxVerts; ++i) vertMap[i] = i;
402
403         maxEdges = dm->getNumEdges(dm);
404         edgeMap = MEM_callocN(sizeof(*edgeMap) * maxEdges,
405                               "build modifier edgeMap");
406         for(i = 0; i < maxEdges; ++i) edgeMap[i] = i;
407
408         maxFaces = dm->getNumFaces(dm);
409         faceMap = MEM_callocN(sizeof(*faceMap) * maxFaces,
410                               "build modifier faceMap");
411         for(i = 0; i < maxFaces; ++i) faceMap[i] = i;
412
413         if (ob) {
414                 frac = bsystem_time(ob, (float)G.scene->r.cfra,
415                                     bmd->start - 1.0f) / bmd->length;
416         } else {
417                 frac = G.scene->r.cfra - bmd->start / bmd->length;
418         }
419         CLAMP(frac, 0.0, 1.0);
420
421         numFaces = dm->getNumFaces(dm) * frac;
422         numEdges = dm->getNumEdges(dm) * frac;
423
424         /* if there's at least one face, build based on faces */
425         if(numFaces) {
426                 int maxEdges;
427
428                 if(bmd->randomize)
429                         BLI_array_randomize(faceMap, sizeof(*faceMap),
430                                             maxFaces, bmd->seed);
431
432                 /* get the set of all vert indices that will be in the final mesh,
433                 * mapped to the new indices
434                 */
435                 for(i = 0; i < numFaces; ++i) {
436                         MFace mf;
437                         dm->getFace(dm, faceMap[i], &mf);
438
439                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v1)))
440                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v1),
441                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
442                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v2)))
443                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v2),
444                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
445                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v3)))
446                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v3),
447                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
448                         if(mf.v4 && !BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(mf.v4)))
449                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(mf.v4),
450                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
451                 }
452
453                 /* get the set of edges that will be in the new mesh (i.e. all edges
454                 * that have both verts in the new mesh)
455                 */
456                 maxEdges = dm->getNumEdges(dm);
457                 for(i = 0; i < maxEdges; ++i) {
458                         MEdge me;
459                         dm->getEdge(dm, i, &me);
460
461                         if(BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1))
462                                                 && BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
463                                 BLI_ghash_insert(edgeHash,
464                                         SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)), SET_INT_IN_POINTER(i));
465                 }
466         } else if(numEdges) {
467                 if(bmd->randomize)
468                         BLI_array_randomize(edgeMap, sizeof(*edgeMap),
469                                             maxEdges, bmd->seed);
470
471                 /* get the set of all vert indices that will be in the final mesh,
472                 * mapped to the new indices
473                 */
474                 for(i = 0; i < numEdges; ++i) {
475                         MEdge me;
476                         dm->getEdge(dm, edgeMap[i], &me);
477
478                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v1)))
479                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v1),
480                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
481                         if(!BLI_ghash_haskey(vertHash, SET_INT_IN_POINTER(me.v2)))
482                                 BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(me.v2),
483                                         SET_INT_IN_POINTER(BLI_ghash_size(vertHash)));
484                 }
485
486                 /* get the set of edges that will be in the new mesh
487                 */
488                 for(i = 0; i < numEdges; ++i) {
489                         MEdge me;
490                         dm->getEdge(dm, edgeMap[i], &me);
491
492                         BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(BLI_ghash_size(edgeHash)),
493                                          SET_INT_IN_POINTER(edgeMap[i]));
494                 }
495         } else {
496                 int numVerts = dm->getNumVerts(dm) * frac;
497
498                 if(bmd->randomize)
499                         BLI_array_randomize(vertMap, sizeof(*vertMap),
500                                             maxVerts, bmd->seed);
501
502                 /* get the set of all vert indices that will be in the final mesh,
503                 * mapped to the new indices
504                 */
505                 for(i = 0; i < numVerts; ++i)
506                         BLI_ghash_insert(vertHash, SET_INT_IN_POINTER(vertMap[i]), SET_INT_IN_POINTER(i));
507         }
508
509         /* now we know the number of verts, edges and faces, we can create
510         * the mesh
511         */
512         result = CDDM_from_template(dm, BLI_ghash_size(vertHash),
513                                     BLI_ghash_size(edgeHash), numFaces);
514
515         /* copy the vertices across */
516         for(hashIter = BLI_ghashIterator_new(vertHash);
517                    !BLI_ghashIterator_isDone(hashIter);
518                    BLI_ghashIterator_step(hashIter)) {
519                            MVert source;
520                            MVert *dest;
521                            int oldIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(hashIter));
522                            int newIndex = GET_INT_FROM_POINTER(BLI_ghashIterator_getValue(hashIter));
523
524                            dm->getVert(dm, oldIndex, &source);
525                            dest = CDDM_get_vert(result, newIndex);
526
527                            DM_copy_vert_data(dm, result, oldIndex, newIndex, 1);
528                            *dest = source;
529                    }
530                    BLI_ghashIterator_free(hashIter);
531
532                    /* copy the edges across, remapping indices */
533                    for(i = 0; i < BLI_ghash_size(edgeHash); ++i) {
534                            MEdge source;
535                            MEdge *dest;
536                            int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i)));
537
538                            dm->getEdge(dm, oldIndex, &source);
539                            dest = CDDM_get_edge(result, i);
540
541                            source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
542                            source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
543
544                            DM_copy_edge_data(dm, result, oldIndex, i, 1);
545                            *dest = source;
546                    }
547
548                    /* copy the faces across, remapping indices */
549                    for(i = 0; i < numFaces; ++i) {
550                            MFace source;
551                            MFace *dest;
552                            int orig_v4;
553
554                            dm->getFace(dm, faceMap[i], &source);
555                            dest = CDDM_get_face(result, i);
556
557                            orig_v4 = source.v4;
558
559                            source.v1 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v1)));
560                            source.v2 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v2)));
561                            source.v3 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v3)));
562                            if(source.v4)
563                                    source.v4 = GET_INT_FROM_POINTER(BLI_ghash_lookup(vertHash, SET_INT_IN_POINTER(source.v4)));
564
565                            DM_copy_face_data(dm, result, faceMap[i], i, 1);
566                            *dest = source;
567
568                            test_index_face(dest, &result->faceData, i, (orig_v4 ? 4 : 3));
569                    }
570
571                    CDDM_calc_normals(result);
572
573                    BLI_ghash_free(vertHash, NULL, NULL);
574                    BLI_ghash_free(edgeHash, NULL, NULL);
575
576                    MEM_freeN(vertMap);
577                    MEM_freeN(edgeMap);
578                    MEM_freeN(faceMap);
579
580                    return result;
581 }
582
583 /* Array */
584 /* Array modifier: duplicates the object multiple times along an axis
585 */
586
587 static void arrayModifier_initData(ModifierData *md)
588 {
589         ArrayModifierData *amd = (ArrayModifierData*) md;
590
591         /* default to 2 duplicates distributed along the x-axis by an
592         offset of 1 object-width
593         */
594         amd->start_cap = amd->end_cap = amd->curve_ob = amd->offset_ob = NULL;
595         amd->count = 2;
596         amd->offset[0] = amd->offset[1] = amd->offset[2] = 0;
597         amd->scale[0] = 1;
598         amd->scale[1] = amd->scale[2] = 0;
599         amd->length = 0;
600         amd->merge_dist = 0.01;
601         amd->fit_type = MOD_ARR_FIXEDCOUNT;
602         amd->offset_type = MOD_ARR_OFF_RELATIVE;
603         amd->flags = 0;
604 }
605
606 static void arrayModifier_copyData(ModifierData *md, ModifierData *target)
607 {
608         ArrayModifierData *amd = (ArrayModifierData*) md;
609         ArrayModifierData *tamd = (ArrayModifierData*) target;
610
611         tamd->start_cap = amd->start_cap;
612         tamd->end_cap = amd->end_cap;
613         tamd->curve_ob = amd->curve_ob;
614         tamd->offset_ob = amd->offset_ob;
615         tamd->count = amd->count;
616         VECCOPY(tamd->offset, amd->offset);
617         VECCOPY(tamd->scale, amd->scale);
618         tamd->length = amd->length;
619         tamd->merge_dist = amd->merge_dist;
620         tamd->fit_type = amd->fit_type;
621         tamd->offset_type = amd->offset_type;
622         tamd->flags = amd->flags;
623 }
624
625 static void arrayModifier_foreachObjectLink(
626                                             ModifierData *md, Object *ob,
627          void (*walk)(void *userData, Object *ob, Object **obpoin),
628                 void *userData)
629 {
630         ArrayModifierData *amd = (ArrayModifierData*) md;
631
632         walk(userData, ob, &amd->start_cap);
633         walk(userData, ob, &amd->end_cap);
634         walk(userData, ob, &amd->curve_ob);
635         walk(userData, ob, &amd->offset_ob);
636 }
637
638 static void arrayModifier_updateDepgraph(ModifierData *md, DagForest *forest,
639                                          Object *ob, DagNode *obNode)
640 {
641         ArrayModifierData *amd = (ArrayModifierData*) md;
642
643         if (amd->start_cap) {
644                 DagNode *curNode = dag_get_node(forest, amd->start_cap);
645
646                 dag_add_relation(forest, curNode, obNode,
647                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
648         }
649         if (amd->end_cap) {
650                 DagNode *curNode = dag_get_node(forest, amd->end_cap);
651
652                 dag_add_relation(forest, curNode, obNode,
653                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
654         }
655         if (amd->curve_ob) {
656                 DagNode *curNode = dag_get_node(forest, amd->curve_ob);
657
658                 dag_add_relation(forest, curNode, obNode,
659                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
660         }
661         if (amd->offset_ob) {
662                 DagNode *curNode = dag_get_node(forest, amd->offset_ob);
663
664                 dag_add_relation(forest, curNode, obNode,
665                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
666         }
667 }
668
669 float vertarray_size(MVert *mvert, int numVerts, int axis)
670 {
671         int i;
672         float min_co, max_co;
673
674         /* if there are no vertices, width is 0 */
675         if(numVerts == 0) return 0;
676
677         /* find the minimum and maximum coordinates on the desired axis */
678         min_co = max_co = mvert->co[axis];
679         ++mvert;
680         for(i = 1; i < numVerts; ++i, ++mvert) {
681                 if(mvert->co[axis] < min_co) min_co = mvert->co[axis];
682                 if(mvert->co[axis] > max_co) max_co = mvert->co[axis];
683         }
684
685         return max_co - min_co;
686 }
687
688 typedef struct IndexMapEntry {
689         /* the new vert index that this old vert index maps to */
690         int new;
691         /* -1 if this vert isn't merged, otherwise the old vert index it
692         * should be replaced with
693         */
694         int merge;
695         /* 1 if this vert's first copy is merged with the last copy of its
696         * merge target, otherwise 0
697         */
698         short merge_final;
699 } IndexMapEntry;
700
701 /* indexMap - an array of IndexMap entries
702  * oldIndex - the old index to map
703  * copyNum - the copy number to map to (original = 0, first copy = 1, etc.)
704  */
705 static int calc_mapping(IndexMapEntry *indexMap, int oldIndex, int copyNum)
706 {
707         if(indexMap[oldIndex].merge < 0) {
708                 /* vert wasn't merged, so use copy of this vert */
709                 return indexMap[oldIndex].new + copyNum;
710         } else if(indexMap[oldIndex].merge == oldIndex) {
711                 /* vert was merged with itself */
712                 return indexMap[oldIndex].new;
713         } else {
714                 /* vert was merged with another vert */
715                 /* follow the chain of merges to the end, or until we've passed
716                 * a number of vertices equal to the copy number
717                 */
718                 if(copyNum <= 0)
719                         return indexMap[oldIndex].new;
720                 else
721                         return calc_mapping(indexMap, indexMap[oldIndex].merge,
722                                             copyNum - 1);
723         }
724 }
725
726 static DerivedMesh *arrayModifier_doArray(ArrayModifierData *amd,
727                                           Object *ob, DerivedMesh *dm,
728        int initFlags)
729 {
730         int i, j;
731         /* offset matrix */
732         float offset[4][4];
733         float final_offset[4][4];
734         float tmp_mat[4][4];
735         float length = amd->length;
736         int count = amd->count;
737         int numVerts, numEdges, numFaces;
738         int maxVerts, maxEdges, maxFaces;
739         int finalVerts, finalEdges, finalFaces;
740         DerivedMesh *result, *start_cap = NULL, *end_cap = NULL;
741         MVert *mvert, *src_mvert;
742         MEdge *medge;
743         MFace *mface;
744
745         IndexMapEntry *indexMap;
746
747         EdgeHash *edges;
748
749         /* need to avoid infinite recursion here */
750         if(amd->start_cap && amd->start_cap != ob)
751                 start_cap = mesh_get_derived_final(amd->start_cap, CD_MASK_MESH);
752         if(amd->end_cap && amd->end_cap != ob)
753                 end_cap = mesh_get_derived_final(amd->end_cap, CD_MASK_MESH);
754
755         MTC_Mat4One(offset);
756
757         indexMap = MEM_callocN(sizeof(*indexMap) * dm->getNumVerts(dm),
758                                "indexmap");
759
760         src_mvert = dm->getVertArray(dm);
761
762         maxVerts = dm->getNumVerts(dm);
763
764         if(amd->offset_type & MOD_ARR_OFF_CONST)
765                 VecAddf(offset[3], offset[3], amd->offset);
766         if(amd->offset_type & MOD_ARR_OFF_RELATIVE) {
767                 for(j = 0; j < 3; j++)
768                         offset[3][j] += amd->scale[j] * vertarray_size(src_mvert,
769                                         maxVerts, j);
770         }
771
772         if((amd->offset_type & MOD_ARR_OFF_OBJ) && (amd->offset_ob)) {
773                 float obinv[4][4];
774                 float result_mat[4][4];
775
776                 if(ob)
777                         MTC_Mat4Invert(obinv, ob->obmat);
778                 else
779                         MTC_Mat4One(obinv);
780
781                 MTC_Mat4MulSerie(result_mat, offset,
782                                  obinv, amd->offset_ob->obmat,
783      NULL, NULL, NULL, NULL, NULL);
784                 MTC_Mat4CpyMat4(offset, result_mat);
785         }
786
787         if(amd->fit_type == MOD_ARR_FITCURVE && amd->curve_ob) {
788                 Curve *cu = amd->curve_ob->data;
789                 if(cu) {
790                         if(!cu->path) {
791                                 cu->flag |= CU_PATH; // needed for path & bevlist
792                                 makeDispListCurveTypes(amd->curve_ob, 0);
793                         }
794                         if(cu->path)
795                                 length = cu->path->totdist;
796                 }
797         }
798
799         /* calculate the maximum number of copies which will fit within the
800         prescribed length */
801         if(amd->fit_type == MOD_ARR_FITLENGTH
802                   || amd->fit_type == MOD_ARR_FITCURVE) {
803                 float dist = sqrt(MTC_dot3Float(offset[3], offset[3]));
804
805                 if(dist > 1e-6f)
806                         /* this gives length = first copy start to last copy end
807                         add a tiny offset for floating point rounding errors */
808                         count = (length + 1e-6f) / dist;
809                 else
810                         /* if the offset has no translation, just make one copy */
811                         count = 1;
812                   }
813
814                   if(count < 1)
815                           count = 1;
816
817         /* allocate memory for count duplicates (including original) plus
818                   * start and end caps
819         */
820                   finalVerts = dm->getNumVerts(dm) * count;
821                   finalEdges = dm->getNumEdges(dm) * count;
822                   finalFaces = dm->getNumFaces(dm) * count;
823                   if(start_cap) {
824                           finalVerts += start_cap->getNumVerts(start_cap);
825                           finalEdges += start_cap->getNumEdges(start_cap);
826                           finalFaces += start_cap->getNumFaces(start_cap);
827                   }
828                   if(end_cap) {
829                           finalVerts += end_cap->getNumVerts(end_cap);
830                           finalEdges += end_cap->getNumEdges(end_cap);
831                           finalFaces += end_cap->getNumFaces(end_cap);
832                   }
833                   result = CDDM_from_template(dm, finalVerts, finalEdges, finalFaces);
834
835                   /* calculate the offset matrix of the final copy (for merging) */ 
836                   MTC_Mat4One(final_offset);
837
838                   for(j=0; j < count - 1; j++) {
839                           MTC_Mat4MulMat4(tmp_mat, final_offset, offset);
840                           MTC_Mat4CpyMat4(final_offset, tmp_mat);
841                   }
842
843                   numVerts = numEdges = numFaces = 0;
844                   mvert = CDDM_get_verts(result);
845
846                   for (i = 0; i < maxVerts; i++) {
847                           MVert *inMV;
848                           MVert *mv = &mvert[numVerts];
849                           MVert *mv2;
850                           float co[3];
851
852                           inMV = &src_mvert[i];
853
854                           DM_copy_vert_data(dm, result, i, numVerts, 1);
855                           *mv = *inMV;
856                           numVerts++;
857
858                           indexMap[i].new = numVerts - 1;
859                           indexMap[i].merge = -1; /* default to no merge */
860                           indexMap[i].merge_final = 0; /* default to no merge */
861
862                           VECCOPY(co, mv->co);
863                 
864                 /* Attempts to merge verts from one duplicate with verts from the
865                           * next duplicate which are closer than amd->merge_dist.
866                           * Only the first such vert pair is merged.
867                           * If verts are merged in the first duplicate pair, they are merged
868                           * in all pairs.
869                 */
870                           if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
871                                   float tmp_co[3];
872                                   VECCOPY(tmp_co, mv->co);
873                                   MTC_Mat4MulVecfl(offset, tmp_co);
874
875                                   for(j = 0; j < maxVerts; j++) {
876                                           /* if vertex already merged, don't use it */
877                                           if( indexMap[j].merge != -1 ) continue;
878
879                                           inMV = &src_mvert[j];
880                                           /* if this vert is within merge limit, merge */
881                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
882                                                   indexMap[i].merge = j;
883
884                                                   /* test for merging with final copy of merge target */
885                                                   if(amd->flags & MOD_ARR_MERGEFINAL) {
886                                                           VECCOPY(tmp_co, inMV->co);
887                                                           inMV = &src_mvert[i];
888                                                           MTC_Mat4MulVecfl(final_offset, tmp_co);
889                                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
890                                                                   indexMap[i].merge_final = 1;
891                                                   }
892                                                   break;
893                                           }
894                                   }
895                           }
896
897                           /* if no merging, generate copies of this vert */
898                           if(indexMap[i].merge < 0) {
899                                   for(j=0; j < count - 1; j++) {
900                                           mv2 = &mvert[numVerts];
901
902                                           DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
903                                           *mv2 = *mv;
904                                           numVerts++;
905
906                                           MTC_Mat4MulVecfl(offset, co);
907                                           VECCOPY(mv2->co, co);
908                                   }
909                           } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
910                         /* if this vert is not merging with itself, and it is merging
911                                   * with the final copy of its merge target, remove the first copy
912                         */
913                                   numVerts--;
914                                   DM_free_vert_data(result, numVerts, 1);
915                           }
916                   }
917
918                   /* make a hashtable so we can avoid duplicate edges from merging */
919                   edges = BLI_edgehash_new();
920
921                   maxEdges = dm->getNumEdges(dm);
922                   medge = CDDM_get_edges(result);
923                   for(i = 0; i < maxEdges; i++) {
924                           MEdge inMED;
925                           MEdge med;
926                           MEdge *med2;
927                           int vert1, vert2;
928
929                           dm->getEdge(dm, i, &inMED);
930
931                           med = inMED;
932                           med.v1 = indexMap[inMED.v1].new;
933                           med.v2 = indexMap[inMED.v2].new;
934
935                 /* if vertices are to be merged with the final copies of their
936                           * merge targets, calculate that final copy
937                 */
938                           if(indexMap[inMED.v1].merge_final) {
939                                   med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
940                                                   count - 1);
941                           }
942                           if(indexMap[inMED.v2].merge_final) {
943                                   med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
944                                                   count - 1);
945                           }
946
947                           if(med.v1 == med.v2) continue;
948
949                           if (initFlags) {
950                                   med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
951                           }
952
953                           if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
954                                   DM_copy_edge_data(dm, result, i, numEdges, 1);
955                                   medge[numEdges] = med;
956                                   numEdges++;
957
958                                   BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
959                           }
960
961                           for(j = 1; j < count; j++)
962                           {
963                                   vert1 = calc_mapping(indexMap, inMED.v1, j);
964                                   vert2 = calc_mapping(indexMap, inMED.v2, j);
965                                   /* avoid duplicate edges */
966                                   if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
967                                           med2 = &medge[numEdges];
968
969                                           DM_copy_edge_data(dm, result, i, numEdges, 1);
970                                           *med2 = med;
971                                           numEdges++;
972
973                                           med2->v1 = vert1;
974                                           med2->v2 = vert2;
975
976                                           BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
977                                   }
978                           }
979                   }
980
981                   maxFaces = dm->getNumFaces(dm);
982                   mface = CDDM_get_faces(result);
983                   for (i=0; i < maxFaces; i++) {
984                           MFace inMF;
985                           MFace *mf = &mface[numFaces];
986
987                           dm->getFace(dm, i, &inMF);
988
989                           DM_copy_face_data(dm, result, i, numFaces, 1);
990                           *mf = inMF;
991
992                           mf->v1 = indexMap[inMF.v1].new;
993                           mf->v2 = indexMap[inMF.v2].new;
994                           mf->v3 = indexMap[inMF.v3].new;
995                           if(inMF.v4)
996                                   mf->v4 = indexMap[inMF.v4].new;
997
998                 /* if vertices are to be merged with the final copies of their
999                           * merge targets, calculate that final copy
1000                 */
1001                           if(indexMap[inMF.v1].merge_final)
1002                                   mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
1003                           if(indexMap[inMF.v2].merge_final)
1004                                   mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
1005                           if(indexMap[inMF.v3].merge_final)
1006                                   mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
1007                           if(inMF.v4 && indexMap[inMF.v4].merge_final)
1008                                   mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
1009
1010                           if(test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3) < 3)
1011                                   continue;
1012
1013                           numFaces++;
1014
1015                           /* if the face has fewer than 3 vertices, don't create it */
1016                           if(mf->v3 == 0 || (mf->v1 && (mf->v1 == mf->v3 || mf->v1 == mf->v4))) {
1017                                   numFaces--;
1018                                   DM_free_face_data(result, numFaces, 1);
1019                           }
1020
1021                           for(j = 1; j < count; j++)
1022                           {
1023                                   MFace *mf2 = &mface[numFaces];
1024
1025                                   DM_copy_face_data(dm, result, i, numFaces, 1);
1026                                   *mf2 = *mf;
1027
1028                                   mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
1029                                   mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
1030                                   mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
1031                                   if (inMF.v4)
1032                                           mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
1033
1034                                   test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1035                                   numFaces++;
1036
1037                                   /* if the face has fewer than 3 vertices, don't create it */
1038                                   if(mf2->v3 == 0 || (mf2->v1 && (mf2->v1 == mf2->v3 || mf2->v1 ==
1039                                                                  mf2->v4))) {
1040                                           numFaces--;
1041                                           DM_free_face_data(result, numFaces, 1);
1042                                                                  }
1043                           }
1044                   }
1045
1046                   /* add start and end caps */
1047                   if(start_cap) {
1048                           float startoffset[4][4];
1049                           MVert *cap_mvert;
1050                           MEdge *cap_medge;
1051                           MFace *cap_mface;
1052                           int *origindex;
1053                           int *vert_map;
1054                           int capVerts, capEdges, capFaces;
1055
1056                           capVerts = start_cap->getNumVerts(start_cap);
1057                           capEdges = start_cap->getNumEdges(start_cap);
1058                           capFaces = start_cap->getNumFaces(start_cap);
1059                           cap_mvert = start_cap->getVertArray(start_cap);
1060                           cap_medge = start_cap->getEdgeArray(start_cap);
1061                           cap_mface = start_cap->getFaceArray(start_cap);
1062
1063                           Mat4Invert(startoffset, offset);
1064
1065                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1066                                           "arrayModifier_doArray vert_map");
1067
1068                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1069                           for(i = 0; i < capVerts; i++) {
1070                                   MVert *mv = &cap_mvert[i];
1071                                   short merged = 0;
1072
1073                                   if(amd->flags & MOD_ARR_MERGE) {
1074                                           float tmp_co[3];
1075                                           MVert *in_mv;
1076                                           int j;
1077
1078                                           VECCOPY(tmp_co, mv->co);
1079                                           Mat4MulVecfl(startoffset, tmp_co);
1080
1081                                           for(j = 0; j < maxVerts; j++) {
1082                                                   in_mv = &src_mvert[j];
1083                                                   /* if this vert is within merge limit, merge */
1084                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1085                                                           vert_map[i] = calc_mapping(indexMap, j, 0);
1086                                                           merged = 1;
1087                                                           break;
1088                                                   }
1089                                           }
1090                                   }
1091
1092                                   if(!merged) {
1093                                           DM_copy_vert_data(start_cap, result, i, numVerts, 1);
1094                                           mvert[numVerts] = *mv;
1095                                           Mat4MulVecfl(startoffset, mvert[numVerts].co);
1096                                           origindex[numVerts] = ORIGINDEX_NONE;
1097
1098                                           vert_map[i] = numVerts;
1099
1100                                           numVerts++;
1101                                   }
1102                           }
1103                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1104                           for(i = 0; i < capEdges; i++) {
1105                                   int v1, v2;
1106
1107                                   v1 = vert_map[cap_medge[i].v1];
1108                                   v2 = vert_map[cap_medge[i].v2];
1109
1110                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1111                                           DM_copy_edge_data(start_cap, result, i, numEdges, 1);
1112                                           medge[numEdges] = cap_medge[i];
1113                                           medge[numEdges].v1 = v1;
1114                                           medge[numEdges].v2 = v2;
1115                                           origindex[numEdges] = ORIGINDEX_NONE;
1116
1117                                           numEdges++;
1118                                   }
1119                           }
1120                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1121                           for(i = 0; i < capFaces; i++) {
1122                                   DM_copy_face_data(start_cap, result, i, numFaces, 1);
1123                                   mface[numFaces] = cap_mface[i];
1124                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1125                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1126                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1127                                   if(mface[numFaces].v4)
1128                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1129                                   origindex[numFaces] = ORIGINDEX_NONE;
1130
1131                                   numFaces++;
1132                           }
1133
1134                           MEM_freeN(vert_map);
1135                           start_cap->release(start_cap);
1136                   }
1137
1138                   if(end_cap) {
1139                           float endoffset[4][4];
1140                           MVert *cap_mvert;
1141                           MEdge *cap_medge;
1142                           MFace *cap_mface;
1143                           int *origindex;
1144                           int *vert_map;
1145                           int capVerts, capEdges, capFaces;
1146
1147                           capVerts = end_cap->getNumVerts(end_cap);
1148                           capEdges = end_cap->getNumEdges(end_cap);
1149                           capFaces = end_cap->getNumFaces(end_cap);
1150                           cap_mvert = end_cap->getVertArray(end_cap);
1151                           cap_medge = end_cap->getEdgeArray(end_cap);
1152                           cap_mface = end_cap->getFaceArray(end_cap);
1153
1154                           Mat4MulMat4(endoffset, final_offset, offset);
1155
1156                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1157                                           "arrayModifier_doArray vert_map");
1158
1159                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1160                           for(i = 0; i < capVerts; i++) {
1161                                   MVert *mv = &cap_mvert[i];
1162                                   short merged = 0;
1163
1164                                   if(amd->flags & MOD_ARR_MERGE) {
1165                                           float tmp_co[3];
1166                                           MVert *in_mv;
1167                                           int j;
1168
1169                                           VECCOPY(tmp_co, mv->co);
1170                                           Mat4MulVecfl(offset, tmp_co);
1171
1172                                           for(j = 0; j < maxVerts; j++) {
1173                                                   in_mv = &src_mvert[j];
1174                                                   /* if this vert is within merge limit, merge */
1175                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1176                                                           vert_map[i] = calc_mapping(indexMap, j, count - 1);
1177                                                           merged = 1;
1178                                                           break;
1179                                                   }
1180                                           }
1181                                   }
1182
1183                                   if(!merged) {
1184                                           DM_copy_vert_data(end_cap, result, i, numVerts, 1);
1185                                           mvert[numVerts] = *mv;
1186                                           Mat4MulVecfl(endoffset, mvert[numVerts].co);
1187                                           origindex[numVerts] = ORIGINDEX_NONE;
1188
1189                                           vert_map[i] = numVerts;
1190
1191                                           numVerts++;
1192                                   }
1193                           }
1194                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1195                           for(i = 0; i < capEdges; i++) {
1196                                   int v1, v2;
1197
1198                                   v1 = vert_map[cap_medge[i].v1];
1199                                   v2 = vert_map[cap_medge[i].v2];
1200
1201                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1202                                           DM_copy_edge_data(end_cap, result, i, numEdges, 1);
1203                                           medge[numEdges] = cap_medge[i];
1204                                           medge[numEdges].v1 = v1;
1205                                           medge[numEdges].v2 = v2;
1206                                           origindex[numEdges] = ORIGINDEX_NONE;
1207
1208                                           numEdges++;
1209                                   }
1210                           }
1211                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1212                           for(i = 0; i < capFaces; i++) {
1213                                   DM_copy_face_data(end_cap, result, i, numFaces, 1);
1214                                   mface[numFaces] = cap_mface[i];
1215                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1216                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1217                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1218                                   if(mface[numFaces].v4)
1219                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1220                                   origindex[numFaces] = ORIGINDEX_NONE;
1221
1222                                   numFaces++;
1223                           }
1224
1225                           MEM_freeN(vert_map);
1226                           end_cap->release(end_cap);
1227                   }
1228
1229                   BLI_edgehash_free(edges, NULL);
1230                   MEM_freeN(indexMap);
1231
1232                   CDDM_lower_num_verts(result, numVerts);
1233                   CDDM_lower_num_edges(result, numEdges);
1234                   CDDM_lower_num_faces(result, numFaces);
1235
1236                   return result;
1237 }
1238
1239 static DerivedMesh *arrayModifier_applyModifier(
1240                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1241   int useRenderParams, int isFinalCalc)
1242 {
1243         DerivedMesh *result;
1244         ArrayModifierData *amd = (ArrayModifierData*) md;
1245
1246         result = arrayModifier_doArray(amd, ob, derivedData, 0);
1247
1248         CDDM_calc_normals(result);
1249
1250         return result;
1251 }
1252
1253 static DerivedMesh *arrayModifier_applyModifierEM(
1254                 ModifierData *md, Object *ob, EditMesh *editData,
1255   DerivedMesh *derivedData)
1256 {
1257         return arrayModifier_applyModifier(md, ob, derivedData, 0, 1);
1258 }
1259
1260 /* Mirror */
1261
1262 static void mirrorModifier_initData(ModifierData *md)
1263 {
1264         MirrorModifierData *mmd = (MirrorModifierData*) md;
1265
1266         mmd->flag |= MOD_MIR_AXIS_X;
1267         mmd->tolerance = 0.001;
1268         mmd->mirror_ob = NULL;
1269 }
1270
1271 static void mirrorModifier_copyData(ModifierData *md, ModifierData *target)
1272 {
1273         MirrorModifierData *mmd = (MirrorModifierData*) md;
1274         MirrorModifierData *tmmd = (MirrorModifierData*) target;
1275
1276         tmmd->axis = mmd->axis;
1277         tmmd->flag = mmd->flag;
1278         tmmd->tolerance = mmd->tolerance;
1279         tmmd->mirror_ob = mmd->mirror_ob;;
1280 }
1281
1282 static void mirrorModifier_foreachObjectLink(
1283                                              ModifierData *md, Object *ob,
1284           void (*walk)(void *userData, Object *ob, Object **obpoin),
1285                  void *userData)
1286 {
1287         MirrorModifierData *mmd = (MirrorModifierData*) md;
1288
1289         walk(userData, ob, &mmd->mirror_ob);
1290 }
1291
1292 static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
1293                                           Object *ob, DagNode *obNode)
1294 {
1295         MirrorModifierData *mmd = (MirrorModifierData*) md;
1296
1297         if(mmd->mirror_ob) {
1298                 DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
1299
1300                 dag_add_relation(forest, latNode, obNode,
1301                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
1302         }
1303 }
1304
1305 static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
1306                                    Object *ob,
1307        DerivedMesh *dm,
1308        int initFlags,
1309        int axis)
1310 {
1311         int i;
1312         float tolerance = mmd->tolerance;
1313         DerivedMesh *result;
1314         int numVerts, numEdges, numFaces;
1315         int maxVerts = dm->getNumVerts(dm);
1316         int maxEdges = dm->getNumEdges(dm);
1317         int maxFaces = dm->getNumFaces(dm);
1318         int (*indexMap)[2];
1319         float mtx[4][4], imtx[4][4];
1320
1321         numVerts = numEdges = numFaces = 0;
1322
1323         indexMap = MEM_mallocN(sizeof(*indexMap) * maxVerts, "indexmap");
1324
1325         result = CDDM_from_template(dm, maxVerts * 2, maxEdges * 2, maxFaces * 2);
1326
1327         if (mmd->mirror_ob) {
1328                 float obinv[4][4];
1329
1330                 Mat4Invert(obinv, mmd->mirror_ob->obmat);
1331                 Mat4MulMat4(mtx, ob->obmat, obinv);
1332                 Mat4Invert(imtx, mtx);
1333         }
1334
1335         for(i = 0; i < maxVerts; i++) {
1336                 MVert inMV;
1337                 MVert *mv = CDDM_get_vert(result, numVerts);
1338                 int isShared;
1339                 float co[3];
1340
1341                 dm->getVert(dm, i, &inMV);
1342
1343                 VecCopyf(co, inMV.co);
1344
1345                 if (mmd->mirror_ob) {
1346                         VecMat4MulVecfl(co, mtx, co);
1347                 }
1348                 isShared = ABS(co[axis])<=tolerance;
1349
1350                 /* Because the topology result (# of vertices) must be the same if
1351                 * the mesh data is overridden by vertex cos, have to calc sharedness
1352                 * based on original coordinates. This is why we test before copy.
1353                 */
1354                 DM_copy_vert_data(dm, result, i, numVerts, 1);
1355                 *mv = inMV;
1356                 numVerts++;
1357
1358                 indexMap[i][0] = numVerts - 1;
1359                 indexMap[i][1] = !isShared;
1360
1361                 if(isShared) {
1362                         co[axis] = 0;
1363                         if (mmd->mirror_ob) {
1364                                 VecMat4MulVecfl(co, imtx, co);
1365                         }
1366                         VecCopyf(mv->co, co);
1367                         
1368                         mv->flag |= ME_VERT_MERGED;
1369                 } else {
1370                         MVert *mv2 = CDDM_get_vert(result, numVerts);
1371
1372                         DM_copy_vert_data(dm, result, i, numVerts, 1);
1373                         *mv2 = *mv;
1374                         numVerts++;
1375
1376                         co[axis] = -co[axis];
1377                         if (mmd->mirror_ob) {
1378                                 VecMat4MulVecfl(co, imtx, co);
1379                         }
1380                         VecCopyf(mv2->co, co);
1381                 }
1382         }
1383
1384         for(i = 0; i < maxEdges; i++) {
1385                 MEdge inMED;
1386                 MEdge *med = CDDM_get_edge(result, numEdges);
1387
1388                 dm->getEdge(dm, i, &inMED);
1389
1390                 DM_copy_edge_data(dm, result, i, numEdges, 1);
1391                 *med = inMED;
1392                 numEdges++;
1393
1394                 med->v1 = indexMap[inMED.v1][0];
1395                 med->v2 = indexMap[inMED.v2][0];
1396                 if(initFlags)
1397                         med->flag |= ME_EDGEDRAW | ME_EDGERENDER;
1398
1399                 if(indexMap[inMED.v1][1] || indexMap[inMED.v2][1]) {
1400                         MEdge *med2 = CDDM_get_edge(result, numEdges);
1401
1402                         DM_copy_edge_data(dm, result, i, numEdges, 1);
1403                         *med2 = *med;
1404                         numEdges++;
1405
1406                         med2->v1 += indexMap[inMED.v1][1];
1407                         med2->v2 += indexMap[inMED.v2][1];
1408                 }
1409         }
1410
1411         for(i = 0; i < maxFaces; i++) {
1412                 MFace inMF;
1413                 MFace *mf = CDDM_get_face(result, numFaces);
1414
1415                 dm->getFace(dm, i, &inMF);
1416
1417                 DM_copy_face_data(dm, result, i, numFaces, 1);
1418                 *mf = inMF;
1419                 numFaces++;
1420
1421                 mf->v1 = indexMap[inMF.v1][0];
1422                 mf->v2 = indexMap[inMF.v2][0];
1423                 mf->v3 = indexMap[inMF.v3][0];
1424                 mf->v4 = indexMap[inMF.v4][0];
1425                 
1426                 if(indexMap[inMF.v1][1]
1427                                  || indexMap[inMF.v2][1]
1428                                  || indexMap[inMF.v3][1]
1429                                  || (mf->v4 && indexMap[inMF.v4][1])) {
1430                         MFace *mf2 = CDDM_get_face(result, numFaces);
1431                         static int corner_indices[4] = {2, 1, 0, 3};
1432
1433                         DM_copy_face_data(dm, result, i, numFaces, 1);
1434                         *mf2 = *mf;
1435
1436                         mf2->v1 += indexMap[inMF.v1][1];
1437                         mf2->v2 += indexMap[inMF.v2][1];
1438                         mf2->v3 += indexMap[inMF.v3][1];
1439                         if(inMF.v4) mf2->v4 += indexMap[inMF.v4][1];
1440
1441                         /* mirror UVs if enabled */
1442                         if(mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
1443                                 MTFace *tf = result->getFaceData(result, numFaces, CD_MTFACE);
1444                                 if(tf) {
1445                                         int j;
1446                                         for(j = 0; j < 4; ++j) {
1447                                                 if(mmd->flag & MOD_MIR_MIRROR_U)
1448                                                         tf->uv[j][0] = 1.0f - tf->uv[j][0];
1449                                                 if(mmd->flag & MOD_MIR_MIRROR_V)
1450                                                         tf->uv[j][1] = 1.0f - tf->uv[j][1];
1451                                         }
1452                                 }
1453                         }
1454
1455                         /* Flip face normal */
1456                         SWAP(int, mf2->v1, mf2->v3);
1457                         DM_swap_face_data(result, numFaces, corner_indices);
1458
1459                         test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1460                         numFaces++;
1461                                  }
1462         }
1463
1464         MEM_freeN(indexMap);
1465
1466         CDDM_lower_num_verts(result, numVerts);
1467         CDDM_lower_num_edges(result, numEdges);
1468         CDDM_lower_num_faces(result, numFaces);
1469
1470         return result;
1471 }
1472
1473 static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
1474                                              Object *ob, DerivedMesh *dm,
1475           int initFlags)
1476 {
1477         DerivedMesh *result = dm;
1478
1479         /* check which axes have been toggled and mirror accordingly */
1480         if(mmd->flag & MOD_MIR_AXIS_X) {
1481                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 0);
1482         }
1483         if(mmd->flag & MOD_MIR_AXIS_Y) {
1484                 DerivedMesh *tmp = result;
1485                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 1);
1486                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1487         }
1488         if(mmd->flag & MOD_MIR_AXIS_Z) {
1489                 DerivedMesh *tmp = result;
1490                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 2);
1491                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1492         }
1493
1494         return result;
1495 }
1496
1497 static DerivedMesh *mirrorModifier_applyModifier(
1498                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1499   int useRenderParams, int isFinalCalc)
1500 {
1501         DerivedMesh *result;
1502         MirrorModifierData *mmd = (MirrorModifierData*) md;
1503
1504         result = mirrorModifier__doMirror(mmd, ob, derivedData, 0);
1505
1506         CDDM_calc_normals(result);
1507         
1508         return result;
1509 }
1510
1511 static DerivedMesh *mirrorModifier_applyModifierEM(
1512                 ModifierData *md, Object *ob, EditMesh *editData,
1513   DerivedMesh *derivedData)
1514 {
1515         return mirrorModifier_applyModifier(md, ob, derivedData, 0, 1);
1516 }
1517
1518 /* EdgeSplit */
1519 /* EdgeSplit modifier: Splits edges in the mesh according to sharpness flag
1520  * or edge angle (can be used to achieve autosmoothing)
1521 */
1522 #if 0
1523 #define EDGESPLIT_DEBUG_3
1524 #define EDGESPLIT_DEBUG_2
1525 #define EDGESPLIT_DEBUG_1
1526 #define EDGESPLIT_DEBUG_0
1527 #endif
1528
1529 static void edgesplitModifier_initData(ModifierData *md)
1530 {
1531         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1532
1533         /* default to 30-degree split angle, sharpness from both angle & flag
1534         */
1535         emd->split_angle = 30;
1536         emd->flags = MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG;
1537 }
1538
1539 static void edgesplitModifier_copyData(ModifierData *md, ModifierData *target)
1540 {
1541         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1542         EdgeSplitModifierData *temd = (EdgeSplitModifierData*) target;
1543
1544         temd->split_angle = emd->split_angle;
1545         temd->flags = emd->flags;
1546 }
1547
1548 /* Mesh data for edgesplit operation */
1549 typedef struct SmoothVert {
1550         LinkNode *faces;     /* all faces which use this vert */
1551         int oldIndex; /* the index of the original DerivedMesh vert */
1552         int newIndex; /* the index of the new DerivedMesh vert */
1553 } SmoothVert;
1554
1555 #define SMOOTHEDGE_NUM_VERTS 2
1556
1557 typedef struct SmoothEdge {
1558         SmoothVert *verts[SMOOTHEDGE_NUM_VERTS]; /* the verts used by this edge */
1559         LinkNode *faces;     /* all faces which use this edge */
1560         int oldIndex; /* the index of the original DerivedMesh edge */
1561         int newIndex; /* the index of the new DerivedMesh edge */
1562         short flag; /* the flags from the original DerivedMesh edge */
1563 } SmoothEdge;
1564
1565 #define SMOOTHFACE_MAX_EDGES 4
1566
1567 typedef struct SmoothFace {
1568         SmoothEdge *edges[SMOOTHFACE_MAX_EDGES]; /* nonexistent edges == NULL */
1569         int flip[SMOOTHFACE_MAX_EDGES]; /* 1 = flip edge dir, 0 = don't flip */
1570         float normal[3]; /* the normal of this face */
1571         int oldIndex; /* the index of the original DerivedMesh face */
1572         int newIndex; /* the index of the new DerivedMesh face */
1573 } SmoothFace;
1574
1575 typedef struct SmoothMesh {
1576         SmoothVert *verts;
1577         SmoothEdge *edges;
1578         SmoothFace *faces;
1579         int num_verts, num_edges, num_faces;
1580         int max_verts, max_edges, max_faces;
1581         DerivedMesh *dm;
1582         float threshold; /* the cosine of the smoothing angle */
1583         int flags;
1584 } SmoothMesh;
1585
1586 static SmoothVert *smoothvert_copy(SmoothVert *vert, SmoothMesh *mesh)
1587 {
1588         SmoothVert *copy = &mesh->verts[mesh->num_verts];
1589
1590         if(mesh->num_verts >= mesh->max_verts) {
1591                 printf("Attempted to add a SmoothMesh vert beyond end of array\n");
1592                 return NULL;
1593         }
1594
1595         *copy = *vert;
1596         copy->faces = NULL;
1597         copy->newIndex = mesh->num_verts;
1598         ++mesh->num_verts;
1599
1600 #ifdef EDGESPLIT_DEBUG_2
1601         printf("copied vert %4d to vert %4d\n", vert->newIndex, copy->newIndex);
1602 #endif
1603         return copy;
1604 }
1605
1606 static SmoothEdge *smoothedge_copy(SmoothEdge *edge, SmoothMesh *mesh)
1607 {
1608         SmoothEdge *copy = &mesh->edges[mesh->num_edges];
1609
1610         if(mesh->num_edges >= mesh->max_edges) {
1611                 printf("Attempted to add a SmoothMesh edge beyond end of array\n");
1612                 return NULL;
1613         }
1614
1615         *copy = *edge;
1616         copy->faces = NULL;
1617         copy->newIndex = mesh->num_edges;
1618         ++mesh->num_edges;
1619
1620 #ifdef EDGESPLIT_DEBUG_2
1621         printf("copied edge %4d to edge %4d\n", edge->newIndex, copy->newIndex);
1622 #endif
1623         return copy;
1624 }
1625
1626 static int smoothedge_has_vert(SmoothEdge *edge, SmoothVert *vert)
1627 {
1628         int i;
1629         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++)
1630                 if(edge->verts[i] == vert) return 1;
1631
1632         return 0;
1633 }
1634
1635 static SmoothMesh *smoothmesh_new(int num_verts, int num_edges, int num_faces,
1636                                   int max_verts, int max_edges, int max_faces)
1637 {
1638         SmoothMesh *mesh = MEM_callocN(sizeof(*mesh), "smoothmesh");
1639         mesh->verts = MEM_callocN(sizeof(*mesh->verts) * max_verts,
1640                                   "SmoothMesh.verts");
1641         mesh->edges = MEM_callocN(sizeof(*mesh->edges) * max_edges,
1642                                   "SmoothMesh.edges");
1643         mesh->faces = MEM_callocN(sizeof(*mesh->faces) * max_faces,
1644                                   "SmoothMesh.faces");
1645
1646         mesh->num_verts = num_verts;
1647         mesh->num_edges = num_edges;
1648         mesh->num_faces = num_faces;
1649
1650         mesh->max_verts = max_verts;
1651         mesh->max_edges = max_edges;
1652         mesh->max_faces = max_faces;
1653
1654         return mesh;
1655 }
1656
1657 static void smoothmesh_free(SmoothMesh *mesh)
1658 {
1659         int i;
1660
1661         for(i = 0; i < mesh->num_verts; ++i)
1662                 BLI_linklist_free(mesh->verts[i].faces, NULL);
1663
1664         for(i = 0; i < mesh->num_edges; ++i)
1665                 BLI_linklist_free(mesh->edges[i].faces, NULL);
1666
1667         MEM_freeN(mesh->verts);
1668         MEM_freeN(mesh->edges);
1669         MEM_freeN(mesh->faces);
1670         MEM_freeN(mesh);
1671 }
1672
1673 static void smoothmesh_resize_verts(SmoothMesh *mesh, int max_verts)
1674 {
1675         int i;
1676         SmoothVert *tmp;
1677
1678         if(max_verts <= mesh->max_verts) return;
1679
1680         tmp = MEM_callocN(sizeof(*tmp) * max_verts, "SmoothMesh.verts");
1681
1682         memcpy(tmp, mesh->verts, sizeof(*tmp) * mesh->num_verts);
1683
1684         /* remap vert pointers in edges */
1685         for(i = 0; i < mesh->num_edges; ++i) {
1686                 int j;
1687                 SmoothEdge *edge = &mesh->edges[i];
1688
1689                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; ++j)
1690                         /* pointer arithmetic to get vert array index */
1691                         edge->verts[j] = &tmp[edge->verts[j] - mesh->verts];
1692         }
1693
1694         MEM_freeN(mesh->verts);
1695         mesh->verts = tmp;
1696         mesh->max_verts = max_verts;
1697 }
1698
1699 static void smoothmesh_resize_edges(SmoothMesh *mesh, int max_edges)
1700 {
1701         int i;
1702         SmoothEdge *tmp;
1703
1704         if(max_edges <= mesh->max_edges) return;
1705
1706         tmp = MEM_callocN(sizeof(*tmp) * max_edges, "SmoothMesh.edges");
1707
1708         memcpy(tmp, mesh->edges, sizeof(*tmp) * mesh->num_edges);
1709
1710         /* remap edge pointers in faces */
1711         for(i = 0; i < mesh->num_faces; ++i) {
1712                 int j;
1713                 SmoothFace *face = &mesh->faces[i];
1714
1715                 for(j = 0; j < SMOOTHFACE_MAX_EDGES; ++j)
1716                         if(face->edges[j])
1717                                 /* pointer arithmetic to get edge array index */
1718                                 face->edges[j] = &tmp[face->edges[j] - mesh->edges];
1719         }
1720
1721         MEM_freeN(mesh->edges);
1722         mesh->edges = tmp;
1723         mesh->max_edges = max_edges;
1724 }
1725
1726 #ifdef EDGESPLIT_DEBUG_0
1727 static void smoothmesh_print(SmoothMesh *mesh)
1728 {
1729         int i, j;
1730         DerivedMesh *dm = mesh->dm;
1731
1732         printf("--- SmoothMesh ---\n");
1733         printf("--- Vertices ---\n");
1734         for(i = 0; i < mesh->num_verts; i++) {
1735                 SmoothVert *vert = &mesh->verts[i];
1736                 LinkNode *node;
1737                 MVert mv;
1738
1739                 dm->getVert(dm, vert->oldIndex, &mv);
1740
1741                 printf("%3d: ind={%3d, %3d}, pos={% 5.1f, % 5.1f, % 5.1f}",
1742                        i, vert->oldIndex, vert->newIndex,
1743          mv.co[0], mv.co[1], mv.co[2]);
1744                 printf(", faces={");
1745                 for(node = vert->faces; node != NULL; node = node->next) {
1746                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1747                 }
1748                 printf("}\n");
1749         }
1750
1751         printf("\n--- Edges ---\n");
1752         for(i = 0; i < mesh->num_edges; i++) {
1753                 SmoothEdge *edge = &mesh->edges[i];
1754                 LinkNode *node;
1755
1756                 printf("%4d: indices={%4d, %4d}, verts={%4d, %4d}",
1757                        i,
1758          edge->oldIndex, edge->newIndex,
1759   edge->verts[0]->newIndex, edge->verts[1]->newIndex);
1760                 if(edge->verts[0] == edge->verts[1]) printf(" <- DUPLICATE VERTEX");
1761                 printf(", faces={");
1762                 for(node = edge->faces; node != NULL; node = node->next) {
1763                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1764                 }
1765                 printf("}\n");
1766         }
1767
1768         printf("\n--- Faces ---\n");
1769         for(i = 0; i < mesh->num_faces; i++) {
1770                 SmoothFace *face = &mesh->faces[i];
1771
1772                 printf("%4d: indices={%4d, %4d}, edges={", i,
1773                        face->oldIndex, face->newIndex);
1774                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1775                         if(face->flip[j])
1776                                 printf(" -%-2d", face->edges[j]->newIndex);
1777                         else
1778                                 printf("  %-2d", face->edges[j]->newIndex);
1779                 }
1780                 printf("}, verts={");
1781                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1782                         printf(" %d", face->edges[j]->verts[face->flip[j]]->newIndex);
1783                 }
1784                 printf("}\n");
1785         }
1786 }
1787 #endif
1788
1789 static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
1790 {
1791         SmoothMesh *mesh;
1792         EdgeHash *edges = BLI_edgehash_new();
1793         int i;
1794         int totvert, totedge, totface;
1795
1796         totvert = dm->getNumVerts(dm);
1797         totedge = dm->getNumEdges(dm);
1798         totface = dm->getNumFaces(dm);
1799
1800         mesh = smoothmesh_new(totvert, totedge, totface,
1801                               totvert, totedge, totface);
1802
1803         mesh->dm = dm;
1804
1805         for(i = 0; i < totvert; i++) {
1806                 SmoothVert *vert = &mesh->verts[i];
1807
1808                 vert->oldIndex = vert->newIndex = i;
1809         }
1810
1811         for(i = 0; i < totedge; i++) {
1812                 SmoothEdge *edge = &mesh->edges[i];
1813                 MEdge med;
1814
1815                 dm->getEdge(dm, i, &med);
1816                 edge->verts[0] = &mesh->verts[med.v1];
1817                 edge->verts[1] = &mesh->verts[med.v2];
1818                 edge->oldIndex = edge->newIndex = i;
1819                 edge->flag = med.flag;
1820
1821                 BLI_edgehash_insert(edges, med.v1, med.v2, edge);
1822         }
1823
1824         for(i = 0; i < totface; i++) {
1825                 SmoothFace *face = &mesh->faces[i];
1826                 MFace mf;
1827                 MVert v1, v2, v3;
1828                 int j;
1829
1830                 dm->getFace(dm, i, &mf);
1831
1832                 dm->getVert(dm, mf.v1, &v1);
1833                 dm->getVert(dm, mf.v2, &v2);
1834                 dm->getVert(dm, mf.v3, &v3);
1835                 face->edges[0] = BLI_edgehash_lookup(edges, mf.v1, mf.v2);
1836                 if(face->edges[0]->verts[1]->oldIndex == mf.v1) face->flip[0] = 1;
1837                 face->edges[1] = BLI_edgehash_lookup(edges, mf.v2, mf.v3);
1838                 if(face->edges[1]->verts[1]->oldIndex == mf.v2) face->flip[1] = 1;
1839                 if(mf.v4) {
1840                         MVert v4;
1841                         dm->getVert(dm, mf.v4, &v4);
1842                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v4);
1843                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
1844                         face->edges[3] = BLI_edgehash_lookup(edges, mf.v4, mf.v1);
1845                         if(face->edges[3]->verts[1]->oldIndex == mf.v4) face->flip[3] = 1;
1846                         CalcNormFloat4(v1.co, v2.co, v3.co, v4.co, face->normal);
1847                 } else {
1848                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v1);
1849                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
1850                         face->edges[3] = NULL;
1851                         CalcNormFloat(v1.co, v2.co, v3.co, face->normal);
1852                 }
1853
1854                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1855                         SmoothEdge *edge = face->edges[j];
1856                         BLI_linklist_prepend(&edge->faces, face);
1857                         BLI_linklist_prepend(&edge->verts[face->flip[j]]->faces, face);
1858                 }
1859
1860                 face->oldIndex = face->newIndex = i;
1861         }
1862
1863         BLI_edgehash_free(edges, NULL);
1864
1865         return mesh;
1866 }
1867
1868 static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
1869 {
1870         DerivedMesh *result = CDDM_from_template(mesh->dm,
1871                         mesh->num_verts,
1872    mesh->num_edges,
1873    mesh->num_faces);
1874         MVert *new_verts = CDDM_get_verts(result);
1875         MEdge *new_edges = CDDM_get_edges(result);
1876         MFace *new_faces = CDDM_get_faces(result);
1877         int i;
1878
1879         for(i = 0; i < mesh->num_verts; ++i) {
1880                 SmoothVert *vert = &mesh->verts[i];
1881                 MVert *newMV = &new_verts[vert->newIndex];
1882
1883                 DM_copy_vert_data(mesh->dm, result,
1884                                   vert->oldIndex, vert->newIndex, 1);
1885                 mesh->dm->getVert(mesh->dm, vert->oldIndex, newMV);
1886         }
1887
1888         for(i = 0; i < mesh->num_edges; ++i) {
1889                 SmoothEdge *edge = &mesh->edges[i];
1890                 MEdge *newME = &new_edges[edge->newIndex];
1891
1892                 DM_copy_edge_data(mesh->dm, result,
1893                                   edge->oldIndex, edge->newIndex, 1);
1894                 mesh->dm->getEdge(mesh->dm, edge->oldIndex, newME);
1895                 newME->v1 = edge->verts[0]->newIndex;
1896                 newME->v2 = edge->verts[1]->newIndex;
1897         }
1898
1899         for(i = 0; i < mesh->num_faces; ++i) {
1900                 SmoothFace *face = &mesh->faces[i];
1901                 MFace *newMF = &new_faces[face->newIndex];
1902
1903                 DM_copy_face_data(mesh->dm, result,
1904                                   face->oldIndex, face->newIndex, 1);
1905                 mesh->dm->getFace(mesh->dm, face->oldIndex, newMF);
1906
1907                 newMF->v1 = face->edges[0]->verts[face->flip[0]]->newIndex;
1908                 newMF->v2 = face->edges[1]->verts[face->flip[1]]->newIndex;
1909                 newMF->v3 = face->edges[2]->verts[face->flip[2]]->newIndex;
1910
1911                 if(face->edges[3]) {
1912                         newMF->v4 = face->edges[3]->verts[face->flip[3]]->newIndex;
1913                 } else {
1914                         newMF->v4 = 0;
1915                 }
1916         }
1917
1918         return result;
1919 }
1920
1921 /* returns the other vert in the given edge
1922  */
1923 static SmoothVert *other_vert(SmoothEdge *edge, SmoothVert *vert)
1924 {
1925         if(edge->verts[0] == vert) return edge->verts[1];
1926         else return edge->verts[0];
1927 }
1928
1929 /* returns the other edge in the given face that uses the given vert
1930  * returns NULL if no other edge in the given face uses the given vert
1931  * (this should never happen)
1932  */
1933 static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
1934                               SmoothEdge *edge)
1935 {
1936         int i,j;
1937         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
1938                 SmoothEdge *tmp_edge = face->edges[i];
1939                 if(tmp_edge == edge) continue;
1940
1941                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; j++)
1942                         if(tmp_edge->verts[j] == vert) return tmp_edge;
1943         }
1944
1945         /* if we get to here, something's wrong (there should always be 2 edges
1946         * which use the same vert in a face)
1947         */
1948         return NULL;
1949 }
1950
1951 /* returns a face attached to the given edge which is not the given face.
1952  * returns NULL if no other faces use this edge.
1953  */
1954 static SmoothFace *other_face(SmoothEdge *edge, SmoothFace *face)
1955 {
1956         LinkNode *node;
1957
1958         for(node = edge->faces; node != NULL; node = node->next)
1959                 if(node->link != face) return node->link;
1960
1961         return NULL;
1962 }
1963
1964 #if 0
1965 /* copies source list to target, overwriting target (target is not freed)
1966  * nodes in the copy will be in the same order as in source
1967  */
1968 static void linklist_copy(LinkNode **target, LinkNode *source)
1969 {
1970         LinkNode *node = NULL;
1971         *target = NULL;
1972
1973         for(; source; source = source->next) {
1974                 if(node) {
1975                         node->next = MEM_mallocN(sizeof(*node->next), "nlink_copy");
1976                                                                                 node = node->next;
1977 } else {
1978                                                                                 node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
1979 }
1980                                                                                 node->link = source->link;
1981                                                                                 node->next = NULL;
1982 }
1983 }
1984 #endif
1985
1986                                                                                 /* appends source to target if it's not already in target */
1987                                                                                 static void linklist_append_unique(LinkNode **target, void *source) 
1988 {
1989         LinkNode *node;
1990         LinkNode *prev = NULL;
1991
1992         /* check if source value is already in the list */
1993         for(node = *target; node; prev = node, node = node->next)
1994                 if(node->link == source) return;
1995
1996         node = MEM_mallocN(sizeof(*node), "nlink");
1997         node->next = NULL;
1998         node->link = source;
1999
2000         if(prev) prev->next = node;
2001         else *target = node;
2002 }
2003
2004 /* appends elements of source which aren't already in target to target */
2005 static void linklist_append_list_unique(LinkNode **target, LinkNode *source)
2006 {
2007         for(; source; source = source->next)
2008                 linklist_append_unique(target, source->link);
2009 }
2010
2011 #if 0 /* this is no longer used, it should possibly be removed */
2012 /* prepends prepend to list - doesn't copy nodes, just joins the lists */
2013 static void linklist_prepend_linklist(LinkNode **list, LinkNode *prepend)
2014 {
2015         if(prepend) {
2016                 LinkNode *node = prepend;
2017                 while(node->next) node = node->next;
2018
2019                 node->next = *list;
2020                 *list = prepend;
2021 }
2022 }
2023 #endif
2024
2025 /* returns 1 if the linked list contains the given pointer, 0 otherwise
2026  */
2027 static int linklist_contains(LinkNode *list, void *ptr)
2028 {
2029         LinkNode *node;
2030
2031         for(node = list; node; node = node->next)
2032                 if(node->link == ptr) return 1;
2033
2034         return 0;
2035 }
2036
2037 /* returns 1 if the first linked list is a subset of the second (comparing
2038  * pointer values), 0 if not
2039  */
2040 static int linklist_subset(LinkNode *list1, LinkNode *list2)
2041 {
2042         for(; list1; list1 = list1->next)
2043                 if(!linklist_contains(list2, list1->link))
2044                         return 0;
2045
2046         return 1;
2047 }
2048
2049 #if 0
2050 /* empties the linked list
2051  * frees pointers with freefunc if freefunc is not NULL
2052  */
2053 static void linklist_empty(LinkNode **list, LinkNodeFreeFP freefunc)
2054 {
2055         BLI_linklist_free(*list, freefunc);
2056         *list = NULL;
2057 }
2058 #endif
2059
2060 /* removes the first instance of value from the linked list
2061  * frees the pointer with freefunc if freefunc is not NULL
2062  */
2063 static void linklist_remove_first(LinkNode **list, void *value,
2064                                   LinkNodeFreeFP freefunc)
2065 {
2066         LinkNode *node = *list;
2067         LinkNode *prev = NULL;
2068
2069         while(node && node->link != value) {
2070                 prev = node;
2071                 node = node->next;
2072         }
2073
2074         if(node) {
2075                 if(prev)
2076                         prev->next = node->next;
2077                 else
2078                         *list = node->next;
2079
2080                 if(freefunc)
2081                         freefunc(node->link);
2082
2083                 MEM_freeN(node);
2084         }
2085 }
2086
2087 /* removes all elements in source from target */
2088 static void linklist_remove_list(LinkNode **target, LinkNode *source,
2089                                  LinkNodeFreeFP freefunc)
2090 {
2091         for(; source; source = source->next)
2092                 linklist_remove_first(target, source->link, freefunc);
2093 }
2094
2095 #ifdef EDGESPLIT_DEBUG_0
2096 static void print_ptr(void *ptr)
2097 {
2098         printf("%p\n", ptr);
2099 }
2100
2101 static void print_edge(void *ptr)
2102 {
2103         SmoothEdge *edge = ptr;
2104         printf(" %4d", edge->newIndex);
2105 }
2106
2107 static void print_face(void *ptr)
2108 {
2109         SmoothFace *face = ptr;
2110         printf(" %4d", face->newIndex);
2111 }
2112 #endif
2113
2114 typedef struct ReplaceData {
2115         void *find;
2116         void *replace;
2117 } ReplaceData;
2118
2119 static void edge_replace_vert(void *ptr, void *userdata)
2120 {
2121         SmoothEdge *edge = ptr;
2122         SmoothVert *find = ((ReplaceData *)userdata)->find;
2123         SmoothVert *replace = ((ReplaceData *)userdata)->replace;
2124         int i;
2125
2126 #ifdef EDGESPLIT_DEBUG_3
2127         printf("replacing vert %4d with %4d in edge %4d",
2128                find->newIndex, replace->newIndex, edge->newIndex);
2129         printf(": {%4d, %4d}", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2130 #endif
2131
2132         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++) {
2133                 if(edge->verts[i] == find) {
2134                         linklist_append_list_unique(&replace->faces, edge->faces);
2135                         linklist_remove_list(&find->faces, edge->faces, NULL);
2136
2137                         edge->verts[i] = replace;
2138                 }
2139         }
2140
2141 #ifdef EDGESPLIT_DEBUG_3
2142         printf(" -> {%4d, %4d}\n", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2143 #endif
2144 }
2145
2146 static void face_replace_vert(void *ptr, void *userdata)
2147 {
2148         SmoothFace *face = ptr;
2149         int i;
2150
2151         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++)
2152                 edge_replace_vert(face->edges[i], userdata);
2153 }
2154
2155 static void face_replace_edge(void *ptr, void *userdata)
2156 {
2157         SmoothFace *face = ptr;
2158         SmoothEdge *find = ((ReplaceData *)userdata)->find;
2159         SmoothEdge *replace = ((ReplaceData *)userdata)->replace;
2160         int i;
2161
2162 #ifdef EDGESPLIT_DEBUG_3
2163         printf("replacing edge %4d with %4d in face %4d",
2164                find->newIndex, replace->newIndex, face->newIndex);
2165         if(face->edges[3])
2166                 printf(": {%2d %2d %2d %2d}",
2167                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2168          face->edges[2]->newIndex, face->edges[3]->newIndex);
2169         else
2170                 printf(": {%2d %2d %2d}",
2171                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2172          face->edges[2]->newIndex);
2173 #endif
2174
2175         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
2176                 if(face->edges[i] == find) {
2177                         linklist_remove_first(&face->edges[i]->faces, face, NULL);
2178                         BLI_linklist_prepend(&replace->faces, face);
2179                         face->edges[i] = replace;
2180                 }
2181         }
2182
2183 #ifdef EDGESPLIT_DEBUG_3
2184         if(face->edges[3])
2185                 printf(" -> {%2d %2d %2d %2d}\n",
2186                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2187          face->edges[2]->newIndex, face->edges[3]->newIndex);
2188         else
2189                 printf(" -> {%2d %2d %2d}\n",
2190                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2191          face->edges[2]->newIndex);
2192 #endif
2193 }
2194
2195 static int edge_is_loose(SmoothEdge *edge)
2196 {
2197         return !(edge->faces && edge->faces->next);
2198 }
2199
2200 static int edge_is_sharp(SmoothEdge *edge, int flags,
2201                          float threshold)
2202 {
2203 #ifdef EDGESPLIT_DEBUG_1
2204         printf("edge %d: ", edge->newIndex);
2205 #endif
2206         if(edge->flag & ME_SHARP) {
2207                 /* edge can only be sharp if it has at least 2 faces */
2208                 if(!edge_is_loose(edge)) {
2209 #ifdef EDGESPLIT_DEBUG_1
2210                         printf("sharp\n");
2211 #endif
2212                         return 1;
2213                 } else {
2214                         /* edge is loose, so it can't be sharp */
2215                         edge->flag &= ~ME_SHARP;
2216                 }
2217         }
2218
2219 #ifdef EDGESPLIT_DEBUG_1
2220         printf("not sharp\n");
2221 #endif
2222         return 0;
2223 }
2224
2225 /* finds another sharp edge which uses vert, by traversing faces around the
2226  * vert until it does one of the following:
2227  * - hits a loose edge (the edge is returned)
2228  * - hits a sharp edge (the edge is returned)
2229  * - returns to the start edge (NULL is returned)
2230  */
2231 static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
2232                                          LinkNode **visited_faces, float threshold, int flags)
2233 {
2234         SmoothFace *face = NULL;
2235         SmoothEdge *edge2 = NULL;
2236         /* holds the edges we've seen so we can avoid looping indefinitely */
2237         LinkNode *visited_edges = NULL;
2238 #ifdef EDGESPLIT_DEBUG_1
2239         printf("=== START === find_other_sharp_edge(edge = %4d, vert = %4d)\n",
2240                edge->newIndex, vert->newIndex);
2241 #endif
2242
2243         /* get a face on which to start */
2244         if(edge->faces) face = edge->faces->link;
2245         else return NULL;
2246
2247         /* record this edge as visited */
2248         BLI_linklist_prepend(&visited_edges, edge);
2249
2250         /* get the next edge */
2251         edge2 = other_edge(face, vert, edge);
2252
2253         /* record this face as visited */
2254         if(visited_faces)
2255                 BLI_linklist_prepend(visited_faces, face);
2256
2257         /* search until we hit a loose edge or a sharp edge or an edge we've
2258         * seen before
2259         */
2260         while(face && !edge_is_sharp(edge2, flags, threshold)
2261                      && !linklist_contains(visited_edges, edge2)) {
2262 #ifdef EDGESPLIT_DEBUG_3
2263                 printf("current face %4d; current edge %4d\n", face->newIndex,
2264                        edge2->newIndex);
2265 #endif
2266                 /* get the next face */
2267                 face = other_face(edge2, face);
2268
2269                 /* if face == NULL, edge2 is a loose edge */
2270                 if(face) {
2271                         /* record this face as visited */
2272                         if(visited_faces)
2273                                 BLI_linklist_prepend(visited_faces, face);
2274
2275                         /* record this edge as visited */
2276                         BLI_linklist_prepend(&visited_edges, edge2);
2277
2278                         /* get the next edge */
2279                         edge2 = other_edge(face, vert, edge2);
2280 #ifdef EDGESPLIT_DEBUG_3
2281                         printf("next face %4d; next edge %4d\n",
2282                                face->newIndex, edge2->newIndex);
2283                 } else {
2284                         printf("loose edge: %4d\n", edge2->newIndex);
2285 #endif
2286                 }
2287                      }
2288
2289                      /* either we came back to the start edge or we found a sharp/loose edge */
2290                      if(linklist_contains(visited_edges, edge2))
2291                              /* we came back to the start edge */
2292                              edge2 = NULL;
2293
2294                      BLI_linklist_free(visited_edges, NULL);
2295
2296 #ifdef EDGESPLIT_DEBUG_1
2297                      printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
2298                                      "returning edge %d\n",
2299          edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
2300 #endif
2301                      return edge2;
2302 }
2303
2304 static void split_single_vert(SmoothVert *vert, SmoothFace *face,
2305                               SmoothMesh *mesh)
2306 {
2307         SmoothVert *copy_vert;
2308         ReplaceData repdata;
2309
2310         copy_vert = smoothvert_copy(vert, mesh);
2311
2312         repdata.find = vert;
2313         repdata.replace = copy_vert;
2314         face_replace_vert(face, &repdata);
2315 }
2316
2317 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh);
2318
2319 static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
2320                             SmoothMesh *mesh)
2321 {
2322         SmoothEdge *edge2;
2323         LinkNode *visited_faces = NULL;
2324 #ifdef EDGESPLIT_DEBUG_1
2325         printf("=== START === propagate_split(edge = %4d, vert = %4d)\n",
2326                edge->newIndex, vert->newIndex);
2327 #endif
2328
2329         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2330                                       mesh->threshold, mesh->flags);
2331
2332         if(!edge2) {
2333                 /* didn't find a sharp or loose edge, so we've hit a dead end */
2334         } else if(!edge_is_loose(edge2)) {
2335                 /* edge2 is not loose, so it must be sharp */
2336                 if(edge_is_loose(edge)) {
2337                         /* edge is loose, so we can split edge2 at this vert */
2338                         split_edge(edge2, vert, mesh);
2339                 } else if(edge_is_sharp(edge, mesh->flags, mesh->threshold)) {
2340                         /* both edges are sharp, so we can split the pair at vert */
2341                         split_edge(edge, vert, mesh);
2342                 } else {
2343                         /* edge is not sharp, so try to split edge2 at its other vert */
2344                         split_edge(edge2, other_vert(edge2, vert), mesh);
2345                 }
2346         } else { /* edge2 is loose */
2347                 if(edge_is_loose(edge)) {
2348                         SmoothVert *vert2;
2349                         ReplaceData repdata;
2350
2351                         /* can't split edge, what should we do with vert? */
2352                         if(linklist_subset(vert->faces, visited_faces)) {
2353                                 /* vert has only one fan of faces attached; don't split it */
2354                         } else {
2355                                 /* vert has more than one fan of faces attached; split it */
2356                                 vert2 = smoothvert_copy(vert, mesh);
2357
2358                                 /* replace vert with its copy in visited_faces */
2359                                 repdata.find = vert;
2360                                 repdata.replace = vert2;
2361                                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2362                         }
2363                 } else {
2364                         /* edge is not loose, so it must be sharp; split it */
2365                         split_edge(edge, vert, mesh);
2366                 }
2367         }
2368
2369         BLI_linklist_free(visited_faces, NULL);
2370 #ifdef EDGESPLIT_DEBUG_1
2371         printf("=== END === propagate_split(edge = %4d, vert = %4d)\n",
2372                edge->newIndex, vert->newIndex);
2373 #endif
2374 }
2375
2376 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
2377 {
2378         SmoothEdge *edge2;
2379         SmoothVert *vert2;
2380         ReplaceData repdata;
2381         /* the list of faces traversed while looking for a sharp edge */
2382         LinkNode *visited_faces = NULL;
2383 #ifdef EDGESPLIT_DEBUG_1
2384         printf("=== START === split_edge(edge = %4d, vert = %4d)\n",
2385                edge->newIndex, vert->newIndex);
2386 #endif
2387
2388         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2389                                       mesh->threshold, mesh->flags);
2390
2391         if(!edge2) {
2392                 /* didn't find a sharp or loose edge, so try the other vert */
2393                 vert2 = other_vert(edge, vert);
2394                 propagate_split(edge, vert2, mesh);
2395         } else if(!edge_is_loose(edge2)) {
2396                 /* edge2 is not loose, so it must be sharp */
2397                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2398                 SmoothEdge *copy_edge2 = smoothedge_copy(edge2, mesh);
2399                 SmoothVert *vert2;
2400
2401                 /* replace edge with its copy in visited_faces */
2402                 repdata.find = edge;
2403                 repdata.replace = copy_edge;
2404                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2405
2406                 /* replace edge2 with its copy in visited_faces */
2407                 repdata.find = edge2;
2408                 repdata.replace = copy_edge2;
2409                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2410
2411                 vert2 = smoothvert_copy(vert, mesh);
2412
2413                 /* replace vert with its copy in visited_faces (must be done after
2414                 * edge replacement so edges have correct vertices)
2415                 */
2416                 repdata.find = vert;
2417                 repdata.replace = vert2;
2418                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2419
2420                 /* all copying and replacing is done; the mesh should be consistent.
2421                 * now propagate the split to the vertices at either end
2422                 */
2423                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2424                 propagate_split(copy_edge2, other_vert(copy_edge2, vert2), mesh);
2425
2426                 if(smoothedge_has_vert(edge, vert))
2427                         propagate_split(edge, vert, mesh);
2428         } else {
2429                 /* edge2 is loose */
2430                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2431                 SmoothVert *vert2;
2432
2433                 /* replace edge with its copy in visited_faces */
2434                 repdata.find = edge;
2435                 repdata.replace = copy_edge;
2436                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2437
2438                 vert2 = smoothvert_copy(vert, mesh);
2439
2440                 /* replace vert with its copy in visited_faces (must be done after
2441                 * edge replacement so edges have correct vertices)
2442                 */
2443                 repdata.find = vert;
2444                 repdata.replace = vert2;
2445                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2446
2447                 /* copying and replacing is done; the mesh should be consistent.
2448                 * now propagate the split to the vertex at the other end
2449                 */
2450                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2451
2452                 if(smoothedge_has_vert(edge, vert))
2453                         propagate_split(edge, vert, mesh);
2454         }
2455
2456         BLI_linklist_free(visited_faces, NULL);
2457 #ifdef EDGESPLIT_DEBUG_1
2458         printf("=== END === split_edge(edge = %4d, vert = %4d)\n",
2459                edge->newIndex, vert->newIndex);
2460 #endif
2461 }
2462
2463 static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
2464                                       int flags, int *extra_edges)
2465 {
2466         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2467         /* FIXME not sure if this always works */
2468         /* 0.00001 added for floating-point rounding */
2469         float threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2470         int i;
2471
2472         *extra_edges = 0;
2473
2474         /* loop through edges, counting potential new ones */
2475         for(i = 0; i < mesh->num_edges; i++) {
2476                 SmoothEdge *edge = &mesh->edges[i];
2477                 int sharp = 0;
2478
2479                 /* treat all non-manifold edges (3 or more faces) as sharp */
2480                 if(edge->faces && edge->faces->next && edge->faces->next->next) {
2481                         LinkNode *node;
2482
2483                         /* this edge is sharp */
2484                         sharp = 1;
2485
2486                         /* add an extra edge for every face beyond the first */
2487                         *extra_edges += 2;
2488                         for(node = edge->faces->next->next->next; node; node = node->next)
2489                                 (*extra_edges)++;
2490                 } else if((flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG))
2491                                          && !edge_is_loose(edge)) {
2492                         /* (the edge can only be sharp if we're checking angle or flag,
2493                         * and it has at least 2 faces) */
2494
2495                                                  /* if we're checking the sharp flag and it's set, good */
2496                                                  if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
2497                                                          /* this edge is sharp */
2498                                                          sharp = 1;
2499
2500                                                          (*extra_edges)++;
2501                                                  } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
2502                                                          /* we know the edge has 2 faces, so check the angle */
2503                                                          SmoothFace *face1 = edge->faces->link;
2504                                                          SmoothFace *face2 = edge->faces->next->link;
2505                                                          float edge_angle_cos = MTC_dot3Float(face1->normal,
2506                                                                          face2->normal);
2507
2508                                                          if(edge_angle_cos < threshold) {
2509                                                                  /* this edge is sharp */
2510                                                                  sharp = 1;
2511
2512                                                                  (*extra_edges)++;
2513                                                          }
2514                                                  }
2515                                          }
2516
2517                                          /* set/clear sharp flag appropriately */
2518                                          if(sharp) edge->flag |= ME_SHARP;
2519                                          else edge->flag &= ~ME_SHARP;
2520         }
2521 }
2522
2523 static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
2524 {
2525         int i;
2526         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2527         /* FIXME not sure if this always works */
2528         /* 0.00001 added for floating-point rounding */
2529         mesh->threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2530         mesh->flags = flags;
2531
2532         /* loop through edges, splitting sharp ones */
2533         /* can't use an iterator here, because we'll be adding edges */
2534         for(i = 0; i < mesh->num_edges; i++) {
2535                 SmoothEdge *edge = &mesh->edges[i];
2536
2537                 if(edge_is_sharp(edge, flags, mesh->threshold))
2538                         split_edge(edge, edge->verts[0], mesh);
2539         }
2540
2541 }
2542
2543 static int count_bridge_verts(SmoothMesh *mesh)
2544 {
2545         int i, j, count = 0;
2546
2547         for(i = 0; i < mesh->num_faces; i++) {
2548                 SmoothFace *face = &mesh->faces[i];
2549
2550                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2551                         SmoothEdge *edge = face->edges[j];
2552                         SmoothEdge *next_edge;
2553                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2554                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2555
2556                         /* wrap next around if at last edge */
2557                         if(!face->edges[next]) next = 0;
2558
2559                         next_edge = face->edges[next];
2560
2561                         /* if there are other faces sharing this vertex but not
2562                         * these edges, the vertex will be split, so count it
2563                         */
2564                         /* vert has to have at least one face (this one), so faces != 0 */
2565                         if(!edge->faces->next && !next_edge->faces->next
2566                                                  && vert->faces->next) {
2567                                 count++;
2568                                                  }
2569                 }
2570         }
2571
2572         /* each bridge vert will be counted once per face that uses it,
2573         * so count is too high, but it's ok for now
2574         */
2575         return count;
2576 }
2577
2578 static void split_bridge_verts(SmoothMesh *mesh)
2579 {
2580         int i,j;
2581
2582         for(i = 0; i < mesh->num_faces; i++) {
2583                 SmoothFace *face = &mesh->faces[i];
2584
2585                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2586                         SmoothEdge *edge = face->edges[j];
2587                         SmoothEdge *next_edge;
2588                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2589                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2590
2591                         /* wrap next around if at last edge */
2592                         if(!face->edges[next]) next = 0;
2593
2594                         next_edge = face->edges[next];
2595
2596                         /* if there are other faces sharing this vertex but not
2597                         * these edges, split the vertex
2598                         */
2599                         /* vert has to have at least one face (this one), so faces != 0 */
2600                         if(!edge->faces->next && !next_edge->faces->next
2601                                                  && vert->faces->next)
2602                                 /* FIXME this needs to find all faces that share edges with
2603                                 * this one and split off together
2604                                 */
2605                                 split_single_vert(vert, face, mesh);
2606                 }
2607         }
2608 }
2609
2610 static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
2611                                          Object *ob, DerivedMesh *dm)
2612 {
2613         SmoothMesh *mesh;
2614         DerivedMesh *result;
2615         int max_verts, max_edges;
2616
2617         if(!(emd->flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG)))
2618                 return dm;
2619
2620         /* 1. make smoothmesh with initial number of elements */
2621         mesh = smoothmesh_from_derivedmesh(dm);
2622
2623         /* 2. count max number of elements to add */
2624         tag_and_count_extra_edges(mesh, emd->split_angle, emd->flags, &max_edges);
2625         max_verts = max_edges * 2 + mesh->max_verts;
2626         max_verts += count_bridge_verts(mesh);
2627         max_edges += mesh->max_edges;
2628
2629         /* 3. reallocate smoothmesh arrays & copy elements across */
2630         /* 4. remap copied elements' pointers to point into the new arrays */
2631         smoothmesh_resize_verts(mesh, max_verts);
2632         smoothmesh_resize_edges(mesh, max_edges);
2633
2634 #ifdef EDGESPLIT_DEBUG_1
2635         printf("********** Pre-split **********\n");
2636         smoothmesh_print(mesh);
2637 #endif
2638
2639         split_sharp_edges(mesh, emd->split_angle, emd->flags);
2640 #ifdef EDGESPLIT_DEBUG_1
2641         printf("********** Post-edge-split **********\n");
2642         smoothmesh_print(mesh);
2643 #endif
2644
2645         split_bridge_verts(mesh);
2646
2647 #ifdef EDGESPLIT_DEBUG_1
2648         printf("********** Post-vert-split **********\n");
2649         smoothmesh_print(mesh);
2650 #endif
2651
2652 #ifdef EDGESPLIT_DEBUG_0
2653         printf("Edgesplit: Estimated %d verts & %d edges, "
2654                         "found %d verts & %d edges\n", max_verts, max_edges,
2655    mesh->num_verts, mesh->num_edges);
2656 #endif
2657
2658         result = CDDM_from_smoothmesh(mesh);
2659         smoothmesh_free(mesh);
2660
2661         return result;
2662 }
2663
2664 static DerivedMesh *edgesplitModifier_applyModifier(
2665                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2666   int useRenderParams, int isFinalCalc)
2667 {
2668         DerivedMesh *result;
2669         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
2670
2671         result = edgesplitModifier_do(emd, ob, derivedData);
2672
2673         CDDM_calc_normals(result);
2674
2675         return result;
2676 }
2677
2678 static DerivedMesh *edgesplitModifier_applyModifierEM(
2679                 ModifierData *md, Object *ob, EditMesh *editData,
2680   DerivedMesh *derivedData)
2681 {
2682         return edgesplitModifier_applyModifier(md, ob, derivedData, 0, 1);
2683 }
2684
2685 /* Bevel */
2686
2687 static void bevelModifier_initData(ModifierData *md)
2688 {
2689         BevelModifierData *bmd = (BevelModifierData*) md;
2690
2691         bmd->value = 0.1f;
2692         bmd->res = 1;
2693         bmd->flags = 0;
2694         bmd->val_flags = 0;
2695         bmd->lim_flags = 0;
2696         bmd->e_flags = 0;
2697         bmd->bevel_angle = 30;
2698         bmd->defgrp_name[0] = '\0';
2699 }
2700
2701 static void bevelModifier_copyData(ModifierData *md, ModifierData *target)
2702 {
2703         BevelModifierData *bmd = (BevelModifierData*) md;
2704         BevelModifierData *tbmd = (BevelModifierData*) target;
2705
2706         tbmd->value = bmd->value;
2707         tbmd->res = bmd->res;
2708         tbmd->flags = bmd->flags;
2709         tbmd->val_flags = bmd->val_flags;
2710         tbmd->lim_flags = bmd->lim_flags;
2711         tbmd->e_flags = bmd->e_flags;
2712         tbmd->bevel_angle = bmd->bevel_angle;
2713         strncpy(tbmd->defgrp_name, bmd->defgrp_name, 32);
2714 }
2715
2716 CustomDataMask bevelModifier_requiredDataMask(ModifierData *md)
2717 {
2718         BevelModifierData *bmd = (BevelModifierData *)md;
2719         CustomDataMask dataMask = 0;
2720
2721         /* ask for vertexgroups if we need them */
2722         if(bmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2723
2724         return dataMask;
2725 }
2726
2727 static DerivedMesh *bevelModifier_applyModifier(
2728                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2729   int useRenderParams, int isFinalCalc)
2730 {
2731         DerivedMesh *result;
2732         BME_Mesh *bm;
2733         /*bDeformGroup *def;*/
2734         int /*i,*/ options, defgrp_index = -1;
2735         BevelModifierData *bmd = (BevelModifierData*) md;
2736
2737         options = bmd->flags|bmd->val_flags|bmd->lim_flags|bmd->e_flags;
2738
2739         //~ if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
2740                 //~ for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
2741                         //~ if (!strcmp(def->name, bmd->defgrp_name)) {
2742                                 //~ defgrp_index = i;
2743                                 //~ break;
2744                         //~ }
2745                 //~ }
2746                 //~ if (defgrp_index < 0) {
2747                         //~ options &= ~BME_BEVEL_VWEIGHT;
2748                 //~ }
2749         //~ }
2750
2751         bm = BME_make_mesh();
2752         bm = BME_derivedmesh_to_bmesh(derivedData, bm);
2753         BME_bevel(bm,bmd->value,bmd->res,options,defgrp_index,bmd->bevel_angle,NULL);
2754         result = BME_bmesh_to_derivedmesh(bm,derivedData);
2755         BME_free_mesh(bm);
2756
2757         CDDM_calc_normals(result);
2758
2759         return result;
2760 }
2761
2762 static DerivedMesh *bevelModifier_applyModifierEM(
2763                 ModifierData *md, Object *ob, EditMesh *editData,
2764   DerivedMesh *derivedData)
2765 {
2766         return bevelModifier_applyModifier(md, ob, derivedData, 0, 1);
2767 }
2768
2769 /* Displace */
2770
2771 static void displaceModifier_initData(ModifierData *md)
2772 {
2773         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2774
2775         dmd->texture = NULL;
2776         dmd->strength = 1;
2777         dmd->direction = MOD_DISP_DIR_NOR;
2778         dmd->midlevel = 0.5;
2779 }
2780
2781 static void displaceModifier_copyData(ModifierData *md, ModifierData *target)
2782 {
2783         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2784         DisplaceModifierData *tdmd = (DisplaceModifierData*) target;
2785
2786         tdmd->texture = dmd->texture;
2787         tdmd->strength = dmd->strength;
2788         tdmd->direction = dmd->direction;
2789         strncpy(tdmd->defgrp_name, dmd->defgrp_name, 32);
2790         tdmd->midlevel = dmd->midlevel;
2791         tdmd->texmapping = dmd->texmapping;
2792         tdmd->map_object = dmd->map_object;
2793         strncpy(tdmd->uvlayer_name, dmd->uvlayer_name, 32);
2794 }
2795
2796 CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
2797 {
2798         DisplaceModifierData *dmd = (DisplaceModifierData *)md;
2799         CustomDataMask dataMask = 0;
2800
2801         /* ask for vertexgroups if we need them */
2802         if(dmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2803
2804         /* ask for UV coordinates if we need them */
2805         if(dmd->texmapping == MOD_DISP_MAP_UV) dataMask |= (1 << CD_MTFACE);
2806
2807         return dataMask;
2808 }
2809
2810 static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
2811                                                ObjectWalkFunc walk, void *userData)
2812 {
2813         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2814
2815         walk(userData, ob, &dmd->map_object);
2816 }
2817
2818 static void displaceModifier_foreachIDLink(ModifierData *md, Object *ob,
2819                                            IDWalkFunc walk, void *userData)
2820 {
2821         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2822
2823         walk(userData, ob, (ID **)&dmd->texture);
2824
2825         displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
2826 }
2827
2828 static int displaceModifier_isDisabled(ModifierData *md)
2829 {
2830         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2831
2832         return !dmd->texture;
2833 }
2834
2835 static void displaceModifier_updateDepgraph(
2836                                             ModifierData *md, DagForest *forest,
2837          Object *ob, DagNode *obNode)
2838 {
2839         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2840
2841         if(dmd->map_object) {
2842                 DagNode *curNode = dag_get_node(forest, dmd->map_object);
2843
2844                 dag_add_relation(forest, curNode, obNode,
2845                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA);
2846         }
2847 }
2848
2849 static void validate_layer_name(const CustomData *data, int type, char *name)
2850 {
2851         int index = -1;
2852
2853         /* if a layer name was given, try to find that layer */
2854         if(name[0])
2855                 index = CustomData_get_named_layer_index(data, CD_MTFACE, name);
2856
2857         if(index < 0) {
2858                 /* either no layer was specified, or the layer we want has been
2859                 * deleted, so assign the active layer to name
2860                 */
2861                 index = CustomData_get_active_layer_index(data, CD_MTFACE);
2862                 strcpy(name, data->layers[index].name);
2863         }
2864 }
2865
2866 static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
2867                                DerivedMesh *dm,
2868           float (*co)[3], float (*texco)[3],
2869                   int numVerts)
2870 {
2871         int i;
2872         int texmapping = dmd->texmapping;
2873
2874         if(texmapping == MOD_DISP_MAP_OBJECT) {
2875                 if(dmd->map_object)
2876                         Mat4Invert(dmd->map_object->imat, dmd->map_object->obmat);
2877                 else /* if there is no map object, default to local */
2878                         texmapping = MOD_DISP_MAP_LOCAL;
2879         }
2880
2881         /* UVs need special handling, since they come from faces */
2882         if(texmapping == MOD_DISP_MAP_UV) {
2883                 if(dm->getFaceDataArray(dm, CD_MTFACE)) {
2884                         MFace *mface = dm->getFaceArray(dm);
2885                         MFace *mf;
2886                         char *done = MEM_callocN(sizeof(*done) * numVerts,
2887                                         "get_texture_coords done");
2888                         int numFaces = dm->getNumFaces(dm);
2889                         MTFace *tf;
2890
2891                         validate_layer_name(&dm->faceData, CD_MTFACE, dmd->uvlayer_name);
2892
2893                         tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
2894                                         dmd->uvlayer_name);
2895
2896                         /* verts are given the UV from the first face that uses them */
2897                         for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
2898                                 if(!done[mf->v1]) {
2899                                         texco[mf->v1][0] = tf->uv[0][0];
2900                                         texco[mf->v1][1] = tf->uv[0][1];
2901                                         texco[mf->v1][2] = 0;
2902                                         done[mf->v1] = 1;
2903                                 }
2904                                 if(!done[mf->v2]) {
2905                                         texco[mf->v2][0] = tf->uv[1][0];
2906                                         texco[mf->v2][1] = tf->uv[1][1];
2907                                         texco[mf->v2][2] = 0;
2908                                         done[mf->v2] = 1;
2909                                 }
2910                                 if(!done[mf->v3]) {
2911                                         texco[mf->v3][0] = tf->uv[2][0];
2912                                         texco[mf->v3][1] = tf->uv[2][1];
2913                                         texco[mf->v3][2] = 0;
2914                                         done[mf->v3] = 1;
2915                                 }
2916                                 if(!done[mf->v4]) {
2917                                         texco[mf->v4][0] = tf->uv[3][0];
2918                                         texco[mf->v4][1] = tf->uv[3][1];
2919                                         texco[mf->v4][2] = 0;
2920                                         done[mf->v4] = 1;
2921                                 }
2922                         }
2923
2924                         /* remap UVs from [0, 1] to [-1, 1] */
2925                         for(i = 0; i < numVerts; ++i) {
2926                                 texco[i][0] = texco[i][0] * 2 - 1;
2927                                 texco[i][1] = texco[i][1] * 2 - 1;
2928                         }
2929
2930                         MEM_freeN(done);
2931                         return;
2932                 } else /* if there are no UVs, default to local */
2933                         texmapping = MOD_DISP_MAP_LOCAL;
2934         }
2935
2936         for(i = 0; i < numVerts; ++i, ++co, ++texco) {
2937                 switch(texmapping) {
2938                         case MOD_DISP_MAP_LOCAL:
2939                                 VECCOPY(*texco, *co);
2940                                 break;
2941                         case MOD_DISP_MAP_GLOBAL:
2942                                 VECCOPY(*texco, *co);
2943                                 Mat4MulVecfl(ob->obmat, *texco);
2944                                 break;
2945                         case MOD_DISP_MAP_OBJECT:
2946                                 VECCOPY(*texco, *co);
2947                                 Mat4MulVecfl(ob->obmat, *texco);
2948                                 Mat4MulVecfl(dmd->map_object->imat, *texco);
2949                                 break;
2950                 }
2951         }
2952 }
2953
2954 static void get_texture_value(Tex *texture, float *tex_co, TexResult *texres)
2955 {
2956         int result_type;
2957
2958         result_type = multitex_ext(texture, tex_co, NULL,
2959                                    NULL, 1, texres);
2960
2961         /* if the texture gave an RGB value, we assume it didn't give a valid
2962         * intensity, so calculate one (formula from do_material_tex).
2963         * if the texture didn't give an RGB value, copy the intensity across
2964         */
2965         if(result_type & TEX_RGB)
2966                 texres->tin = (0.35 * texres->tr + 0.45 * texres->tg
2967                                 + 0.2 * texres->tb);
2968         else
2969                 texres->tr = texres->tg = texres->tb = texres->tin;
2970 }
2971
2972 /* dm must be a CDDerivedMesh */
2973 static void displaceModifier_do(
2974                                 DisplaceModifierData *dmd, Object *ob,
2975     DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
2976 {
2977         int i;
2978         MVert *mvert;
2979         MDeformVert *dvert = NULL;
2980         int defgrp_index;
2981         float (*tex_co)[3];
2982
2983         if(!dmd->texture) return;
2984
2985         defgrp_index = -1;
2986
2987         if(dmd->defgrp_name[0]) {
2988                 bDeformGroup *def;
2989                 for(i = 0, def = ob->defbase.first; def; def = def->next, i++) {
2990                         if(!strcmp(def->name, dmd->defgrp_name)) {
2991                                 defgrp_index = i;
2992                                 break;
2993                         }
2994                 }
2995         }
2996
2997         mvert = CDDM_get_verts(dm);
2998         if(defgrp_index >= 0)
2999                 dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
3000
3001         tex_co = MEM_callocN(sizeof(*tex_co) * numVerts,
3002                              "displaceModifier_do tex_co");
3003         get_texture_coords(dmd, ob, dm, vertexCos, tex_co, numVerts);
3004
3005         for(i = 0; i < numVerts; ++i) {
3006                 TexResult texres;
3007                 float delta = 0, strength = dmd->strength;
3008                 MDeformWeight *def_weight = NULL;
3009
3010                 if(dvert) {
3011                         int j;
3012                         for(j = 0; j < dvert[i].totweight; ++j) {
3013                                 if(dvert[i].dw[j].def_nr == defgrp_index) {
3014                                         def_weight = &dvert[i].dw[j];
3015                                         break;
3016                                 }
3017                         }
3018                         if(!def_weight) continue;
3019                 }
3020
3021                 texres.nor = NULL;
3022                 get_texture_value(dmd->texture, tex_co[i], &texres);
3023
3024                 delta = texres.tin - dmd->midlevel;
3025
3026                 if(def_weight) strength *= def_weight->weight;
3027
3028                 delta *= strength;
3029
3030                 switch(dmd->direction) {
3031                         case MOD_DISP_DIR_X:
3032                                 vertexCos[i][0] += delta;
3033                                 break;
3034                         case MOD_DISP_DIR_Y:
3035                                 vertexCos[i][1] += delta;
3036                                 break;
3037                         case MOD_DISP_DIR_Z:
3038                                 vertexCos[i][2] += delta;
3039                                 break;
3040                         case MOD_DISP_DIR_RGB_XYZ:
3041                                 vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
3042                                 vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
3043                                 vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
3044                                 break;
3045                         case MOD_DISP_DIR_NOR:
3046                                 vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
3047                                 vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
3048                                 vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
3049                                 break;
3050                 }
3051         }
3052
3053         MEM_freeN(tex_co);
3054 }
3055
3056 static void displaceModifier_deformVerts(
3057                                          ModifierData *md, Object *ob, DerivedMesh *derivedData,
3058       float (*vertexCos)[3], int numVerts)
3059 {
3060         DerivedMesh *dm;
3061
3062         if(derivedData) dm = CDDM_copy(derivedData);
3063         else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
3064         else return;
3065
3066         CDDM_apply_vert_coords(dm, vertexCos);
3067         CDDM_calc_normals(dm);
3068
3069         displaceModifier_do((DisplaceModifierData *)md, ob, dm,
3070                              vertexCos, numVerts);
3071
3072         dm->release(dm);
3073 }
3074
3075 static void displaceModifier_deformVertsEM(
3076  &