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