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