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