-> More Bmesh Custom Data stuff
[blender.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, "Curve Modifier");
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, "Lattice Modifier");
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, "Array Modifier");
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, "Array Modifier");
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, "Array Modifier");
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, "Array Modifier");
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                           indexMap[i].merge = -1; /* default to no merge */
848                           indexMap[i].merge_final = 0; /* default to no merge */
849                   }
850
851                   for (i = 0; i < maxVerts; i++) {
852                           MVert *inMV;
853                           MVert *mv = &mvert[numVerts];
854                           MVert *mv2;
855                           float co[3];
856
857                           inMV = &src_mvert[i];
858
859                           DM_copy_vert_data(dm, result, i, numVerts, 1);
860                           *mv = *inMV;
861                           numVerts++;
862
863                           indexMap[i].new = numVerts - 1;
864
865                           VECCOPY(co, mv->co);
866                 
867                 /* Attempts to merge verts from one duplicate with verts from the
868                           * next duplicate which are closer than amd->merge_dist.
869                           * Only the first such vert pair is merged.
870                           * If verts are merged in the first duplicate pair, they are merged
871                           * in all pairs.
872                 */
873                           if((count > 1) && (amd->flags & MOD_ARR_MERGE)) {
874                                   float tmp_co[3];
875                                   VECCOPY(tmp_co, mv->co);
876                                   MTC_Mat4MulVecfl(offset, tmp_co);
877
878                                   for(j = 0; j < maxVerts; j++) {
879                                           /* if vertex already merged, don't use it */
880                                           if( indexMap[j].merge != -1 ) continue;
881
882                                           inMV = &src_mvert[j];
883                                           /* if this vert is within merge limit, merge */
884                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist)) {
885                                                   indexMap[i].merge = j;
886
887                                                   /* test for merging with final copy of merge target */
888                                                   if(amd->flags & MOD_ARR_MERGEFINAL) {
889                                                           VECCOPY(tmp_co, inMV->co);
890                                                           inMV = &src_mvert[i];
891                                                           MTC_Mat4MulVecfl(final_offset, tmp_co);
892                                                           if(VecLenCompare(tmp_co, inMV->co, amd->merge_dist))
893                                                                   indexMap[i].merge_final = 1;
894                                                   }
895                                                   break;
896                                           }
897                                   }
898                           }
899
900                           /* if no merging, generate copies of this vert */
901                           if(indexMap[i].merge < 0) {
902                                   for(j=0; j < count - 1; j++) {
903                                           mv2 = &mvert[numVerts];
904
905                                           DM_copy_vert_data(result, result, numVerts - 1, numVerts, 1);
906                                           *mv2 = *mv;
907                                           numVerts++;
908
909                                           MTC_Mat4MulVecfl(offset, co);
910                                           VECCOPY(mv2->co, co);
911                                   }
912                           } else if(indexMap[i].merge != i && indexMap[i].merge_final) {
913                         /* if this vert is not merging with itself, and it is merging
914                                   * with the final copy of its merge target, remove the first copy
915                         */
916                                   numVerts--;
917                                   DM_free_vert_data(result, numVerts, 1);
918                           }
919                   }
920
921                   /* make a hashtable so we can avoid duplicate edges from merging */
922                   edges = BLI_edgehash_new();
923
924                   maxEdges = dm->getNumEdges(dm);
925                   medge = CDDM_get_edges(result);
926                   for(i = 0; i < maxEdges; i++) {
927                           MEdge inMED;
928                           MEdge med;
929                           MEdge *med2;
930                           int vert1, vert2;
931
932                           dm->getEdge(dm, i, &inMED);
933
934                           med = inMED;
935                           med.v1 = indexMap[inMED.v1].new;
936                           med.v2 = indexMap[inMED.v2].new;
937
938                 /* if vertices are to be merged with the final copies of their
939                           * merge targets, calculate that final copy
940                 */
941                           if(indexMap[inMED.v1].merge_final) {
942                                   med.v1 = calc_mapping(indexMap, indexMap[inMED.v1].merge,
943                                                   count - 1);
944                           }
945                           if(indexMap[inMED.v2].merge_final) {
946                                   med.v2 = calc_mapping(indexMap, indexMap[inMED.v2].merge,
947                                                   count - 1);
948                           }
949
950                           if(med.v1 == med.v2) continue;
951
952                           if (initFlags) {
953                                   med.flag |= ME_EDGEDRAW | ME_EDGERENDER;
954                           }
955
956                           if(!BLI_edgehash_haskey(edges, med.v1, med.v2)) {
957                                   DM_copy_edge_data(dm, result, i, numEdges, 1);
958                                   medge[numEdges] = med;
959                                   numEdges++;
960
961                                   BLI_edgehash_insert(edges, med.v1, med.v2, NULL);
962                           }
963
964                           for(j = 1; j < count; j++)
965                           {
966                                   vert1 = calc_mapping(indexMap, inMED.v1, j);
967                                   vert2 = calc_mapping(indexMap, inMED.v2, j);
968                                   /* avoid duplicate edges */
969                                   if(!BLI_edgehash_haskey(edges, vert1, vert2)) {
970                                           med2 = &medge[numEdges];
971
972                                           DM_copy_edge_data(dm, result, i, numEdges, 1);
973                                           *med2 = med;
974                                           numEdges++;
975
976                                           med2->v1 = vert1;
977                                           med2->v2 = vert2;
978
979                                           BLI_edgehash_insert(edges, med2->v1, med2->v2, NULL);
980                                   }
981                           }
982                   }
983
984                   maxFaces = dm->getNumFaces(dm);
985                   mface = CDDM_get_faces(result);
986                   for (i=0; i < maxFaces; i++) {
987                           MFace inMF;
988                           MFace *mf = &mface[numFaces];
989
990                           dm->getFace(dm, i, &inMF);
991
992                           DM_copy_face_data(dm, result, i, numFaces, 1);
993                           *mf = inMF;
994
995                           mf->v1 = indexMap[inMF.v1].new;
996                           mf->v2 = indexMap[inMF.v2].new;
997                           mf->v3 = indexMap[inMF.v3].new;
998                           if(inMF.v4)
999                                   mf->v4 = indexMap[inMF.v4].new;
1000
1001                 /* if vertices are to be merged with the final copies of their
1002                           * merge targets, calculate that final copy
1003                 */
1004                           if(indexMap[inMF.v1].merge_final)
1005                                   mf->v1 = calc_mapping(indexMap, indexMap[inMF.v1].merge, count-1);
1006                           if(indexMap[inMF.v2].merge_final)
1007                                   mf->v2 = calc_mapping(indexMap, indexMap[inMF.v2].merge, count-1);
1008                           if(indexMap[inMF.v3].merge_final)
1009                                   mf->v3 = calc_mapping(indexMap, indexMap[inMF.v3].merge, count-1);
1010                           if(inMF.v4 && indexMap[inMF.v4].merge_final)
1011                                   mf->v4 = calc_mapping(indexMap, indexMap[inMF.v4].merge, count-1);
1012
1013                           if(test_index_face(mf, &result->faceData, numFaces, inMF.v4?4:3) < 3)
1014                                   continue;
1015
1016                           numFaces++;
1017
1018                           /* if the face has fewer than 3 vertices, don't create it */
1019                           if(mf->v3 == 0 || (mf->v1 && (mf->v1 == mf->v3 || mf->v1 == mf->v4))) {
1020                                   numFaces--;
1021                                   DM_free_face_data(result, numFaces, 1);
1022                           }
1023
1024                           for(j = 1; j < count; j++)
1025                           {
1026                                   MFace *mf2 = &mface[numFaces];
1027
1028                                   DM_copy_face_data(dm, result, i, numFaces, 1);
1029                                   *mf2 = *mf;
1030
1031                                   mf2->v1 = calc_mapping(indexMap, inMF.v1, j);
1032                                   mf2->v2 = calc_mapping(indexMap, inMF.v2, j);
1033                                   mf2->v3 = calc_mapping(indexMap, inMF.v3, j);
1034                                   if (inMF.v4)
1035                                           mf2->v4 = calc_mapping(indexMap, inMF.v4, j);
1036
1037                                   test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1038                                   numFaces++;
1039
1040                                   /* if the face has fewer than 3 vertices, don't create it */
1041                                   if(mf2->v3 == 0 || (mf2->v1 && (mf2->v1 == mf2->v3 || mf2->v1 ==
1042                                                                  mf2->v4))) {
1043                                           numFaces--;
1044                                           DM_free_face_data(result, numFaces, 1);
1045                                                                  }
1046                           }
1047                   }
1048
1049                   /* add start and end caps */
1050                   if(start_cap) {
1051                           float startoffset[4][4];
1052                           MVert *cap_mvert;
1053                           MEdge *cap_medge;
1054                           MFace *cap_mface;
1055                           int *origindex;
1056                           int *vert_map;
1057                           int capVerts, capEdges, capFaces;
1058
1059                           capVerts = start_cap->getNumVerts(start_cap);
1060                           capEdges = start_cap->getNumEdges(start_cap);
1061                           capFaces = start_cap->getNumFaces(start_cap);
1062                           cap_mvert = start_cap->getVertArray(start_cap);
1063                           cap_medge = start_cap->getEdgeArray(start_cap);
1064                           cap_mface = start_cap->getFaceArray(start_cap);
1065
1066                           Mat4Invert(startoffset, offset);
1067
1068                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1069                                           "arrayModifier_doArray vert_map");
1070
1071                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1072                           for(i = 0; i < capVerts; i++) {
1073                                   MVert *mv = &cap_mvert[i];
1074                                   short merged = 0;
1075
1076                                   if(amd->flags & MOD_ARR_MERGE) {
1077                                           float tmp_co[3];
1078                                           MVert *in_mv;
1079                                           int j;
1080
1081                                           VECCOPY(tmp_co, mv->co);
1082                                           Mat4MulVecfl(startoffset, tmp_co);
1083
1084                                           for(j = 0; j < maxVerts; j++) {
1085                                                   in_mv = &src_mvert[j];
1086                                                   /* if this vert is within merge limit, merge */
1087                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1088                                                           vert_map[i] = calc_mapping(indexMap, j, 0);
1089                                                           merged = 1;
1090                                                           break;
1091                                                   }
1092                                           }
1093                                   }
1094
1095                                   if(!merged) {
1096                                           DM_copy_vert_data(start_cap, result, i, numVerts, 1);
1097                                           mvert[numVerts] = *mv;
1098                                           Mat4MulVecfl(startoffset, mvert[numVerts].co);
1099                                           origindex[numVerts] = ORIGINDEX_NONE;
1100
1101                                           vert_map[i] = numVerts;
1102
1103                                           numVerts++;
1104                                   }
1105                           }
1106                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1107                           for(i = 0; i < capEdges; i++) {
1108                                   int v1, v2;
1109
1110                                   v1 = vert_map[cap_medge[i].v1];
1111                                   v2 = vert_map[cap_medge[i].v2];
1112
1113                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1114                                           DM_copy_edge_data(start_cap, result, i, numEdges, 1);
1115                                           medge[numEdges] = cap_medge[i];
1116                                           medge[numEdges].v1 = v1;
1117                                           medge[numEdges].v2 = v2;
1118                                           origindex[numEdges] = ORIGINDEX_NONE;
1119
1120                                           numEdges++;
1121                                   }
1122                           }
1123                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1124                           for(i = 0; i < capFaces; i++) {
1125                                   DM_copy_face_data(start_cap, result, i, numFaces, 1);
1126                                   mface[numFaces] = cap_mface[i];
1127                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1128                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1129                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1130                                   if(mface[numFaces].v4)
1131                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1132                                   origindex[numFaces] = ORIGINDEX_NONE;
1133
1134                                   numFaces++;
1135                           }
1136
1137                           MEM_freeN(vert_map);
1138                           start_cap->release(start_cap);
1139                   }
1140
1141                   if(end_cap) {
1142                           float endoffset[4][4];
1143                           MVert *cap_mvert;
1144                           MEdge *cap_medge;
1145                           MFace *cap_mface;
1146                           int *origindex;
1147                           int *vert_map;
1148                           int capVerts, capEdges, capFaces;
1149
1150                           capVerts = end_cap->getNumVerts(end_cap);
1151                           capEdges = end_cap->getNumEdges(end_cap);
1152                           capFaces = end_cap->getNumFaces(end_cap);
1153                           cap_mvert = end_cap->getVertArray(end_cap);
1154                           cap_medge = end_cap->getEdgeArray(end_cap);
1155                           cap_mface = end_cap->getFaceArray(end_cap);
1156
1157                           Mat4MulMat4(endoffset, final_offset, offset);
1158
1159                           vert_map = MEM_callocN(sizeof(*vert_map) * capVerts,
1160                                           "arrayModifier_doArray vert_map");
1161
1162                           origindex = result->getVertDataArray(result, CD_ORIGINDEX);
1163                           for(i = 0; i < capVerts; i++) {
1164                                   MVert *mv = &cap_mvert[i];
1165                                   short merged = 0;
1166
1167                                   if(amd->flags & MOD_ARR_MERGE) {
1168                                           float tmp_co[3];
1169                                           MVert *in_mv;
1170                                           int j;
1171
1172                                           VECCOPY(tmp_co, mv->co);
1173                                           Mat4MulVecfl(offset, tmp_co);
1174
1175                                           for(j = 0; j < maxVerts; j++) {
1176                                                   in_mv = &src_mvert[j];
1177                                                   /* if this vert is within merge limit, merge */
1178                                                   if(VecLenCompare(tmp_co, in_mv->co, amd->merge_dist)) {
1179                                                           vert_map[i] = calc_mapping(indexMap, j, count - 1);
1180                                                           merged = 1;
1181                                                           break;
1182                                                   }
1183                                           }
1184                                   }
1185
1186                                   if(!merged) {
1187                                           DM_copy_vert_data(end_cap, result, i, numVerts, 1);
1188                                           mvert[numVerts] = *mv;
1189                                           Mat4MulVecfl(endoffset, mvert[numVerts].co);
1190                                           origindex[numVerts] = ORIGINDEX_NONE;
1191
1192                                           vert_map[i] = numVerts;
1193
1194                                           numVerts++;
1195                                   }
1196                           }
1197                           origindex = result->getEdgeDataArray(result, CD_ORIGINDEX);
1198                           for(i = 0; i < capEdges; i++) {
1199                                   int v1, v2;
1200
1201                                   v1 = vert_map[cap_medge[i].v1];
1202                                   v2 = vert_map[cap_medge[i].v2];
1203
1204                                   if(!BLI_edgehash_haskey(edges, v1, v2)) {
1205                                           DM_copy_edge_data(end_cap, result, i, numEdges, 1);
1206                                           medge[numEdges] = cap_medge[i];
1207                                           medge[numEdges].v1 = v1;
1208                                           medge[numEdges].v2 = v2;
1209                                           origindex[numEdges] = ORIGINDEX_NONE;
1210
1211                                           numEdges++;
1212                                   }
1213                           }
1214                           origindex = result->getFaceDataArray(result, CD_ORIGINDEX);
1215                           for(i = 0; i < capFaces; i++) {
1216                                   DM_copy_face_data(end_cap, result, i, numFaces, 1);
1217                                   mface[numFaces] = cap_mface[i];
1218                                   mface[numFaces].v1 = vert_map[mface[numFaces].v1];
1219                                   mface[numFaces].v2 = vert_map[mface[numFaces].v2];
1220                                   mface[numFaces].v3 = vert_map[mface[numFaces].v3];
1221                                   if(mface[numFaces].v4)
1222                                           mface[numFaces].v4 = vert_map[mface[numFaces].v4];
1223                                   origindex[numFaces] = ORIGINDEX_NONE;
1224
1225                                   numFaces++;
1226                           }
1227
1228                           MEM_freeN(vert_map);
1229                           end_cap->release(end_cap);
1230                   }
1231
1232                   BLI_edgehash_free(edges, NULL);
1233                   MEM_freeN(indexMap);
1234
1235                   CDDM_lower_num_verts(result, numVerts);
1236                   CDDM_lower_num_edges(result, numEdges);
1237                   CDDM_lower_num_faces(result, numFaces);
1238
1239                   return result;
1240 }
1241
1242 static DerivedMesh *arrayModifier_applyModifier(
1243                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1244   int useRenderParams, int isFinalCalc)
1245 {
1246         DerivedMesh *result;
1247         ArrayModifierData *amd = (ArrayModifierData*) md;
1248
1249         result = arrayModifier_doArray(amd, ob, derivedData, 0);
1250
1251         if(result != derivedData)
1252                 CDDM_calc_normals(result);
1253
1254         return result;
1255 }
1256
1257 static DerivedMesh *arrayModifier_applyModifierEM(
1258                 ModifierData *md, Object *ob, EditMesh *editData,
1259   DerivedMesh *derivedData)
1260 {
1261         return arrayModifier_applyModifier(md, ob, derivedData, 0, 1);
1262 }
1263
1264 /* Mirror */
1265
1266 static void mirrorModifier_initData(ModifierData *md)
1267 {
1268         MirrorModifierData *mmd = (MirrorModifierData*) md;
1269
1270         mmd->flag |= MOD_MIR_AXIS_X;
1271         mmd->tolerance = 0.001;
1272         mmd->mirror_ob = NULL;
1273 }
1274
1275 static void mirrorModifier_copyData(ModifierData *md, ModifierData *target)
1276 {
1277         MirrorModifierData *mmd = (MirrorModifierData*) md;
1278         MirrorModifierData *tmmd = (MirrorModifierData*) target;
1279
1280         tmmd->axis = mmd->axis;
1281         tmmd->flag = mmd->flag;
1282         tmmd->tolerance = mmd->tolerance;
1283         tmmd->mirror_ob = mmd->mirror_ob;;
1284 }
1285
1286 static void mirrorModifier_foreachObjectLink(
1287                                              ModifierData *md, Object *ob,
1288           void (*walk)(void *userData, Object *ob, Object **obpoin),
1289                  void *userData)
1290 {
1291         MirrorModifierData *mmd = (MirrorModifierData*) md;
1292
1293         walk(userData, ob, &mmd->mirror_ob);
1294 }
1295
1296 static void mirrorModifier_updateDepgraph(ModifierData *md, DagForest *forest,
1297                                           Object *ob, DagNode *obNode)
1298 {
1299         MirrorModifierData *mmd = (MirrorModifierData*) md;
1300
1301         if(mmd->mirror_ob) {
1302                 DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
1303
1304                 dag_add_relation(forest, latNode, obNode,
1305                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mirror Modifier");
1306         }
1307 }
1308
1309 static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
1310                                    Object *ob,
1311        DerivedMesh *dm,
1312        int initFlags,
1313        int axis)
1314 {
1315         int i;
1316         float tolerance = mmd->tolerance;
1317         DerivedMesh *result;
1318         int numVerts, numEdges, numFaces;
1319         int maxVerts = dm->getNumVerts(dm);
1320         int maxEdges = dm->getNumEdges(dm);
1321         int maxFaces = dm->getNumFaces(dm);
1322         int (*indexMap)[2];
1323         float mtx[4][4], imtx[4][4];
1324
1325         numVerts = numEdges = numFaces = 0;
1326
1327         indexMap = MEM_mallocN(sizeof(*indexMap) * maxVerts, "indexmap");
1328
1329         result = CDDM_from_template(dm, maxVerts * 2, maxEdges * 2, maxFaces * 2);
1330
1331         if (mmd->mirror_ob) {
1332                 float obinv[4][4];
1333
1334                 Mat4Invert(obinv, mmd->mirror_ob->obmat);
1335                 Mat4MulMat4(mtx, ob->obmat, obinv);
1336                 Mat4Invert(imtx, mtx);
1337         }
1338
1339         for(i = 0; i < maxVerts; i++) {
1340                 MVert inMV;
1341                 MVert *mv = CDDM_get_vert(result, numVerts);
1342                 int isShared;
1343                 float co[3];
1344
1345                 dm->getVert(dm, i, &inMV);
1346
1347                 VecCopyf(co, inMV.co);
1348
1349                 if (mmd->mirror_ob) {
1350                         VecMat4MulVecfl(co, mtx, co);
1351                 }
1352                 isShared = ABS(co[axis])<=tolerance;
1353
1354                 /* Because the topology result (# of vertices) must be the same if
1355                 * the mesh data is overridden by vertex cos, have to calc sharedness
1356                 * based on original coordinates. This is why we test before copy.
1357                 */
1358                 DM_copy_vert_data(dm, result, i, numVerts, 1);
1359                 *mv = inMV;
1360                 numVerts++;
1361
1362                 indexMap[i][0] = numVerts - 1;
1363                 indexMap[i][1] = !isShared;
1364
1365                 if(isShared) {
1366                         co[axis] = 0;
1367                         if (mmd->mirror_ob) {
1368                                 VecMat4MulVecfl(co, imtx, co);
1369                         }
1370                         VecCopyf(mv->co, co);
1371                         
1372                         mv->flag |= ME_VERT_MERGED;
1373                 } else {
1374                         MVert *mv2 = CDDM_get_vert(result, numVerts);
1375
1376                         DM_copy_vert_data(dm, result, i, numVerts, 1);
1377                         *mv2 = *mv;
1378                         numVerts++;
1379
1380                         co[axis] = -co[axis];
1381                         if (mmd->mirror_ob) {
1382                                 VecMat4MulVecfl(co, imtx, co);
1383                         }
1384                         VecCopyf(mv2->co, co);
1385                 }
1386         }
1387
1388         for(i = 0; i < maxEdges; i++) {
1389                 MEdge inMED;
1390                 MEdge *med = CDDM_get_edge(result, numEdges);
1391
1392                 dm->getEdge(dm, i, &inMED);
1393
1394                 DM_copy_edge_data(dm, result, i, numEdges, 1);
1395                 *med = inMED;
1396                 numEdges++;
1397
1398                 med->v1 = indexMap[inMED.v1][0];
1399                 med->v2 = indexMap[inMED.v2][0];
1400                 if(initFlags)
1401                         med->flag |= ME_EDGEDRAW | ME_EDGERENDER;
1402
1403                 if(indexMap[inMED.v1][1] || indexMap[inMED.v2][1]) {
1404                         MEdge *med2 = CDDM_get_edge(result, numEdges);
1405
1406                         DM_copy_edge_data(dm, result, i, numEdges, 1);
1407                         *med2 = *med;
1408                         numEdges++;
1409
1410                         med2->v1 += indexMap[inMED.v1][1];
1411                         med2->v2 += indexMap[inMED.v2][1];
1412                 }
1413         }
1414
1415         for(i = 0; i < maxFaces; i++) {
1416                 MFace inMF;
1417                 MFace *mf = CDDM_get_face(result, numFaces);
1418
1419                 dm->getFace(dm, i, &inMF);
1420
1421                 DM_copy_face_data(dm, result, i, numFaces, 1);
1422                 *mf = inMF;
1423                 numFaces++;
1424
1425                 mf->v1 = indexMap[inMF.v1][0];
1426                 mf->v2 = indexMap[inMF.v2][0];
1427                 mf->v3 = indexMap[inMF.v3][0];
1428                 mf->v4 = indexMap[inMF.v4][0];
1429                 
1430                 if(indexMap[inMF.v1][1]
1431                                  || indexMap[inMF.v2][1]
1432                                  || indexMap[inMF.v3][1]
1433                                  || (mf->v4 && indexMap[inMF.v4][1])) {
1434                         MFace *mf2 = CDDM_get_face(result, numFaces);
1435                         static int corner_indices[4] = {2, 1, 0, 3};
1436
1437                         DM_copy_face_data(dm, result, i, numFaces, 1);
1438                         *mf2 = *mf;
1439
1440                         mf2->v1 += indexMap[inMF.v1][1];
1441                         mf2->v2 += indexMap[inMF.v2][1];
1442                         mf2->v3 += indexMap[inMF.v3][1];
1443                         if(inMF.v4) mf2->v4 += indexMap[inMF.v4][1];
1444
1445                         /* mirror UVs if enabled */
1446                         if(mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
1447                                 MTFace *tf = result->getFaceData(result, numFaces, CD_MTFACE);
1448                                 if(tf) {
1449                                         int j;
1450                                         for(j = 0; j < 4; ++j) {
1451                                                 if(mmd->flag & MOD_MIR_MIRROR_U)
1452                                                         tf->uv[j][0] = 1.0f - tf->uv[j][0];
1453                                                 if(mmd->flag & MOD_MIR_MIRROR_V)
1454                                                         tf->uv[j][1] = 1.0f - tf->uv[j][1];
1455                                         }
1456                                 }
1457                         }
1458
1459                         /* Flip face normal */
1460                         SWAP(int, mf2->v1, mf2->v3);
1461                         DM_swap_face_data(result, numFaces, corner_indices);
1462
1463                         test_index_face(mf2, &result->faceData, numFaces, inMF.v4?4:3);
1464                         numFaces++;
1465                                  }
1466         }
1467
1468         MEM_freeN(indexMap);
1469
1470         CDDM_lower_num_verts(result, numVerts);
1471         CDDM_lower_num_edges(result, numEdges);
1472         CDDM_lower_num_faces(result, numFaces);
1473
1474         return result;
1475 }
1476
1477 static DerivedMesh *mirrorModifier__doMirror(MirrorModifierData *mmd,
1478                                              Object *ob, DerivedMesh *dm,
1479           int initFlags)
1480 {
1481         DerivedMesh *result = dm;
1482
1483         /* check which axes have been toggled and mirror accordingly */
1484         if(mmd->flag & MOD_MIR_AXIS_X) {
1485                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 0);
1486         }
1487         if(mmd->flag & MOD_MIR_AXIS_Y) {
1488                 DerivedMesh *tmp = result;
1489                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 1);
1490                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1491         }
1492         if(mmd->flag & MOD_MIR_AXIS_Z) {
1493                 DerivedMesh *tmp = result;
1494                 result = doMirrorOnAxis(mmd, ob, result, initFlags, 2);
1495                 if(tmp != dm) tmp->release(tmp); /* free intermediate results */
1496         }
1497
1498         return result;
1499 }
1500
1501 static DerivedMesh *mirrorModifier_applyModifier(
1502                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
1503   int useRenderParams, int isFinalCalc)
1504 {
1505         DerivedMesh *result;
1506         MirrorModifierData *mmd = (MirrorModifierData*) md;
1507
1508         result = mirrorModifier__doMirror(mmd, ob, derivedData, 0);
1509
1510         if(result != derivedData)
1511                 CDDM_calc_normals(result);
1512         
1513         return result;
1514 }
1515
1516 static DerivedMesh *mirrorModifier_applyModifierEM(
1517                 ModifierData *md, Object *ob, EditMesh *editData,
1518   DerivedMesh *derivedData)
1519 {
1520         return mirrorModifier_applyModifier(md, ob, derivedData, 0, 1);
1521 }
1522
1523 /* EdgeSplit */
1524 /* EdgeSplit modifier: Splits edges in the mesh according to sharpness flag
1525  * or edge angle (can be used to achieve autosmoothing)
1526 */
1527 #if 0
1528 #define EDGESPLIT_DEBUG_3
1529 #define EDGESPLIT_DEBUG_2
1530 #define EDGESPLIT_DEBUG_1
1531 #define EDGESPLIT_DEBUG_0
1532 #endif
1533
1534 static void edgesplitModifier_initData(ModifierData *md)
1535 {
1536         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1537
1538         /* default to 30-degree split angle, sharpness from both angle & flag
1539         */
1540         emd->split_angle = 30;
1541         emd->flags = MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG;
1542 }
1543
1544 static void edgesplitModifier_copyData(ModifierData *md, ModifierData *target)
1545 {
1546         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
1547         EdgeSplitModifierData *temd = (EdgeSplitModifierData*) target;
1548
1549         temd->split_angle = emd->split_angle;
1550         temd->flags = emd->flags;
1551 }
1552
1553 /* Mesh data for edgesplit operation */
1554 typedef struct SmoothVert {
1555         LinkNode *faces;     /* all faces which use this vert */
1556         int oldIndex; /* the index of the original DerivedMesh vert */
1557         int newIndex; /* the index of the new DerivedMesh vert */
1558 } SmoothVert;
1559
1560 #define SMOOTHEDGE_NUM_VERTS 2
1561
1562 typedef struct SmoothEdge {
1563         SmoothVert *verts[SMOOTHEDGE_NUM_VERTS]; /* the verts used by this edge */
1564         LinkNode *faces;     /* all faces which use this edge */
1565         int oldIndex; /* the index of the original DerivedMesh edge */
1566         int newIndex; /* the index of the new DerivedMesh edge */
1567         short flag; /* the flags from the original DerivedMesh edge */
1568 } SmoothEdge;
1569
1570 #define SMOOTHFACE_MAX_EDGES 4
1571
1572 typedef struct SmoothFace {
1573         SmoothEdge *edges[SMOOTHFACE_MAX_EDGES]; /* nonexistent edges == NULL */
1574         int flip[SMOOTHFACE_MAX_EDGES]; /* 1 = flip edge dir, 0 = don't flip */
1575         float normal[3]; /* the normal of this face */
1576         int oldIndex; /* the index of the original DerivedMesh face */
1577         int newIndex; /* the index of the new DerivedMesh face */
1578 } SmoothFace;
1579
1580 typedef struct SmoothMesh {
1581         SmoothVert *verts;
1582         SmoothEdge *edges;
1583         SmoothFace *faces;
1584         int num_verts, num_edges, num_faces;
1585         int max_verts, max_edges, max_faces;
1586         DerivedMesh *dm;
1587         float threshold; /* the cosine of the smoothing angle */
1588         int flags;
1589 } SmoothMesh;
1590
1591 static SmoothVert *smoothvert_copy(SmoothVert *vert, SmoothMesh *mesh)
1592 {
1593         SmoothVert *copy = &mesh->verts[mesh->num_verts];
1594
1595         if(mesh->num_verts >= mesh->max_verts) {
1596                 printf("Attempted to add a SmoothMesh vert beyond end of array\n");
1597                 return NULL;
1598         }
1599
1600         *copy = *vert;
1601         copy->faces = NULL;
1602         copy->newIndex = mesh->num_verts;
1603         ++mesh->num_verts;
1604
1605 #ifdef EDGESPLIT_DEBUG_2
1606         printf("copied vert %4d to vert %4d\n", vert->newIndex, copy->newIndex);
1607 #endif
1608         return copy;
1609 }
1610
1611 static SmoothEdge *smoothedge_copy(SmoothEdge *edge, SmoothMesh *mesh)
1612 {
1613         SmoothEdge *copy = &mesh->edges[mesh->num_edges];
1614
1615         if(mesh->num_edges >= mesh->max_edges) {
1616                 printf("Attempted to add a SmoothMesh edge beyond end of array\n");
1617                 return NULL;
1618         }
1619
1620         *copy = *edge;
1621         copy->faces = NULL;
1622         copy->newIndex = mesh->num_edges;
1623         ++mesh->num_edges;
1624
1625 #ifdef EDGESPLIT_DEBUG_2
1626         printf("copied edge %4d to edge %4d\n", edge->newIndex, copy->newIndex);
1627 #endif
1628         return copy;
1629 }
1630
1631 static int smoothedge_has_vert(SmoothEdge *edge, SmoothVert *vert)
1632 {
1633         int i;
1634         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++)
1635                 if(edge->verts[i] == vert) return 1;
1636
1637         return 0;
1638 }
1639
1640 static SmoothMesh *smoothmesh_new(int num_verts, int num_edges, int num_faces,
1641                                   int max_verts, int max_edges, int max_faces)
1642 {
1643         SmoothMesh *mesh = MEM_callocN(sizeof(*mesh), "smoothmesh");
1644         mesh->verts = MEM_callocN(sizeof(*mesh->verts) * max_verts,
1645                                   "SmoothMesh.verts");
1646         mesh->edges = MEM_callocN(sizeof(*mesh->edges) * max_edges,
1647                                   "SmoothMesh.edges");
1648         mesh->faces = MEM_callocN(sizeof(*mesh->faces) * max_faces,
1649                                   "SmoothMesh.faces");
1650
1651         mesh->num_verts = num_verts;
1652         mesh->num_edges = num_edges;
1653         mesh->num_faces = num_faces;
1654
1655         mesh->max_verts = max_verts;
1656         mesh->max_edges = max_edges;
1657         mesh->max_faces = max_faces;
1658
1659         return mesh;
1660 }
1661
1662 static void smoothmesh_free(SmoothMesh *mesh)
1663 {
1664         int i;
1665
1666         for(i = 0; i < mesh->num_verts; ++i)
1667                 BLI_linklist_free(mesh->verts[i].faces, NULL);
1668
1669         for(i = 0; i < mesh->num_edges; ++i)
1670                 BLI_linklist_free(mesh->edges[i].faces, NULL);
1671
1672         MEM_freeN(mesh->verts);
1673         MEM_freeN(mesh->edges);
1674         MEM_freeN(mesh->faces);
1675         MEM_freeN(mesh);
1676 }
1677
1678 static void smoothmesh_resize_verts(SmoothMesh *mesh, int max_verts)
1679 {
1680         int i;
1681         SmoothVert *tmp;
1682
1683         if(max_verts <= mesh->max_verts) return;
1684
1685         tmp = MEM_callocN(sizeof(*tmp) * max_verts, "SmoothMesh.verts");
1686
1687         memcpy(tmp, mesh->verts, sizeof(*tmp) * mesh->num_verts);
1688
1689         /* remap vert pointers in edges */
1690         for(i = 0; i < mesh->num_edges; ++i) {
1691                 int j;
1692                 SmoothEdge *edge = &mesh->edges[i];
1693
1694                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; ++j)
1695                         /* pointer arithmetic to get vert array index */
1696                         edge->verts[j] = &tmp[edge->verts[j] - mesh->verts];
1697         }
1698
1699         MEM_freeN(mesh->verts);
1700         mesh->verts = tmp;
1701         mesh->max_verts = max_verts;
1702 }
1703
1704 static void smoothmesh_resize_edges(SmoothMesh *mesh, int max_edges)
1705 {
1706         int i;
1707         SmoothEdge *tmp;
1708
1709         if(max_edges <= mesh->max_edges) return;
1710
1711         tmp = MEM_callocN(sizeof(*tmp) * max_edges, "SmoothMesh.edges");
1712
1713         memcpy(tmp, mesh->edges, sizeof(*tmp) * mesh->num_edges);
1714
1715         /* remap edge pointers in faces */
1716         for(i = 0; i < mesh->num_faces; ++i) {
1717                 int j;
1718                 SmoothFace *face = &mesh->faces[i];
1719
1720                 for(j = 0; j < SMOOTHFACE_MAX_EDGES; ++j)
1721                         if(face->edges[j])
1722                                 /* pointer arithmetic to get edge array index */
1723                                 face->edges[j] = &tmp[face->edges[j] - mesh->edges];
1724         }
1725
1726         MEM_freeN(mesh->edges);
1727         mesh->edges = tmp;
1728         mesh->max_edges = max_edges;
1729 }
1730
1731 #ifdef EDGESPLIT_DEBUG_0
1732 static void smoothmesh_print(SmoothMesh *mesh)
1733 {
1734         int i, j;
1735         DerivedMesh *dm = mesh->dm;
1736
1737         printf("--- SmoothMesh ---\n");
1738         printf("--- Vertices ---\n");
1739         for(i = 0; i < mesh->num_verts; i++) {
1740                 SmoothVert *vert = &mesh->verts[i];
1741                 LinkNode *node;
1742                 MVert mv;
1743
1744                 dm->getVert(dm, vert->oldIndex, &mv);
1745
1746                 printf("%3d: ind={%3d, %3d}, pos={% 5.1f, % 5.1f, % 5.1f}",
1747                        i, vert->oldIndex, vert->newIndex,
1748          mv.co[0], mv.co[1], mv.co[2]);
1749                 printf(", faces={");
1750                 for(node = vert->faces; node != NULL; node = node->next) {
1751                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1752                 }
1753                 printf("}\n");
1754         }
1755
1756         printf("\n--- Edges ---\n");
1757         for(i = 0; i < mesh->num_edges; i++) {
1758                 SmoothEdge *edge = &mesh->edges[i];
1759                 LinkNode *node;
1760
1761                 printf("%4d: indices={%4d, %4d}, verts={%4d, %4d}",
1762                        i,
1763          edge->oldIndex, edge->newIndex,
1764   edge->verts[0]->newIndex, edge->verts[1]->newIndex);
1765                 if(edge->verts[0] == edge->verts[1]) printf(" <- DUPLICATE VERTEX");
1766                 printf(", faces={");
1767                 for(node = edge->faces; node != NULL; node = node->next) {
1768                         printf(" %d", ((SmoothFace *)node->link)->newIndex);
1769                 }
1770                 printf("}\n");
1771         }
1772
1773         printf("\n--- Faces ---\n");
1774         for(i = 0; i < mesh->num_faces; i++) {
1775                 SmoothFace *face = &mesh->faces[i];
1776
1777                 printf("%4d: indices={%4d, %4d}, edges={", i,
1778                        face->oldIndex, face->newIndex);
1779                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1780                         if(face->flip[j])
1781                                 printf(" -%-2d", face->edges[j]->newIndex);
1782                         else
1783                                 printf("  %-2d", face->edges[j]->newIndex);
1784                 }
1785                 printf("}, verts={");
1786                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1787                         printf(" %d", face->edges[j]->verts[face->flip[j]]->newIndex);
1788                 }
1789                 printf("}\n");
1790         }
1791 }
1792 #endif
1793
1794 static SmoothMesh *smoothmesh_from_derivedmesh(DerivedMesh *dm)
1795 {
1796         SmoothMesh *mesh;
1797         EdgeHash *edges = BLI_edgehash_new();
1798         int i;
1799         int totvert, totedge, totface;
1800
1801         totvert = dm->getNumVerts(dm);
1802         totedge = dm->getNumEdges(dm);
1803         totface = dm->getNumFaces(dm);
1804
1805         mesh = smoothmesh_new(totvert, totedge, totface,
1806                               totvert, totedge, totface);
1807
1808         mesh->dm = dm;
1809
1810         for(i = 0; i < totvert; i++) {
1811                 SmoothVert *vert = &mesh->verts[i];
1812
1813                 vert->oldIndex = vert->newIndex = i;
1814         }
1815
1816         for(i = 0; i < totedge; i++) {
1817                 SmoothEdge *edge = &mesh->edges[i];
1818                 MEdge med;
1819
1820                 dm->getEdge(dm, i, &med);
1821                 edge->verts[0] = &mesh->verts[med.v1];
1822                 edge->verts[1] = &mesh->verts[med.v2];
1823                 edge->oldIndex = edge->newIndex = i;
1824                 edge->flag = med.flag;
1825
1826                 BLI_edgehash_insert(edges, med.v1, med.v2, edge);
1827         }
1828
1829         for(i = 0; i < totface; i++) {
1830                 SmoothFace *face = &mesh->faces[i];
1831                 MFace mf;
1832                 MVert v1, v2, v3;
1833                 int j;
1834
1835                 dm->getFace(dm, i, &mf);
1836
1837                 dm->getVert(dm, mf.v1, &v1);
1838                 dm->getVert(dm, mf.v2, &v2);
1839                 dm->getVert(dm, mf.v3, &v3);
1840                 face->edges[0] = BLI_edgehash_lookup(edges, mf.v1, mf.v2);
1841                 if(face->edges[0]->verts[1]->oldIndex == mf.v1) face->flip[0] = 1;
1842                 face->edges[1] = BLI_edgehash_lookup(edges, mf.v2, mf.v3);
1843                 if(face->edges[1]->verts[1]->oldIndex == mf.v2) face->flip[1] = 1;
1844                 if(mf.v4) {
1845                         MVert v4;
1846                         dm->getVert(dm, mf.v4, &v4);
1847                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v4);
1848                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
1849                         face->edges[3] = BLI_edgehash_lookup(edges, mf.v4, mf.v1);
1850                         if(face->edges[3]->verts[1]->oldIndex == mf.v4) face->flip[3] = 1;
1851                         CalcNormFloat4(v1.co, v2.co, v3.co, v4.co, face->normal);
1852                 } else {
1853                         face->edges[2] = BLI_edgehash_lookup(edges, mf.v3, mf.v1);
1854                         if(face->edges[2]->verts[1]->oldIndex == mf.v3) face->flip[2] = 1;
1855                         face->edges[3] = NULL;
1856                         CalcNormFloat(v1.co, v2.co, v3.co, face->normal);
1857                 }
1858
1859                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
1860                         SmoothEdge *edge = face->edges[j];
1861                         BLI_linklist_prepend(&edge->faces, face);
1862                         BLI_linklist_prepend(&edge->verts[face->flip[j]]->faces, face);
1863                 }
1864
1865                 face->oldIndex = face->newIndex = i;
1866         }
1867
1868         BLI_edgehash_free(edges, NULL);
1869
1870         return mesh;
1871 }
1872
1873 static DerivedMesh *CDDM_from_smoothmesh(SmoothMesh *mesh)
1874 {
1875         DerivedMesh *result = CDDM_from_template(mesh->dm,
1876                         mesh->num_verts,
1877    mesh->num_edges,
1878    mesh->num_faces);
1879         MVert *new_verts = CDDM_get_verts(result);
1880         MEdge *new_edges = CDDM_get_edges(result);
1881         MFace *new_faces = CDDM_get_faces(result);
1882         int i;
1883
1884         for(i = 0; i < mesh->num_verts; ++i) {
1885                 SmoothVert *vert = &mesh->verts[i];
1886                 MVert *newMV = &new_verts[vert->newIndex];
1887
1888                 DM_copy_vert_data(mesh->dm, result,
1889                                   vert->oldIndex, vert->newIndex, 1);
1890                 mesh->dm->getVert(mesh->dm, vert->oldIndex, newMV);
1891         }
1892
1893         for(i = 0; i < mesh->num_edges; ++i) {
1894                 SmoothEdge *edge = &mesh->edges[i];
1895                 MEdge *newME = &new_edges[edge->newIndex];
1896
1897                 DM_copy_edge_data(mesh->dm, result,
1898                                   edge->oldIndex, edge->newIndex, 1);
1899                 mesh->dm->getEdge(mesh->dm, edge->oldIndex, newME);
1900                 newME->v1 = edge->verts[0]->newIndex;
1901                 newME->v2 = edge->verts[1]->newIndex;
1902         }
1903
1904         for(i = 0; i < mesh->num_faces; ++i) {
1905                 SmoothFace *face = &mesh->faces[i];
1906                 MFace *newMF = &new_faces[face->newIndex];
1907
1908                 DM_copy_face_data(mesh->dm, result,
1909                                   face->oldIndex, face->newIndex, 1);
1910                 mesh->dm->getFace(mesh->dm, face->oldIndex, newMF);
1911
1912                 newMF->v1 = face->edges[0]->verts[face->flip[0]]->newIndex;
1913                 newMF->v2 = face->edges[1]->verts[face->flip[1]]->newIndex;
1914                 newMF->v3 = face->edges[2]->verts[face->flip[2]]->newIndex;
1915
1916                 if(face->edges[3]) {
1917                         newMF->v4 = face->edges[3]->verts[face->flip[3]]->newIndex;
1918                 } else {
1919                         newMF->v4 = 0;
1920                 }
1921         }
1922
1923         return result;
1924 }
1925
1926 /* returns the other vert in the given edge
1927  */
1928 static SmoothVert *other_vert(SmoothEdge *edge, SmoothVert *vert)
1929 {
1930         if(edge->verts[0] == vert) return edge->verts[1];
1931         else return edge->verts[0];
1932 }
1933
1934 /* returns the other edge in the given face that uses the given vert
1935  * returns NULL if no other edge in the given face uses the given vert
1936  * (this should never happen)
1937  */
1938 static SmoothEdge *other_edge(SmoothFace *face, SmoothVert *vert,
1939                               SmoothEdge *edge)
1940 {
1941         int i,j;
1942         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
1943                 SmoothEdge *tmp_edge = face->edges[i];
1944                 if(tmp_edge == edge) continue;
1945
1946                 for(j = 0; j < SMOOTHEDGE_NUM_VERTS; j++)
1947                         if(tmp_edge->verts[j] == vert) return tmp_edge;
1948         }
1949
1950         /* if we get to here, something's wrong (there should always be 2 edges
1951         * which use the same vert in a face)
1952         */
1953         return NULL;
1954 }
1955
1956 /* returns a face attached to the given edge which is not the given face.
1957  * returns NULL if no other faces use this edge.
1958  */
1959 static SmoothFace *other_face(SmoothEdge *edge, SmoothFace *face)
1960 {
1961         LinkNode *node;
1962
1963         for(node = edge->faces; node != NULL; node = node->next)
1964                 if(node->link != face) return node->link;
1965
1966         return NULL;
1967 }
1968
1969 #if 0
1970 /* copies source list to target, overwriting target (target is not freed)
1971  * nodes in the copy will be in the same order as in source
1972  */
1973 static void linklist_copy(LinkNode **target, LinkNode *source)
1974 {
1975         LinkNode *node = NULL;
1976         *target = NULL;
1977
1978         for(; source; source = source->next) {
1979                 if(node) {
1980                         node->next = MEM_mallocN(sizeof(*node->next), "nlink_copy");
1981                                                                                 node = node->next;
1982 } else {
1983                                                                                 node = *target = MEM_mallocN(sizeof(**target), "nlink_copy");
1984 }
1985                                                                                 node->link = source->link;
1986                                                                                 node->next = NULL;
1987 }
1988 }
1989 #endif
1990
1991                                                                                 /* appends source to target if it's not already in target */
1992                                                                                 static void linklist_append_unique(LinkNode **target, void *source) 
1993 {
1994         LinkNode *node;
1995         LinkNode *prev = NULL;
1996
1997         /* check if source value is already in the list */
1998         for(node = *target; node; prev = node, node = node->next)
1999                 if(node->link == source) return;
2000
2001         node = MEM_mallocN(sizeof(*node), "nlink");
2002         node->next = NULL;
2003         node->link = source;
2004
2005         if(prev) prev->next = node;
2006         else *target = node;
2007 }
2008
2009 /* appends elements of source which aren't already in target to target */
2010 static void linklist_append_list_unique(LinkNode **target, LinkNode *source)
2011 {
2012         for(; source; source = source->next)
2013                 linklist_append_unique(target, source->link);
2014 }
2015
2016 #if 0 /* this is no longer used, it should possibly be removed */
2017 /* prepends prepend to list - doesn't copy nodes, just joins the lists */
2018 static void linklist_prepend_linklist(LinkNode **list, LinkNode *prepend)
2019 {
2020         if(prepend) {
2021                 LinkNode *node = prepend;
2022                 while(node->next) node = node->next;
2023
2024                 node->next = *list;
2025                 *list = prepend;
2026 }
2027 }
2028 #endif
2029
2030 /* returns 1 if the linked list contains the given pointer, 0 otherwise
2031  */
2032 static int linklist_contains(LinkNode *list, void *ptr)
2033 {
2034         LinkNode *node;
2035
2036         for(node = list; node; node = node->next)
2037                 if(node->link == ptr) return 1;
2038
2039         return 0;
2040 }
2041
2042 /* returns 1 if the first linked list is a subset of the second (comparing
2043  * pointer values), 0 if not
2044  */
2045 static int linklist_subset(LinkNode *list1, LinkNode *list2)
2046 {
2047         for(; list1; list1 = list1->next)
2048                 if(!linklist_contains(list2, list1->link))
2049                         return 0;
2050
2051         return 1;
2052 }
2053
2054 #if 0
2055 /* empties the linked list
2056  * frees pointers with freefunc if freefunc is not NULL
2057  */
2058 static void linklist_empty(LinkNode **list, LinkNodeFreeFP freefunc)
2059 {
2060         BLI_linklist_free(*list, freefunc);
2061         *list = NULL;
2062 }
2063 #endif
2064
2065 /* removes the first instance of value from the linked list
2066  * frees the pointer with freefunc if freefunc is not NULL
2067  */
2068 static void linklist_remove_first(LinkNode **list, void *value,
2069                                   LinkNodeFreeFP freefunc)
2070 {
2071         LinkNode *node = *list;
2072         LinkNode *prev = NULL;
2073
2074         while(node && node->link != value) {
2075                 prev = node;
2076                 node = node->next;
2077         }
2078
2079         if(node) {
2080                 if(prev)
2081                         prev->next = node->next;
2082                 else
2083                         *list = node->next;
2084
2085                 if(freefunc)
2086                         freefunc(node->link);
2087
2088                 MEM_freeN(node);
2089         }
2090 }
2091
2092 /* removes all elements in source from target */
2093 static void linklist_remove_list(LinkNode **target, LinkNode *source,
2094                                  LinkNodeFreeFP freefunc)
2095 {
2096         for(; source; source = source->next)
2097                 linklist_remove_first(target, source->link, freefunc);
2098 }
2099
2100 #ifdef EDGESPLIT_DEBUG_0
2101 static void print_ptr(void *ptr)
2102 {
2103         printf("%p\n", ptr);
2104 }
2105
2106 static void print_edge(void *ptr)
2107 {
2108         SmoothEdge *edge = ptr;
2109         printf(" %4d", edge->newIndex);
2110 }
2111
2112 static void print_face(void *ptr)
2113 {
2114         SmoothFace *face = ptr;
2115         printf(" %4d", face->newIndex);
2116 }
2117 #endif
2118
2119 typedef struct ReplaceData {
2120         void *find;
2121         void *replace;
2122 } ReplaceData;
2123
2124 static void edge_replace_vert(void *ptr, void *userdata)
2125 {
2126         SmoothEdge *edge = ptr;
2127         SmoothVert *find = ((ReplaceData *)userdata)->find;
2128         SmoothVert *replace = ((ReplaceData *)userdata)->replace;
2129         int i;
2130
2131 #ifdef EDGESPLIT_DEBUG_3
2132         printf("replacing vert %4d with %4d in edge %4d",
2133                find->newIndex, replace->newIndex, edge->newIndex);
2134         printf(": {%4d, %4d}", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2135 #endif
2136
2137         for(i = 0; i < SMOOTHEDGE_NUM_VERTS; i++) {
2138                 if(edge->verts[i] == find) {
2139                         linklist_append_list_unique(&replace->faces, edge->faces);
2140                         linklist_remove_list(&find->faces, edge->faces, NULL);
2141
2142                         edge->verts[i] = replace;
2143                 }
2144         }
2145
2146 #ifdef EDGESPLIT_DEBUG_3
2147         printf(" -> {%4d, %4d}\n", edge->verts[0]->newIndex, edge->verts[1]->newIndex);
2148 #endif
2149 }
2150
2151 static void face_replace_vert(void *ptr, void *userdata)
2152 {
2153         SmoothFace *face = ptr;
2154         int i;
2155
2156         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++)
2157                 edge_replace_vert(face->edges[i], userdata);
2158 }
2159
2160 static void face_replace_edge(void *ptr, void *userdata)
2161 {
2162         SmoothFace *face = ptr;
2163         SmoothEdge *find = ((ReplaceData *)userdata)->find;
2164         SmoothEdge *replace = ((ReplaceData *)userdata)->replace;
2165         int i;
2166
2167 #ifdef EDGESPLIT_DEBUG_3
2168         printf("replacing edge %4d with %4d in face %4d",
2169                find->newIndex, replace->newIndex, face->newIndex);
2170         if(face->edges[3])
2171                 printf(": {%2d %2d %2d %2d}",
2172                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2173          face->edges[2]->newIndex, face->edges[3]->newIndex);
2174         else
2175                 printf(": {%2d %2d %2d}",
2176                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2177          face->edges[2]->newIndex);
2178 #endif
2179
2180         for(i = 0; i < SMOOTHFACE_MAX_EDGES && face->edges[i]; i++) {
2181                 if(face->edges[i] == find) {
2182                         linklist_remove_first(&face->edges[i]->faces, face, NULL);
2183                         BLI_linklist_prepend(&replace->faces, face);
2184                         face->edges[i] = replace;
2185                 }
2186         }
2187
2188 #ifdef EDGESPLIT_DEBUG_3
2189         if(face->edges[3])
2190                 printf(" -> {%2d %2d %2d %2d}\n",
2191                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2192          face->edges[2]->newIndex, face->edges[3]->newIndex);
2193         else
2194                 printf(" -> {%2d %2d %2d}\n",
2195                        face->edges[0]->newIndex, face->edges[1]->newIndex,
2196          face->edges[2]->newIndex);
2197 #endif
2198 }
2199
2200 static int edge_is_loose(SmoothEdge *edge)
2201 {
2202         return !(edge->faces && edge->faces->next);
2203 }
2204
2205 static int edge_is_sharp(SmoothEdge *edge, int flags,
2206                          float threshold)
2207 {
2208 #ifdef EDGESPLIT_DEBUG_1
2209         printf("edge %d: ", edge->newIndex);
2210 #endif
2211         if(edge->flag & ME_SHARP) {
2212                 /* edge can only be sharp if it has at least 2 faces */
2213                 if(!edge_is_loose(edge)) {
2214 #ifdef EDGESPLIT_DEBUG_1
2215                         printf("sharp\n");
2216 #endif
2217                         return 1;
2218                 } else {
2219                         /* edge is loose, so it can't be sharp */
2220                         edge->flag &= ~ME_SHARP;
2221                 }
2222         }
2223
2224 #ifdef EDGESPLIT_DEBUG_1
2225         printf("not sharp\n");
2226 #endif
2227         return 0;
2228 }
2229
2230 /* finds another sharp edge which uses vert, by traversing faces around the
2231  * vert until it does one of the following:
2232  * - hits a loose edge (the edge is returned)
2233  * - hits a sharp edge (the edge is returned)
2234  * - returns to the start edge (NULL is returned)
2235  */
2236 static SmoothEdge *find_other_sharp_edge(SmoothVert *vert, SmoothEdge *edge,
2237                                          LinkNode **visited_faces, float threshold, int flags)
2238 {
2239         SmoothFace *face = NULL;
2240         SmoothEdge *edge2 = NULL;
2241         /* holds the edges we've seen so we can avoid looping indefinitely */
2242         LinkNode *visited_edges = NULL;
2243 #ifdef EDGESPLIT_DEBUG_1
2244         printf("=== START === find_other_sharp_edge(edge = %4d, vert = %4d)\n",
2245                edge->newIndex, vert->newIndex);
2246 #endif
2247
2248         /* get a face on which to start */
2249         if(edge->faces) face = edge->faces->link;
2250         else return NULL;
2251
2252         /* record this edge as visited */
2253         BLI_linklist_prepend(&visited_edges, edge);
2254
2255         /* get the next edge */
2256         edge2 = other_edge(face, vert, edge);
2257
2258         /* record this face as visited */
2259         if(visited_faces)
2260                 BLI_linklist_prepend(visited_faces, face);
2261
2262         /* search until we hit a loose edge or a sharp edge or an edge we've
2263         * seen before
2264         */
2265         while(face && !edge_is_sharp(edge2, flags, threshold)
2266                      && !linklist_contains(visited_edges, edge2)) {
2267 #ifdef EDGESPLIT_DEBUG_3
2268                 printf("current face %4d; current edge %4d\n", face->newIndex,
2269                        edge2->newIndex);
2270 #endif
2271                 /* get the next face */
2272                 face = other_face(edge2, face);
2273
2274                 /* if face == NULL, edge2 is a loose edge */
2275                 if(face) {
2276                         /* record this face as visited */
2277                         if(visited_faces)
2278                                 BLI_linklist_prepend(visited_faces, face);
2279
2280                         /* record this edge as visited */
2281                         BLI_linklist_prepend(&visited_edges, edge2);
2282
2283                         /* get the next edge */
2284                         edge2 = other_edge(face, vert, edge2);
2285 #ifdef EDGESPLIT_DEBUG_3
2286                         printf("next face %4d; next edge %4d\n",
2287                                face->newIndex, edge2->newIndex);
2288                 } else {
2289                         printf("loose edge: %4d\n", edge2->newIndex);
2290 #endif
2291                 }
2292                      }
2293
2294                      /* either we came back to the start edge or we found a sharp/loose edge */
2295                      if(linklist_contains(visited_edges, edge2))
2296                              /* we came back to the start edge */
2297                              edge2 = NULL;
2298
2299                      BLI_linklist_free(visited_edges, NULL);
2300
2301 #ifdef EDGESPLIT_DEBUG_1
2302                      printf("=== END === find_other_sharp_edge(edge = %4d, vert = %4d), "
2303                                      "returning edge %d\n",
2304          edge->newIndex, vert->newIndex, edge2 ? edge2->newIndex : -1);
2305 #endif
2306                      return edge2;
2307 }
2308
2309 static void split_single_vert(SmoothVert *vert, SmoothFace *face,
2310                               SmoothMesh *mesh)
2311 {
2312         SmoothVert *copy_vert;
2313         ReplaceData repdata;
2314
2315         copy_vert = smoothvert_copy(vert, mesh);
2316
2317         repdata.find = vert;
2318         repdata.replace = copy_vert;
2319         face_replace_vert(face, &repdata);
2320 }
2321
2322 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh);
2323
2324 static void propagate_split(SmoothEdge *edge, SmoothVert *vert,
2325                             SmoothMesh *mesh)
2326 {
2327         SmoothEdge *edge2;
2328         LinkNode *visited_faces = NULL;
2329 #ifdef EDGESPLIT_DEBUG_1
2330         printf("=== START === propagate_split(edge = %4d, vert = %4d)\n",
2331                edge->newIndex, vert->newIndex);
2332 #endif
2333
2334         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2335                                       mesh->threshold, mesh->flags);
2336
2337         if(!edge2) {
2338                 /* didn't find a sharp or loose edge, so we've hit a dead end */
2339         } else if(!edge_is_loose(edge2)) {
2340                 /* edge2 is not loose, so it must be sharp */
2341                 if(edge_is_loose(edge)) {
2342                         /* edge is loose, so we can split edge2 at this vert */
2343                         split_edge(edge2, vert, mesh);
2344                 } else if(edge_is_sharp(edge, mesh->flags, mesh->threshold)) {
2345                         /* both edges are sharp, so we can split the pair at vert */
2346                         split_edge(edge, vert, mesh);
2347                 } else {
2348                         /* edge is not sharp, so try to split edge2 at its other vert */
2349                         split_edge(edge2, other_vert(edge2, vert), mesh);
2350                 }
2351         } else { /* edge2 is loose */
2352                 if(edge_is_loose(edge)) {
2353                         SmoothVert *vert2;
2354                         ReplaceData repdata;
2355
2356                         /* can't split edge, what should we do with vert? */
2357                         if(linklist_subset(vert->faces, visited_faces)) {
2358                                 /* vert has only one fan of faces attached; don't split it */
2359                         } else {
2360                                 /* vert has more than one fan of faces attached; split it */
2361                                 vert2 = smoothvert_copy(vert, mesh);
2362
2363                                 /* replace vert with its copy in visited_faces */
2364                                 repdata.find = vert;
2365                                 repdata.replace = vert2;
2366                                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2367                         }
2368                 } else {
2369                         /* edge is not loose, so it must be sharp; split it */
2370                         split_edge(edge, vert, mesh);
2371                 }
2372         }
2373
2374         BLI_linklist_free(visited_faces, NULL);
2375 #ifdef EDGESPLIT_DEBUG_1
2376         printf("=== END === propagate_split(edge = %4d, vert = %4d)\n",
2377                edge->newIndex, vert->newIndex);
2378 #endif
2379 }
2380
2381 static void split_edge(SmoothEdge *edge, SmoothVert *vert, SmoothMesh *mesh)
2382 {
2383         SmoothEdge *edge2;
2384         SmoothVert *vert2;
2385         ReplaceData repdata;
2386         /* the list of faces traversed while looking for a sharp edge */
2387         LinkNode *visited_faces = NULL;
2388 #ifdef EDGESPLIT_DEBUG_1
2389         printf("=== START === split_edge(edge = %4d, vert = %4d)\n",
2390                edge->newIndex, vert->newIndex);
2391 #endif
2392
2393         edge2 = find_other_sharp_edge(vert, edge, &visited_faces,
2394                                       mesh->threshold, mesh->flags);
2395
2396         if(!edge2) {
2397                 /* didn't find a sharp or loose edge, so try the other vert */
2398                 vert2 = other_vert(edge, vert);
2399                 propagate_split(edge, vert2, mesh);
2400         } else if(!edge_is_loose(edge2)) {
2401                 /* edge2 is not loose, so it must be sharp */
2402                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2403                 SmoothEdge *copy_edge2 = smoothedge_copy(edge2, mesh);
2404                 SmoothVert *vert2;
2405
2406                 /* replace edge with its copy in visited_faces */
2407                 repdata.find = edge;
2408                 repdata.replace = copy_edge;
2409                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2410
2411                 /* replace edge2 with its copy in visited_faces */
2412                 repdata.find = edge2;
2413                 repdata.replace = copy_edge2;
2414                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2415
2416                 vert2 = smoothvert_copy(vert, mesh);
2417
2418                 /* replace vert with its copy in visited_faces (must be done after
2419                 * edge replacement so edges have correct vertices)
2420                 */
2421                 repdata.find = vert;
2422                 repdata.replace = vert2;
2423                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2424
2425                 /* all copying and replacing is done; the mesh should be consistent.
2426                 * now propagate the split to the vertices at either end
2427                 */
2428                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2429                 propagate_split(copy_edge2, other_vert(copy_edge2, vert2), mesh);
2430
2431                 if(smoothedge_has_vert(edge, vert))
2432                         propagate_split(edge, vert, mesh);
2433         } else {
2434                 /* edge2 is loose */
2435                 SmoothEdge *copy_edge = smoothedge_copy(edge, mesh);
2436                 SmoothVert *vert2;
2437
2438                 /* replace edge with its copy in visited_faces */
2439                 repdata.find = edge;
2440                 repdata.replace = copy_edge;
2441                 BLI_linklist_apply(visited_faces, face_replace_edge, &repdata);
2442
2443                 vert2 = smoothvert_copy(vert, mesh);
2444
2445                 /* replace vert with its copy in visited_faces (must be done after
2446                 * edge replacement so edges have correct vertices)
2447                 */
2448                 repdata.find = vert;
2449                 repdata.replace = vert2;
2450                 BLI_linklist_apply(visited_faces, face_replace_vert, &repdata);
2451
2452                 /* copying and replacing is done; the mesh should be consistent.
2453                 * now propagate the split to the vertex at the other end
2454                 */
2455                 propagate_split(copy_edge, other_vert(copy_edge, vert2), mesh);
2456
2457                 if(smoothedge_has_vert(edge, vert))
2458                         propagate_split(edge, vert, mesh);
2459         }
2460
2461         BLI_linklist_free(visited_faces, NULL);
2462 #ifdef EDGESPLIT_DEBUG_1
2463         printf("=== END === split_edge(edge = %4d, vert = %4d)\n",
2464                edge->newIndex, vert->newIndex);
2465 #endif
2466 }
2467
2468 static void tag_and_count_extra_edges(SmoothMesh *mesh, float split_angle,
2469                                       int flags, int *extra_edges)
2470 {
2471         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2472         /* FIXME not sure if this always works */
2473         /* 0.00001 added for floating-point rounding */
2474         float threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2475         int i;
2476
2477         *extra_edges = 0;
2478
2479         /* loop through edges, counting potential new ones */
2480         for(i = 0; i < mesh->num_edges; i++) {
2481                 SmoothEdge *edge = &mesh->edges[i];
2482                 int sharp = 0;
2483
2484                 /* treat all non-manifold edges (3 or more faces) as sharp */
2485                 if(edge->faces && edge->faces->next && edge->faces->next->next) {
2486                         LinkNode *node;
2487
2488                         /* this edge is sharp */
2489                         sharp = 1;
2490
2491                         /* add an extra edge for every face beyond the first */
2492                         *extra_edges += 2;
2493                         for(node = edge->faces->next->next->next; node; node = node->next)
2494                                 (*extra_edges)++;
2495                 } else if((flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG))
2496                                          && !edge_is_loose(edge)) {
2497                         /* (the edge can only be sharp if we're checking angle or flag,
2498                         * and it has at least 2 faces) */
2499
2500                                                  /* if we're checking the sharp flag and it's set, good */
2501                                                  if((flags & MOD_EDGESPLIT_FROMFLAG) && (edge->flag & ME_SHARP)) {
2502                                                          /* this edge is sharp */
2503                                                          sharp = 1;
2504
2505                                                          (*extra_edges)++;
2506                                                  } else if(flags & MOD_EDGESPLIT_FROMANGLE) {
2507                                                          /* we know the edge has 2 faces, so check the angle */
2508                                                          SmoothFace *face1 = edge->faces->link;
2509                                                          SmoothFace *face2 = edge->faces->next->link;
2510                                                          float edge_angle_cos = MTC_dot3Float(face1->normal,
2511                                                                          face2->normal);
2512
2513                                                          if(edge_angle_cos < threshold) {
2514                                                                  /* this edge is sharp */
2515                                                                  sharp = 1;
2516
2517                                                                  (*extra_edges)++;
2518                                                          }
2519                                                  }
2520                                          }
2521
2522                                          /* set/clear sharp flag appropriately */
2523                                          if(sharp) edge->flag |= ME_SHARP;
2524                                          else edge->flag &= ~ME_SHARP;
2525         }
2526 }
2527
2528 static void split_sharp_edges(SmoothMesh *mesh, float split_angle, int flags)
2529 {
2530         int i;
2531         /* if normal1 dot normal2 < threshold, angle is greater, so split */
2532         /* FIXME not sure if this always works */
2533         /* 0.00001 added for floating-point rounding */
2534         mesh->threshold = cos((split_angle + 0.00001) * M_PI / 180.0);
2535         mesh->flags = flags;
2536
2537         /* loop through edges, splitting sharp ones */
2538         /* can't use an iterator here, because we'll be adding edges */
2539         for(i = 0; i < mesh->num_edges; i++) {
2540                 SmoothEdge *edge = &mesh->edges[i];
2541
2542                 if(edge_is_sharp(edge, flags, mesh->threshold))
2543                         split_edge(edge, edge->verts[0], mesh);
2544         }
2545
2546 }
2547
2548 static int count_bridge_verts(SmoothMesh *mesh)
2549 {
2550         int i, j, count = 0;
2551
2552         for(i = 0; i < mesh->num_faces; i++) {
2553                 SmoothFace *face = &mesh->faces[i];
2554
2555                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2556                         SmoothEdge *edge = face->edges[j];
2557                         SmoothEdge *next_edge;
2558                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2559                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2560
2561                         /* wrap next around if at last edge */
2562                         if(!face->edges[next]) next = 0;
2563
2564                         next_edge = face->edges[next];
2565
2566                         /* if there are other faces sharing this vertex but not
2567                         * these edges, the vertex will be split, so count it
2568                         */
2569                         /* vert has to have at least one face (this one), so faces != 0 */
2570                         if(!edge->faces->next && !next_edge->faces->next
2571                                                  && vert->faces->next) {
2572                                 count++;
2573                                                  }
2574                 }
2575         }
2576
2577         /* each bridge vert will be counted once per face that uses it,
2578         * so count is too high, but it's ok for now
2579         */
2580         return count;
2581 }
2582
2583 static void split_bridge_verts(SmoothMesh *mesh)
2584 {
2585         int i,j;
2586
2587         for(i = 0; i < mesh->num_faces; i++) {
2588                 SmoothFace *face = &mesh->faces[i];
2589
2590                 for(j = 0; j < SMOOTHFACE_MAX_EDGES && face->edges[j]; j++) {
2591                         SmoothEdge *edge = face->edges[j];
2592                         SmoothEdge *next_edge;
2593                         SmoothVert *vert = edge->verts[1 - face->flip[j]];
2594                         int next = (j + 1) % SMOOTHFACE_MAX_EDGES;
2595
2596                         /* wrap next around if at last edge */
2597                         if(!face->edges[next]) next = 0;
2598
2599                         next_edge = face->edges[next];
2600
2601                         /* if there are other faces sharing this vertex but not
2602                         * these edges, split the vertex
2603                         */
2604                         /* vert has to have at least one face (this one), so faces != 0 */
2605                         if(!edge->faces->next && !next_edge->faces->next
2606                                                  && vert->faces->next)
2607                                 /* FIXME this needs to find all faces that share edges with
2608                                 * this one and split off together
2609                                 */
2610                                 split_single_vert(vert, face, mesh);
2611                 }
2612         }
2613 }
2614
2615 static DerivedMesh *edgesplitModifier_do(EdgeSplitModifierData *emd,
2616                                          Object *ob, DerivedMesh *dm)
2617 {
2618         SmoothMesh *mesh;
2619         DerivedMesh *result;
2620         int max_verts, max_edges;
2621
2622         if(!(emd->flags & (MOD_EDGESPLIT_FROMANGLE | MOD_EDGESPLIT_FROMFLAG)))
2623                 return dm;
2624
2625         /* 1. make smoothmesh with initial number of elements */
2626         mesh = smoothmesh_from_derivedmesh(dm);
2627
2628         /* 2. count max number of elements to add */
2629         tag_and_count_extra_edges(mesh, emd->split_angle, emd->flags, &max_edges);
2630         max_verts = max_edges * 2 + mesh->max_verts;
2631         max_verts += count_bridge_verts(mesh);
2632         max_edges += mesh->max_edges;
2633
2634         /* 3. reallocate smoothmesh arrays & copy elements across */
2635         /* 4. remap copied elements' pointers to point into the new arrays */
2636         smoothmesh_resize_verts(mesh, max_verts);
2637         smoothmesh_resize_edges(mesh, max_edges);
2638
2639 #ifdef EDGESPLIT_DEBUG_1
2640         printf("********** Pre-split **********\n");
2641         smoothmesh_print(mesh);
2642 #endif
2643
2644         split_sharp_edges(mesh, emd->split_angle, emd->flags);
2645 #ifdef EDGESPLIT_DEBUG_1
2646         printf("********** Post-edge-split **********\n");
2647         smoothmesh_print(mesh);
2648 #endif
2649
2650         split_bridge_verts(mesh);
2651
2652 #ifdef EDGESPLIT_DEBUG_1
2653         printf("********** Post-vert-split **********\n");
2654         smoothmesh_print(mesh);
2655 #endif
2656
2657 #ifdef EDGESPLIT_DEBUG_0
2658         printf("Edgesplit: Estimated %d verts & %d edges, "
2659                         "found %d verts & %d edges\n", max_verts, max_edges,
2660    mesh->num_verts, mesh->num_edges);
2661 #endif
2662
2663         result = CDDM_from_smoothmesh(mesh);
2664         smoothmesh_free(mesh);
2665
2666         return result;
2667 }
2668
2669 static DerivedMesh *edgesplitModifier_applyModifier(
2670                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2671   int useRenderParams, int isFinalCalc)
2672 {
2673         DerivedMesh *result;
2674         EdgeSplitModifierData *emd = (EdgeSplitModifierData*) md;
2675
2676         result = edgesplitModifier_do(emd, ob, derivedData);
2677
2678         if(result != derivedData)
2679                 CDDM_calc_normals(result);
2680
2681         return result;
2682 }
2683
2684 static DerivedMesh *edgesplitModifier_applyModifierEM(
2685                 ModifierData *md, Object *ob, EditMesh *editData,
2686   DerivedMesh *derivedData)
2687 {
2688         return edgesplitModifier_applyModifier(md, ob, derivedData, 0, 1);
2689 }
2690
2691 /* Bevel */
2692
2693 static void bevelModifier_initData(ModifierData *md)
2694 {
2695         BevelModifierData *bmd = (BevelModifierData*) md;
2696
2697         bmd->value = 0.1f;
2698         bmd->res = 1;
2699         bmd->flags = 0;
2700         bmd->val_flags = 0;
2701         bmd->lim_flags = 0;
2702         bmd->e_flags = 0;
2703         bmd->bevel_angle = 30;
2704         bmd->defgrp_name[0] = '\0';
2705 }
2706
2707 static void bevelModifier_copyData(ModifierData *md, ModifierData *target)
2708 {
2709         BevelModifierData *bmd = (BevelModifierData*) md;
2710         BevelModifierData *tbmd = (BevelModifierData*) target;
2711
2712         tbmd->value = bmd->value;
2713         tbmd->res = bmd->res;
2714         tbmd->flags = bmd->flags;
2715         tbmd->val_flags = bmd->val_flags;
2716         tbmd->lim_flags = bmd->lim_flags;
2717         tbmd->e_flags = bmd->e_flags;
2718         tbmd->bevel_angle = bmd->bevel_angle;
2719         strncpy(tbmd->defgrp_name, bmd->defgrp_name, 32);
2720 }
2721
2722 CustomDataMask bevelModifier_requiredDataMask(ModifierData *md)
2723 {
2724         BevelModifierData *bmd = (BevelModifierData *)md;
2725         CustomDataMask dataMask = 0;
2726
2727         /* ask for vertexgroups if we need them */
2728         if(bmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2729
2730         return dataMask;
2731 }
2732
2733 static DerivedMesh *bevelModifier_applyModifier(
2734                 ModifierData *md, Object *ob, DerivedMesh *derivedData,
2735   int useRenderParams, int isFinalCalc)
2736 {
2737         DerivedMesh *result;
2738         BME_Mesh *bm;
2739
2740         /*bDeformGroup *def;*/
2741         int /*i,*/ options, defgrp_index = -1;
2742         BevelModifierData *bmd = (BevelModifierData*) md;
2743
2744         options = bmd->flags|bmd->val_flags|bmd->lim_flags|bmd->e_flags;
2745
2746         //~ if ((options & BME_BEVEL_VWEIGHT) && bmd->defgrp_name[0]) {
2747                 //~ for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
2748                         //~ if (!strcmp(def->name, bmd->defgrp_name)) {
2749                                 //~ defgrp_index = i;
2750                                 //~ break;
2751                         //~ }
2752                 //~ }
2753                 //~ if (defgrp_index < 0) {
2754                         //~ options &= ~BME_BEVEL_VWEIGHT;
2755                 //~ }
2756         //~ }
2757
2758         bm = BME_derivedmesh_to_bmesh(derivedData);
2759         BME_bevel(bm,bmd->value,bmd->res,options,defgrp_index,bmd->bevel_angle,NULL);
2760         result = BME_bmesh_to_derivedmesh(bm,derivedData);
2761         BME_free_mesh(bm);
2762
2763         CDDM_calc_normals(result);
2764
2765         return result;
2766 }
2767
2768 static DerivedMesh *bevelModifier_applyModifierEM(
2769                 ModifierData *md, Object *ob, EditMesh *editData,
2770   DerivedMesh *derivedData)
2771 {
2772         return bevelModifier_applyModifier(md, ob, derivedData, 0, 1);
2773 }
2774
2775 /* Displace */
2776
2777 static void displaceModifier_initData(ModifierData *md)
2778 {
2779         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2780
2781         dmd->texture = NULL;
2782         dmd->strength = 1;
2783         dmd->direction = MOD_DISP_DIR_NOR;
2784         dmd->midlevel = 0.5;
2785 }
2786
2787 static void displaceModifier_copyData(ModifierData *md, ModifierData *target)
2788 {
2789         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2790         DisplaceModifierData *tdmd = (DisplaceModifierData*) target;
2791
2792         tdmd->texture = dmd->texture;
2793         tdmd->strength = dmd->strength;
2794         tdmd->direction = dmd->direction;
2795         strncpy(tdmd->defgrp_name, dmd->defgrp_name, 32);
2796         tdmd->midlevel = dmd->midlevel;
2797         tdmd->texmapping = dmd->texmapping;
2798         tdmd->map_object = dmd->map_object;
2799         strncpy(tdmd->uvlayer_name, dmd->uvlayer_name, 32);
2800 }
2801
2802 CustomDataMask displaceModifier_requiredDataMask(ModifierData *md)
2803 {
2804         DisplaceModifierData *dmd = (DisplaceModifierData *)md;
2805         CustomDataMask dataMask = 0;
2806
2807         /* ask for vertexgroups if we need them */
2808         if(dmd->defgrp_name[0]) dataMask |= (1 << CD_MDEFORMVERT);
2809
2810         /* ask for UV coordinates if we need them */
2811         if(dmd->texmapping == MOD_DISP_MAP_UV) dataMask |= (1 << CD_MTFACE);
2812
2813         return dataMask;
2814 }
2815
2816 static void displaceModifier_foreachObjectLink(ModifierData *md, Object *ob,
2817                                                ObjectWalkFunc walk, void *userData)
2818 {
2819         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2820
2821         walk(userData, ob, &dmd->map_object);
2822 }
2823
2824 static void displaceModifier_foreachIDLink(ModifierData *md, Object *ob,
2825                                            IDWalkFunc walk, void *userData)
2826 {
2827         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2828
2829         walk(userData, ob, (ID **)&dmd->texture);
2830
2831         displaceModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
2832 }
2833
2834 static int displaceModifier_isDisabled(ModifierData *md)
2835 {
2836         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2837
2838         return !dmd->texture;
2839 }
2840
2841 static void displaceModifier_updateDepgraph(
2842                                             ModifierData *md, DagForest *forest,
2843          Object *ob, DagNode *obNode)
2844 {
2845         DisplaceModifierData *dmd = (DisplaceModifierData*) md;
2846
2847         if(dmd->map_object) {
2848                 DagNode *curNode = dag_get_node(forest, dmd->map_object);
2849
2850                 dag_add_relation(forest, curNode, obNode,
2851                                  DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier");
2852         }
2853 }
2854
2855 static void validate_layer_name(const CustomData *data, int type, char *name)
2856 {
2857         int index = -1;
2858
2859         /* if a layer name was given, try to find that layer */
2860         if(name[0])
2861                 index = CustomData_get_named_layer_index(data, CD_MTFACE, name);
2862
2863         if(index < 0) {
2864                 /* either no layer was specified, or the layer we want has been
2865                 * deleted, so assign the active layer to name
2866                 */
2867                 index = CustomData_get_active_layer_index(data, CD_MTFACE);
2868                 strcpy(name, data->layers[index].name);
2869         }
2870 }
2871
2872 static void get_texture_coords(DisplaceModifierData *dmd, Object *ob,
2873                                DerivedMesh *dm,
2874           float (*co)[3], float (*texco)[3],
2875                   int numVerts)
2876 {
2877         int i;
2878         int texmapping = dmd->texmapping;
2879
2880         if(texmapping == MOD_DISP_MAP_OBJECT) {
2881                 if(dmd->map_object)
2882                         Mat4Invert(dmd->map_object->imat, dmd->map_object->obmat);
2883                 else /* if there is no map object, default to local */
2884                         texmapping = MOD_DISP_MAP_LOCAL;
2885         }
2886
2887         /* UVs need special handling, since they come from faces */
2888         if(texmapping == MOD_DISP_MAP_UV) {
2889                 if(dm->getFaceDataArray(dm, CD_MTFACE)) {
2890                         MFace *mface = dm->getFaceArray(dm);
2891                         MFace *mf;
2892                         char *done = MEM_callocN(sizeof(*done) * numVerts,
2893                                         "get_texture_coords done");
2894                         int numFaces = dm->getNumFaces(dm);
2895                         MTFace *tf;
2896
2897                         validate_layer_name(&dm->faceData, CD_MTFACE, dmd->uvlayer_name);
2898
2899                         tf = CustomData_get_layer_named(&dm->faceData, CD_MTFACE,
2900                                         dmd->uvlayer_name);
2901
2902                         /* verts are given the UV from the first face that uses them */
2903                         for(i = 0, mf = mface; i < numFaces; ++i, ++mf, ++tf) {
2904                                 if(!done[mf->v1]) {
2905                                         texco[mf->v1][0] = tf->uv[0][0];
2906                                         texco[mf->v1][1] = tf->uv[0][1];
2907                                         texco[mf->v1][2] = 0;
2908                                         done[mf->v1] = 1;
2909                                 }
2910                                 if(!done[mf->v2]) {
2911                                         texco[mf->v2][0] = tf->uv[1][0];
2912                                         texco[mf->v2][1] = tf->uv[1][1];
2913                                         texco[mf->v2][2] = 0;
2914                                         done[mf->v2] = 1;
2915                                 }
2916                                 if(!done[mf->v3]) {
2917                                         texco[mf->v3][0] = tf->uv[2][0];
2918                                         texco[mf->v3][1] = tf->uv[2][1];
2919                                         texco[mf->v3][2] = 0;
2920                                         done[mf->v3] = 1;
2921                                 }
2922                                 if(!done[mf->v4]) {
2923                                         texco[mf->v4][0] = tf->uv[3][0];
2924                                         texco[mf->v4][1] = tf->uv[3][1];
2925                                         texco[mf->v4][2] = 0;
2926                                         done[mf->v4] = 1;
2927                                 }
2928                         }
2929
2930                         /* remap UVs from [0, 1] to [-1, 1] */
2931                         for(i = 0; i < numVerts; ++i) {
2932                                 texco[i][0] = texco[i][0] * 2 - 1;
2933                                 texco[i][1] = texco[i][1] * 2 - 1;
2934                         }
2935
2936                         MEM_freeN(done);
2937                         return;
2938                 } else /* if there are no UVs, default to local */
2939                         texmapping = MOD_DISP_MAP_LOCAL;
2940         }
2941
2942         for(i = 0; i < numVerts; ++i, ++co, ++texco) {
2943                 switch(texmapping) {
2944                         case MOD_DISP_MAP_LOCAL:
2945                                 VECCOPY(*texco, *co);
2946                                 break;
2947                         case MOD_DISP_MAP_GLOBAL:
2948                                 VECCOPY(*texco, *co);
2949                                 Mat4MulVecfl(ob->obmat, *texco);
2950                                 break;
2951                         case MOD_DISP_MAP_OBJECT:
2952                                 VECCOPY(*texco, *co);
2953                                 Mat4MulVecfl(ob->obmat, *texco);
2954                                 Mat4MulVecfl(dmd->map_object->imat, *texco);
2955                                 break;
2956                 }
2957         }
2958 }
2959
2960 static void get_texture_value(Tex *texture, float *tex_co, TexResult *texres)
2961 {
2962         int result_type;
2963
2964         result_type = multitex_ext(texture, tex_co, NULL,
2965                                    NULL, 1, texres);
2966
2967         /* if the texture gave an RGB value, we assume it didn't give a valid
2968         * intensity, so calculate one (formula from do_material_tex).
2969         * if the texture didn't give an RGB value, copy the intensity across
2970         */
2971         if(result_type & TEX_RGB)
2972                 texres->tin = (0.35 * texres->tr + 0.45 * texres->tg
2973                                 + 0.2 * texres->tb);
2974         else
2975                 texres->tr = texres->tg = texres->tb = texres->tin;
2976 }
2977
2978 /* dm must be a CDDerivedMesh */
2979 static void displaceModifier_do(
2980                                 DisplaceModifierData *dmd, Object *ob,
2981     DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
2982 {
2983         int i;
2984         MVert *mvert;
2985         MDeformVert *dvert = NULL;
2986         int defgrp_index;
2987         float (*tex_co)[3];
2988
2989         if(!dmd->texture) return;
2990
2991         defgrp_index = -1;
2992
2993         if(dmd->defgrp_name[0]) {
2994                 bDeformGroup *def;
2995                 for(i = 0, def = ob->defbase.first; def; def = def->next, i++) {
2996                         if(!strcmp(def->name, dmd->defgrp_name)) {
2997                                 defgrp_index = i;
2998                                 break;
2999                         }
3000                 }
3001         }
3002
3003         mvert = CDDM_get_verts(dm);
3004         if(defgrp_index >= 0)
3005                 dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
3006
3007         tex_co = MEM_callocN(sizeof(*tex_co) * numVerts,
3008                              "displaceModifier_do tex_co");
3009         get_texture_coords(dmd, ob, dm, vertexCos, tex_co, numVerts);
3010
3011         for(i = 0; i < numVerts; ++i) {
3012                 TexResult texres;
3013                 float delta = 0, strength = dmd->strength;
3014                 MDeformWeight *def_weight = NULL;
3015
3016                 if(dvert) {
3017                         int j;
3018                         for(j = 0; j < dvert[i].totweight; ++j) {
3019                                 if(dvert[i].dw[j].def_nr == defgrp_index) {
3020                                         def_weight = &dvert[i].dw[j];
3021                                         break;
3022                                 }
3023                         }
3024                         if(!def_weight) continue;
3025                 }
3026
3027                 texres.nor = NULL;
3028                 get_texture_value(dmd->texture, tex_co[i], &texres);
3029
3030                 delta = texres.tin - dmd->midlevel;
3031
3032                 if(def_weight) strength *= def_weight->weight;
3033
3034                 delta *= strength;
3035
3036                 switch(dmd->direction) {
3037                         case MOD_DISP_DIR_X:
3038                                 vertexCos[i][0] += delta;
3039                                 break;
3040                         case MOD_DISP_DIR_Y:
3041                                 vertexCos[i][1] += delta;
3042                                 break;
3043                         case MOD_DISP_DIR_Z:
3044                                 vertexCos[i][2] += delta;
3045                                 break;
3046                         case MOD_DISP_DIR_RGB_XYZ:
3047                                 vertexCos[i][0] += (texres.tr - dmd->midlevel) * strength;
3048                                 vertexCos[i][1] += (texres.tg - dmd->midlevel) * strength;
3049                                 vertexCos[i][2] += (texres.tb - dmd->midlevel) * strength;
3050                                 break;
3051                         case MOD_DISP_DIR_NOR:
3052                                 vertexCos[i][0] += delta * mvert[i].no[0] / 32767.0f;
3053                                 vertexCos[i][1] += delta * mvert[i].no[1] / 32767.0f;
3054                                 vertexCos[i][2] += delta * mvert[i].no[2] / 32767.0f;
3055                                 break;
3056                 }
3057         }
3058
3059         MEM_freeN(tex_co);
3060 }
3061
3062 static void displaceModifier_deformVerts(
3063                                          ModifierData *md, Object *ob, DerivedMesh *derivedData,
3064       float (*vertexCos)[3], int numVerts)
3065 {
3066         DerivedMesh *dm;
3067
3068         if(derivedData) dm = CDDM_copy(derivedData);
3069         else if(ob->type==OB_MESH) dm = CDDM_from_mesh(ob->data, ob);
3070         else return;
3071
3072         CDDM_apply_vert_coords(dm, vertexCos);
3073         CDDM_calc_normals(dm);
3074
3075         displaceModifier_do((DisplaceModifierData *)md, ob, dm,
3076                              vertexCos, numVerts);
3077
3078         dm->release(dm);
3079 }
3080
3081 static void displaceModifier_deformVertsEM(
3082                                            ModifierData *md, Object *ob, EditMesh *editData,
3083         DerivedMesh *derivedData, float (*vertexCos)[3], int numVerts)
3084 {
3085         DerivedMesh *dm;
3086
3087         if(derivedData) dm = CDDM_copy(derivedData);
3088         else dm = CDDM_from_editmesh(editData, ob->data);
3089
3090         CDDM_apply_vert_coords(dm, vertexCos);
3091         CDDM_calc_normals(dm);
3092
3093         displaceModifier_do((DisplaceModifierData *)md, ob, dm,
3094                              vertexCos, numVerts);
3095
3096         dm->release(dm);
3097 }
3098
3099 /* UVProject */
3100 /* UV Project modifier: Generates UVs projected from an object
3101 */
3102
3103 static void uvprojectModifier_initData(ModifierData *md)
3104 {
3105         UVProjectModifierData *umd = (UVProjectModifierData*) md;
3106         int i;
3107
3108         for(i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
3109                 umd->projectors[i] = NULL;
3110         umd->image = NULL;
3111         umd->flags = 0;
3112         umd->num_projectors = 1;
3113         umd->aspectx = umd->aspecty = 1.0f;
3114 }
3115
3116 static void uvprojectModifier_copyData(ModifierData *md, ModifierData *target)
3117 {
3118         UVProjectModifierData *umd = (UVProjectModifierData*) md;
3119         UVProjectModifierData *tumd = (UVProjectModifierData*) target;
3120         int i;
3121
3122         for(i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
3123                 tumd->projectors[i] = umd->projectors[i];
3124         tumd->image = umd->image;
3125         tumd->flags = umd->flags;
3126         tumd->num_projectors = umd->num_projectors;
3127         tumd->aspectx = umd->aspectx;
3128         tumd->aspecty = umd->aspecty;
3129 }
3130
3131 CustomDataMask uvprojectModifier_requiredDataMask(ModifierData *md)
3132 {
3133         CustomDataMask dataMask = 0;
3134
3135         /* ask for UV coordinates */
3136         dataMask |= (1 << CD_MTFACE);
3137
3138         return dataMask;
3139 }
3140
3141 static void uvprojectModifier_foreachObjectLink(ModifierData *md, Object *ob,
3142                 ObjectWalkFunc walk, void *userData)
3143 {
3144         UVProjectModifierData *umd = (UVProjectModifierData*) md;
3145         int i;
3146
3147         for(i = 0; i < MOD_UVPROJECT_MAXPROJECTORS; ++i)
3148                 walk(userData, ob, &umd->projectors[i]);
3149 }
3150
3151 static void uvprojectModifier_foreachIDLink(ModifierData *md, Object *ob,
3152                                             IDWalkFunc walk, void *userData)
3153 {
3154         UVProjectModifierData *umd = (UVProjectModifierData*) md;
3155
3156         walk(userData, ob, (ID **)&umd->image);
3157
3158         uvprojectModifier_foreachObjectLink(md, ob, (ObjectWalkFunc)walk,
3159                                          &