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