code cleanup: spelling
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Genrich
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/cloth.c
27  *  \ingroup bke
28  */
29
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_cloth_types.h"
34 #include "DNA_scene_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_meshdata_types.h"
37
38 #include "BLI_utildefines.h"
39 #include "BLI_math.h"
40 #include "BLI_edgehash.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_linklist.h"
43
44 #include "BKE_cdderivedmesh.h"
45 #include "BKE_cloth.h"
46 #include "BKE_effect.h"
47 #include "BKE_global.h"
48 #include "BKE_modifier.h"
49 #include "BKE_pointcache.h"
50
51 // #include "PIL_time.h"  /* timing for debug prints */
52
53 /* Our available solvers. */
54 // 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
55 // 254 = MAX!
56 static CM_SOLVER_DEF    solvers [] =
57 {
58         { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
59                 // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
60 };
61
62 /* ********** cloth engine ******* */
63 /* Prototypes for internal functions.
64  */
65 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3]);
66 static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm );
67 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first);
68 static void cloth_update_springs( ClothModifierData *clmd );
69 static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
70 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
71
72
73 /******************************************************************************
74  *
75  * External interface called by modifier.c clothModifier functions.
76  *
77  ******************************************************************************/
78 /**
79  * cloth_init - creates a new cloth simulation.
80  *
81  * 1. create object
82  * 2. fill object with standard values or with the GUI settings if given
83  */
84 void cloth_init(ClothModifierData *clmd )
85 {       
86         /* Initialize our new data structure to reasonable values. */
87         clmd->sim_parms->gravity[0] = 0.0;
88         clmd->sim_parms->gravity[1] = 0.0;
89         clmd->sim_parms->gravity[2] = -9.81;
90         clmd->sim_parms->structural = 15.0;
91         clmd->sim_parms->shear = 15.0;
92         clmd->sim_parms->bending = 0.5;
93         clmd->sim_parms->Cdis = 5.0; 
94         clmd->sim_parms->Cvi = 1.0;
95         clmd->sim_parms->mass = 0.3f;
96         clmd->sim_parms->stepsPerFrame = 5;
97         clmd->sim_parms->flags = 0;
98         clmd->sim_parms->solver_type = 0;
99         clmd->sim_parms->preroll = 0;
100         clmd->sim_parms->maxspringlen = 10;
101         clmd->sim_parms->vgroup_mass = 0;
102         clmd->sim_parms->avg_spring_len = 0.0;
103         clmd->sim_parms->presets = 2; /* cotton as start setting */
104         clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
105         clmd->sim_parms->reset = 0;
106         clmd->sim_parms->vel_damping = 1.0f; /* 1.0 = no damping, 0.0 = fully dampened */
107         
108         clmd->coll_parms->self_friction = 5.0;
109         clmd->coll_parms->friction = 5.0;
110         clmd->coll_parms->loop_count = 2;
111         clmd->coll_parms->epsilon = 0.015f;
112         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
113         clmd->coll_parms->collision_list = NULL;
114         clmd->coll_parms->self_loop_count = 1.0;
115         clmd->coll_parms->selfepsilon = 0.75;
116         clmd->coll_parms->vgroup_selfcol = 0;
117
118         /* These defaults are copied from softbody.c's
119          * softbody_calc_forces() function.
120          */
121         clmd->sim_parms->eff_force_scale = 1000.0;
122         clmd->sim_parms->eff_wind_scale = 250.0;
123
124         // also from softbodies
125         clmd->sim_parms->maxgoal = 1.0f;
126         clmd->sim_parms->mingoal = 0.0f;
127         clmd->sim_parms->defgoal = 0.0f;
128         clmd->sim_parms->goalspring = 1.0f;
129         clmd->sim_parms->goalfrict = 0.0f;
130         clmd->sim_parms->velocity_smooth = 0.0f;
131
132         if (!clmd->sim_parms->effector_weights)
133                 clmd->sim_parms->effector_weights = BKE_add_effector_weights(NULL);
134
135         if (clmd->point_cache)
136                 clmd->point_cache->step = 1;
137 }
138
139 static BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float epsilon)
140 {
141         unsigned int i;
142         BVHTree *bvhtree;
143         Cloth *cloth;
144         ClothVertex *verts;
145         float co[12];
146
147         if (!clmd)
148                 return NULL;
149
150         cloth = clmd->clothObject;
151
152         if (!cloth)
153                 return NULL;
154         
155         verts = cloth->verts;
156         
157         // in the moment, return zero if no faces there
158         if (!cloth->numverts)
159                 return NULL;
160         
161         // create quadtree with k=26
162         bvhtree = BLI_bvhtree_new(cloth->numverts, epsilon, 4, 6);
163         
164         // fill tree
165         for (i = 0; i < cloth->numverts; i++, verts++) {
166                 copy_v3_v3(&co[0*3], verts->xold);
167                 
168                 BLI_bvhtree_insert(bvhtree, i, co, 1);
169         }
170         
171         // balance tree
172         BLI_bvhtree_balance(bvhtree);
173         
174         return bvhtree;
175 }
176
177 static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
178 {
179         unsigned int i;
180         BVHTree *bvhtree;
181         Cloth *cloth;
182         ClothVertex *verts;
183         MFace *mfaces;
184         float co[12];
185
186         if (!clmd)
187                 return NULL;
188
189         cloth = clmd->clothObject;
190
191         if (!cloth)
192                 return NULL;
193         
194         verts = cloth->verts;
195         mfaces = cloth->mfaces;
196         
197         /* in the moment, return zero if no faces there */
198         if (!cloth->numfaces)
199                 return NULL;
200
201         /* create quadtree with k=26 */
202         bvhtree = BLI_bvhtree_new(cloth->numfaces, epsilon, 4, 26);
203
204         /* fill tree */
205         for (i = 0; i < cloth->numfaces; i++, mfaces++) {
206                 copy_v3_v3(&co[0*3], verts[mfaces->v1].xold);
207                 copy_v3_v3(&co[1*3], verts[mfaces->v2].xold);
208                 copy_v3_v3(&co[2*3], verts[mfaces->v3].xold);
209
210                 if (mfaces->v4)
211                         copy_v3_v3(&co[3*3], verts[mfaces->v4].xold);
212
213                 BLI_bvhtree_insert(bvhtree, i, co, (mfaces->v4 ? 4 : 3));
214         }
215
216         /* balance tree */
217         BLI_bvhtree_balance(bvhtree);
218         
219         return bvhtree;
220 }
221
222 void bvhtree_update_from_cloth(ClothModifierData *clmd, int moving)
223 {       
224         unsigned int i = 0;
225         Cloth *cloth = clmd->clothObject;
226         BVHTree *bvhtree = cloth->bvhtree;
227         ClothVertex *verts = cloth->verts;
228         MFace *mfaces;
229         float co[12], co_moving[12];
230         int ret = 0;
231         
232         if (!bvhtree)
233                 return;
234         
235         mfaces = cloth->mfaces;
236         
237         // update vertex position in bvh tree
238         if (verts && mfaces) {
239                 for (i = 0; i < cloth->numfaces; i++, mfaces++) {
240                         copy_v3_v3(&co[0*3], verts[mfaces->v1].txold);
241                         copy_v3_v3(&co[1*3], verts[mfaces->v2].txold);
242                         copy_v3_v3(&co[2*3], verts[mfaces->v3].txold);
243                         
244                         if (mfaces->v4)
245                                 copy_v3_v3(&co[3*3], verts[mfaces->v4].txold);
246                 
247                         // copy new locations into array
248                         if (moving) {
249                                 // update moving positions
250                                 copy_v3_v3(&co_moving[0*3], verts[mfaces->v1].tx);
251                                 copy_v3_v3(&co_moving[1*3], verts[mfaces->v2].tx);
252                                 copy_v3_v3(&co_moving[2*3], verts[mfaces->v3].tx);
253                                 
254                                 if (mfaces->v4)
255                                         copy_v3_v3(&co_moving[3*3], verts[mfaces->v4].tx);
256                                 
257                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, (mfaces->v4 ? 4 : 3));
258                         }
259                         else {
260                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, (mfaces->v4 ? 4 : 3));
261                         }
262                         
263                         // check if tree is already full
264                         if (!ret)
265                                 break;
266                 }
267                 
268                 BLI_bvhtree_update_tree(bvhtree);
269         }
270 }
271
272 void bvhselftree_update_from_cloth(ClothModifierData *clmd, int moving)
273 {       
274         unsigned int i = 0;
275         Cloth *cloth = clmd->clothObject;
276         BVHTree *bvhtree = cloth->bvhselftree;
277         ClothVertex *verts = cloth->verts;
278         MFace *mfaces;
279         float co[12], co_moving[12];
280         int ret = 0;
281         
282         if (!bvhtree)
283                 return;
284         
285         mfaces = cloth->mfaces;
286
287         // update vertex position in bvh tree
288         if (verts && mfaces) {
289                 for (i = 0; i < cloth->numverts; i++, verts++) {
290                         copy_v3_v3(&co[0*3], verts->txold);
291
292                         // copy new locations into array
293                         if (moving) {
294                                 // update moving positions
295                                 copy_v3_v3(&co_moving[0*3], verts->tx);
296
297                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, 1);
298                         }
299                         else {
300                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, 1);
301                         }
302
303                         // check if tree is already full
304                         if (!ret)
305                                 break;
306                 }
307                 
308                 BLI_bvhtree_update_tree(bvhtree);
309         }
310 }
311
312 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
313 {
314         PTCacheID pid;
315         
316         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
317
318         // don't do anything as long as we're in editmode!
319         if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT)
320                 return;
321         
322         BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
323 }
324
325 static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
326 {
327         PointCache *cache;
328
329         cache= clmd->point_cache;
330
331         /* initialize simulation data if it didn't exist already */
332         if (clmd->clothObject == NULL) {
333                 if (!cloth_from_object(ob, clmd, result, framenr, 1)) {
334                         BKE_ptcache_invalidate(cache);
335                         modifier_setError(&(clmd->modifier), "Can't initialize cloth");
336                         return 0;
337                 }
338         
339                 if (clmd->clothObject == NULL) {
340                         BKE_ptcache_invalidate(cache);
341                         modifier_setError(&(clmd->modifier), "Null cloth object");
342                         return 0;
343                 }
344         
345                 implicit_set_positions(clmd);
346
347                 clmd->clothObject->last_frame= MINFRAME-1;
348         }
349
350         return 1;
351 }
352
353 static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
354 {
355         ClothVertex *verts = NULL;
356         Cloth *cloth;
357         ListBase *effectors = NULL;
358         MVert *mvert;
359         unsigned int i = 0;
360         int ret = 0;
361
362         /* simulate 1 frame forward */
363         cloth = clmd->clothObject;
364         verts = cloth->verts;
365         mvert = result->getVertArray(result);
366
367         /* force any pinned verts to their constrained location. */
368         for (i = 0; i < clmd->clothObject->numverts; i++, verts++) {
369                 /* save the previous position. */
370                 copy_v3_v3(verts->xold, verts->xconst);
371                 copy_v3_v3(verts->txold, verts->x);
372
373                 /* Get the current position. */
374                 copy_v3_v3(verts->xconst, mvert[i].co);
375                 mul_m4_v3(ob->obmat, verts->xconst);
376         }
377
378         effectors = pdInitEffectors(clmd->scene, ob, NULL, clmd->sim_parms->effector_weights);
379
380         /* Support for dynamic vertex groups, changing from frame to frame */
381         cloth_apply_vgroup ( clmd, result );
382         cloth_update_springs( clmd );
383         
384         // TIMEIT_START(cloth_step)
385
386         /* call the solver. */
387         if (solvers [clmd->sim_parms->solver_type].solver)
388                 ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);
389
390         // TIMEIT_END(cloth_step)
391
392         pdEndEffectors(&effectors);
393
394         // printf ( "%f\n", ( float ) tval() );
395         
396         return ret;
397 }
398
399 #if 0
400 static DerivedMesh *cloth_to_triangles(DerivedMesh *dm)
401 {
402         DerivedMesh *result = NULL;
403         unsigned int i = 0, j = 0;
404         unsigned int quads = 0, numfaces = dm->getNumTessFaces(dm);
405         MFace *mface = dm->getTessFaceArray(dm);
406         MFace *mface2 = NULL;
407
408         /* calc faces */
409         for (i = 0; i < numfaces; i++) {
410                 if (mface[i].v4) {
411                         quads++;
412                 }
413         }
414                 
415         result = CDDM_from_template(dm, dm->getNumVerts(dm), 0, numfaces + quads, 0, 0);
416
417         DM_copy_vert_data(dm, result, 0, 0, dm->getNumVerts(dm));
418         DM_copy_tessface_data(dm, result, 0, 0, numfaces);
419
420         DM_ensure_tessface(result);
421         mface2 = result->getTessFaceArray(result);
422
423         for (i = 0, j = numfaces; i < numfaces; i++) {
424                 // DG TODO: is this necessary?
425                 mface2[i].v1 = mface[i].v1;
426                 mface2[i].v2 = mface[i].v2;
427                 mface2[i].v3 = mface[i].v3;
428
429                 mface2[i].v4 = 0;
430                 //test_index_face(&mface2[i], &result->faceData, i, 3);
431
432                 if (mface[i].v4) {
433                         DM_copy_tessface_data(dm, result, i, j, 1);
434
435                         mface2[j].v1 = mface[i].v1;
436                         mface2[j].v2 = mface[i].v3;
437                         mface2[j].v3 = mface[i].v4;
438                         mface2[j].v4 = 0;
439                         //test_index_face(&mface2[j], &result->faceData, j, 3);
440
441                         j++;
442                 }
443         }
444
445         CDDM_calc_edges_tessface(result);
446         CDDM_tessfaces_to_faces(result); /* builds ngon faces from tess (mface) faces */
447
448         return result;
449 }
450 #endif
451
452 /************************************************
453  * clothModifier_do - main simulation function
454  ************************************************/
455 void clothModifier_do(ClothModifierData *clmd, Scene *scene, Object *ob, DerivedMesh *dm, float (*vertexCos)[3])
456 {
457         PointCache *cache;
458         PTCacheID pid;
459         float timescale;
460         int framenr, startframe, endframe;
461         int cache_result;
462
463         clmd->scene= scene;     /* nice to pass on later :) */
464         framenr= (int)scene->r.cfra;
465         cache= clmd->point_cache;
466
467         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
468         BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
469         clmd->sim_parms->timescale= timescale;
470
471         if (clmd->sim_parms->reset ||
472             (framenr == (startframe - clmd->sim_parms->preroll) && clmd->sim_parms->preroll != 0) ||
473             (clmd->clothObject && dm->getNumVerts(dm) != clmd->clothObject->numverts))
474         {
475                 clmd->sim_parms->reset = 0;
476                 cache->flag |= PTCACHE_OUTDATED;
477                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
478                 BKE_ptcache_validate(cache, 0);
479                 cache->last_exact= 0;
480                 cache->flag &= ~PTCACHE_REDO_NEEDED;
481         }
482         
483         // unused in the moment, calculated separately in implicit.c
484         clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
485
486         /* handle continuous simulation with the play button */
487         if ((clmd->sim_parms->preroll > 0) && (framenr > startframe - clmd->sim_parms->preroll) && (framenr < startframe)) {
488                 BKE_ptcache_invalidate(cache);
489
490                 /* do simulation */
491                 if (!do_init_cloth(ob, clmd, dm, framenr))
492                         return;
493
494                 do_step_cloth(ob, clmd, dm, framenr);
495                 cloth_to_object(ob, clmd, vertexCos);
496
497                 clmd->clothObject->last_frame= framenr;
498
499                 return;
500         }
501
502         /* simulation is only active during a specific period */
503         if (framenr < startframe) {
504                 BKE_ptcache_invalidate(cache);
505                 return;
506         }
507         else if (framenr > endframe) {
508                 framenr= endframe;
509         }
510
511         /* initialize simulation data if it didn't exist already */
512         if (!do_init_cloth(ob, clmd, dm, framenr))
513                 return;
514
515         if ((framenr == startframe) && (clmd->sim_parms->preroll == 0)) {
516                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
517                 do_init_cloth(ob, clmd, dm, framenr);
518                 BKE_ptcache_validate(cache, framenr);
519                 cache->flag &= ~PTCACHE_REDO_NEEDED;
520                 clmd->clothObject->last_frame= framenr;
521                 return;
522         }
523
524         /* try to read from cache */
525         cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe);
526
527         if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED) {
528                 implicit_set_positions(clmd);
529                 cloth_to_object (ob, clmd, vertexCos);
530
531                 BKE_ptcache_validate(cache, framenr);
532
533                 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED)
534                         BKE_ptcache_write(&pid, framenr);
535
536                 clmd->clothObject->last_frame= framenr;
537
538                 return;
539         }
540         else if (cache_result==PTCACHE_READ_OLD) {
541                 implicit_set_positions(clmd);
542         }
543         else if ( /*ob->id.lib ||*/ (cache->flag & PTCACHE_BAKED)) { /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */
544                 /* if baked and nothing in cache, do nothing */
545                 BKE_ptcache_invalidate(cache);
546                 return;
547         }
548
549         if (framenr!=clmd->clothObject->last_frame+1)
550                 return;
551
552         /* if on second frame, write cache for first frame */
553         if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0))
554                 BKE_ptcache_write(&pid, startframe);
555
556         clmd->sim_parms->timescale *= framenr - cache->simframe;
557
558         /* do simulation */
559         BKE_ptcache_validate(cache, framenr);
560
561         if (!do_step_cloth(ob, clmd, dm, framenr)) {
562                 BKE_ptcache_invalidate(cache);
563         }
564         else
565                 BKE_ptcache_write(&pid, framenr);
566
567         cloth_to_object (ob, clmd, vertexCos);
568         clmd->clothObject->last_frame= framenr;
569 }
570
571 /* frees all */
572 void cloth_free_modifier(ClothModifierData *clmd )
573 {
574         Cloth   *cloth = NULL;
575         
576         if ( !clmd )
577                 return;
578
579         cloth = clmd->clothObject;
580
581         
582         if ( cloth ) {
583                 // If our solver provides a free function, call it
584                 if ( solvers [clmd->sim_parms->solver_type].free ) {
585                         solvers [clmd->sim_parms->solver_type].free ( clmd );
586                 }
587
588                 // Free the verts.
589                 if ( cloth->verts != NULL )
590                         MEM_freeN ( cloth->verts );
591
592                 cloth->verts = NULL;
593                 cloth->numverts = 0;
594
595                 // Free the springs.
596                 if ( cloth->springs != NULL ) {
597                         LinkNode *search = cloth->springs;
598                         while (search) {
599                                 ClothSpring *spring = search->link;
600                                                 
601                                 MEM_freeN ( spring );
602                                 search = search->next;
603                         }
604                         BLI_linklist_free(cloth->springs, NULL);
605                 
606                         cloth->springs = NULL;
607                 }
608
609                 cloth->springs = NULL;
610                 cloth->numsprings = 0;
611
612                 // free BVH collision tree
613                 if ( cloth->bvhtree )
614                         BLI_bvhtree_free ( cloth->bvhtree );
615                 
616                 if ( cloth->bvhselftree )
617                         BLI_bvhtree_free ( cloth->bvhselftree );
618
619                 // we save our faces for collision objects
620                 if ( cloth->mfaces )
621                         MEM_freeN ( cloth->mfaces );
622                 
623                 if (cloth->edgehash)
624                         BLI_edgehash_free ( cloth->edgehash, NULL );
625                 
626                 
627                 /*
628                 if (clmd->clothObject->facemarks)
629                 MEM_freeN(clmd->clothObject->facemarks);
630                 */
631                 MEM_freeN ( cloth );
632                 clmd->clothObject = NULL;
633         }
634 }
635
636 /* frees all */
637 void cloth_free_modifier_extern(ClothModifierData *clmd )
638 {
639         Cloth   *cloth = NULL;
640         if (G.debug_value > 0)
641                 printf("cloth_free_modifier_extern\n");
642         
643         if ( !clmd )
644                 return;
645
646         cloth = clmd->clothObject;
647         
648         if ( cloth ) {
649                 if (G.debug_value > 0)
650                         printf("cloth_free_modifier_extern in\n");
651
652                 // If our solver provides a free function, call it
653                 if ( solvers [clmd->sim_parms->solver_type].free ) {
654                         solvers [clmd->sim_parms->solver_type].free ( clmd );
655                 }
656
657                 // Free the verts.
658                 if ( cloth->verts != NULL )
659                         MEM_freeN ( cloth->verts );
660
661                 cloth->verts = NULL;
662                 cloth->numverts = 0;
663
664                 // Free the springs.
665                 if ( cloth->springs != NULL ) {
666                         LinkNode *search = cloth->springs;
667                         while (search) {
668                                 ClothSpring *spring = search->link;
669
670                                 MEM_freeN ( spring );
671                                 search = search->next;
672                         }
673                         BLI_linklist_free(cloth->springs, NULL);
674
675                         cloth->springs = NULL;
676                 }
677
678                 cloth->springs = NULL;
679                 cloth->numsprings = 0;
680
681                 // free BVH collision tree
682                 if ( cloth->bvhtree )
683                         BLI_bvhtree_free ( cloth->bvhtree );
684                 
685                 if ( cloth->bvhselftree )
686                         BLI_bvhtree_free ( cloth->bvhselftree );
687
688                 // we save our faces for collision objects
689                 if ( cloth->mfaces )
690                         MEM_freeN ( cloth->mfaces );
691
692                 if (cloth->edgehash)
693                         BLI_edgehash_free ( cloth->edgehash, NULL );
694
695
696                 /*
697                 if (clmd->clothObject->facemarks)
698                 MEM_freeN(clmd->clothObject->facemarks);
699                 */
700                 MEM_freeN ( cloth );
701                 clmd->clothObject = NULL;
702         }
703 }
704
705 /******************************************************************************
706  *
707  * Internal functions.
708  *
709  ******************************************************************************/
710
711 /**
712  * cloth_to_object - copies the deformed vertices to the object.
713  *
714  **/
715 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3])
716 {
717         unsigned int    i = 0;
718         Cloth *cloth = clmd->clothObject;
719
720         if (clmd->clothObject) {
721                 /* inverse matrix is not uptodate... */
722                 invert_m4_m4(ob->imat, ob->obmat);
723
724                 for (i = 0; i < cloth->numverts; i++) {
725                         copy_v3_v3 (vertexCos[i], cloth->verts[i].x);
726                         mul_m4_v3(ob->imat, vertexCos[i]);      /* cloth is in global coords */
727                 }
728         }
729 }
730
731
732 int cloth_uses_vgroup(ClothModifierData *clmd)
733 {
734         return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || 
735                 (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) ||
736                 (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && 
737                 ((clmd->sim_parms->vgroup_mass>0) || 
738                 (clmd->sim_parms->vgroup_struct>0)||
739                 (clmd->sim_parms->vgroup_bend>0)  ||
740                 (clmd->coll_parms->vgroup_selfcol>0)));
741 }
742
743 /**
744  * cloth_apply_vgroup - applies a vertex group as specified by type
745  *
746  **/
747 /* can be optimized to do all groups in one loop */
748 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
749 {
750         int i = 0;
751         int j = 0;
752         MDeformVert *dvert = NULL;
753         Cloth *clothObj = NULL;
754         int numverts;
755         /* float goalfac = 0; */ /* UNUSED */
756         ClothVertex *verts = NULL;
757
758         if (!clmd || !dm) return;
759
760         clothObj = clmd->clothObject;
761
762         numverts = dm->getNumVerts (dm);
763
764         verts = clothObj->verts;
765         
766         if (cloth_uses_vgroup(clmd)) {
767                 for ( i = 0; i < numverts; i++, verts++ ) {
768
769                         /* Reset Goal values to standard */
770                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
771                                 verts->goal= clmd->sim_parms->defgoal;
772                         else
773                                 verts->goal= 0.0f;
774
775                         /* Reset vertex flags */
776                         verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
777                         verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
778
779                         dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
780                         if ( dvert ) {
781                                 for ( j = 0; j < dvert->totweight; j++ ) {
782                                         if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) {
783                                                 verts->goal = dvert->dw [j].weight;
784
785                                                 /* goalfac= 1.0f; */ /* UNUSED */
786                                                 
787                                                 // Kicking goal factor to simplify things...who uses that anyway?
788                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
789                                                 
790                                                 verts->goal  = powf(verts->goal, 4.0f);
791                                                 if ( verts->goal >= SOFTGOALSNAP )
792                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
793                                         }
794                                         
795                                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) {
796                                                 if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1)) {
797                                                         verts->struct_stiff = dvert->dw [j].weight;
798                                                         verts->shear_stiff = dvert->dw [j].weight;
799                                                 }
800                                                 
801                                                 if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1)) {
802                                                         verts->bend_stiff = dvert->dw [j].weight;
803                                                 }
804                                         }
805
806                                         if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
807                                                 if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) {
808                                                         if (dvert->dw [j].weight > 0.0f) {
809                                                                 verts->flags |= CLOTH_VERT_FLAG_NOSELFCOLL;
810                                                         }
811                                                 }
812                                         }
813                                 }
814                         }
815                 }
816         }
817 }
818
819 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float UNUSED(framenr), int first)
820 {
821         int i = 0;
822         MVert *mvert = NULL;
823         ClothVertex *verts = NULL;
824         float (*shapekey_rest)[3] = NULL;
825         float tnull[3] = {0, 0, 0};
826         Cloth *cloth = NULL;
827         float maxdist = 0;
828
829         // If we have a clothObject, free it. 
830         if ( clmd->clothObject != NULL ) {
831                 cloth_free_modifier ( clmd );
832                 if (G.debug_value > 0)
833                         printf("cloth_free_modifier cloth_from_object\n");
834         }
835
836         // Allocate a new cloth object.
837         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
838         if ( clmd->clothObject ) {
839                 clmd->clothObject->old_solver_type = 255;
840                 // clmd->clothObject->old_collision_type = 255;
841                 cloth = clmd->clothObject;
842                 clmd->clothObject->edgehash = NULL;
843         }
844         else if (!clmd->clothObject) {
845                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject");
846                 return 0;
847         }
848
849         // mesh input objects need DerivedMesh
850         if ( !dm )
851                 return 0;
852
853         cloth_from_mesh ( clmd, dm );
854
855         // create springs
856         clmd->clothObject->springs = NULL;
857         clmd->clothObject->numsprings = -1;
858
859         if ( clmd->sim_parms->shapekey_rest )
860                 shapekey_rest = dm->getVertDataArray ( dm, CD_CLOTH_ORCO );
861
862         mvert = dm->getVertArray (dm);
863
864         verts = clmd->clothObject->verts;
865
866         // set initial values
867         for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ ) {
868                 if (first) {
869                         copy_v3_v3(verts->x, mvert[i].co);
870
871                         mul_m4_v3(ob->obmat, verts->x);
872
873                         if ( shapekey_rest ) {
874                                 verts->xrest= shapekey_rest[i];
875                                 mul_m4_v3(ob->obmat, verts->xrest);
876                         }
877                         else
878                                 verts->xrest = verts->x;
879                 }
880                 
881                 /* no GUI interface yet */
882                 verts->mass = clmd->sim_parms->mass; 
883                 verts->impulse_count = 0;
884
885                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
886                         verts->goal= clmd->sim_parms->defgoal;
887                 else
888                         verts->goal= 0.0f;
889
890                 verts->flags = 0;
891                 copy_v3_v3 ( verts->xold, verts->x );
892                 copy_v3_v3 ( verts->xconst, verts->x );
893                 copy_v3_v3 ( verts->txold, verts->x );
894                 copy_v3_v3 ( verts->tx, verts->x );
895                 mul_v3_fl(verts->v, 0.0f);
896
897                 verts->impulse_count = 0;
898                 copy_v3_v3 ( verts->impulse, tnull );
899         }
900         
901         // apply / set vertex groups
902         // has to be happen before springs are build!
903         cloth_apply_vgroup (clmd, dm);
904
905         if ( !cloth_build_springs ( clmd, dm ) ) {
906                 cloth_free_modifier ( clmd );
907                 modifier_setError(&(clmd->modifier), "Cannot build springs");
908                 printf("cloth_free_modifier cloth_build_springs\n");
909                 return 0;
910         }
911         
912         for ( i = 0; i < dm->getNumVerts(dm); i++) {
913                 if ((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO)) {
914                         cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
915                 }
916         }
917         
918         // init our solver
919         if ( solvers [clmd->sim_parms->solver_type].init ) {
920                 solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
921         }
922         
923         if (!first)
924                 implicit_set_positions(clmd);
925
926         clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, MAX2(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel) );
927         
928         for (i = 0; i < dm->getNumVerts(dm); i++) {
929                 maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0f));
930         }
931         
932         clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist );
933
934         return 1;
935 }
936
937 static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm )
938 {
939         unsigned int numverts = dm->getNumVerts (dm);
940         unsigned int numfaces = dm->getNumTessFaces (dm);
941         MFace *mface = dm->getTessFaceArray(dm);
942         unsigned int i = 0;
943
944         /* Allocate our vertices. */
945         clmd->clothObject->numverts = numverts;
946         clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
947         if ( clmd->clothObject->verts == NULL ) {
948                 cloth_free_modifier ( clmd );
949                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
950                 printf("cloth_free_modifier clmd->clothObject->verts\n");
951                 return;
952         }
953
954         // save face information
955         clmd->clothObject->numfaces = numfaces;
956         clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
957         if ( clmd->clothObject->mfaces == NULL ) {
958                 cloth_free_modifier ( clmd );
959                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->mfaces");
960                 printf("cloth_free_modifier clmd->clothObject->mfaces\n");
961                 return;
962         }
963         for ( i = 0; i < numfaces; i++ )
964                 memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
965
966         /* Free the springs since they can't be correct if the vertices
967          * changed.
968          */
969         if ( clmd->clothObject->springs != NULL )
970                 MEM_freeN ( clmd->clothObject->springs );
971
972 }
973
974 /***************************************************************************************
975  * SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
976  ***************************************************************************************/
977
978 BLI_INLINE void spring_verts_ordered_set(ClothSpring *spring, int v0, int v1)
979 {
980         if (v0 < v1) {
981                 spring->ij = v0;
982                 spring->kl = v1;
983         }
984         else {
985                 spring->ij = v1;
986                 spring->kl = v0;
987         }
988 }
989
990 // be careful: implicit solver has to be resettet when using this one!
991 // --> only for implicit handling of this spring!
992 int cloth_add_spring(ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
993 {
994         Cloth *cloth = clmd->clothObject;
995         ClothSpring *spring = NULL;
996         
997         if (cloth) {
998                 // TODO: look if this spring is already there
999                 
1000                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1001                 
1002                 if (!spring)
1003                         return 0;
1004                 
1005                 spring->ij = indexA;
1006                 spring->kl = indexB;
1007                 spring->restlen =  restlength;
1008                 spring->type = spring_type;
1009                 spring->flags = 0;
1010                 spring->stiffness = 0;
1011                 
1012                 cloth->numsprings++;
1013         
1014                 BLI_linklist_prepend ( &cloth->springs, spring );
1015                 
1016                 return 1;
1017         }
1018         return 0;
1019 }
1020
1021 static void cloth_free_edgelist(LinkNode **edgelist, unsigned int numverts)
1022 {
1023         if (edgelist) {
1024                 unsigned int i;
1025                 for (i = 0; i < numverts; i++) {
1026                         BLI_linklist_free(edgelist[i], NULL);
1027                 }
1028
1029                 MEM_freeN(edgelist);
1030         }
1031 }
1032
1033 static void cloth_free_errorsprings(Cloth *cloth,  LinkNode **edgelist)
1034 {
1035         if ( cloth->springs != NULL ) {
1036                 LinkNode *search = cloth->springs;
1037                 while (search) {
1038                         ClothSpring *spring = search->link;
1039                                                 
1040                         MEM_freeN ( spring );
1041                         search = search->next;
1042                 }
1043                 BLI_linklist_free(cloth->springs, NULL);
1044                 
1045                 cloth->springs = NULL;
1046         }
1047
1048         cloth_free_edgelist(edgelist, cloth->numverts);
1049         
1050         if (cloth->edgehash) {
1051                 BLI_edgehash_free(cloth->edgehash, NULL);
1052                 cloth->edgehash = NULL;
1053         }
1054 }
1055
1056 /* update stiffness if vertex group values are changing from frame to frame */
1057 static void cloth_update_springs( ClothModifierData *clmd )
1058 {
1059         Cloth *cloth = clmd->clothObject;
1060         LinkNode *search = NULL;
1061
1062         search = cloth->springs;
1063         while (search) {
1064                 ClothSpring *spring = search->link;
1065
1066                 spring->stiffness = 0.0f;
1067
1068                 if (spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) {
1069                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1070                 }
1071                 else if (spring->type == CLOTH_SPRING_TYPE_SHEAR) {
1072                         spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1073                 }
1074                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
1075                         spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1076                 }
1077                 else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
1078                         /* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
1079
1080                         /* Activate / Deactivate existing springs */
1081                         if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
1082                             (cloth->verts[spring->ij].goal > ALMOST_ZERO))
1083                         {
1084                                 spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
1085                         }
1086                         else {
1087                                 spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
1088                         }
1089                 }
1090                 
1091                 search = search->next;
1092         }
1093
1094
1095 }
1096
1097 static int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
1098 {
1099         Cloth *cloth = clmd->clothObject;
1100         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1101         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
1102         unsigned int i = 0;
1103         unsigned int numverts = (unsigned int)dm->getNumVerts (dm);
1104         unsigned int numedges = (unsigned int)dm->getNumEdges (dm);
1105         unsigned int numfaces = (unsigned int)dm->getNumTessFaces (dm);
1106         MEdge *medge = dm->getEdgeArray (dm);
1107         MFace *mface = dm->getTessFaceArray (dm);
1108         int index2 = 0; // our second vertex index
1109         LinkNode **edgelist = NULL;
1110         EdgeHash *edgehash = NULL;
1111         LinkNode *search = NULL, *search2 = NULL;
1112         
1113         // error handling
1114         if ( numedges==0 )
1115                 return 0;
1116
1117         /* NOTE: handling ownership of springs and edgehash is quite sloppy
1118          * currently they are never initialized but assert just to be sure */
1119         BLI_assert(cloth->springs == NULL);
1120         BLI_assert(cloth->edgehash == NULL);
1121
1122         cloth->springs = NULL;
1123         cloth->edgehash = NULL;
1124
1125         edgelist = MEM_callocN ( sizeof (LinkNode *) * numverts, "cloth_edgelist_alloc" );
1126         
1127         if (!edgelist)
1128                 return 0;
1129
1130         // structural springs
1131         for ( i = 0; i < numedges; i++ ) {
1132                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1133
1134                 if ( spring ) {
1135                         spring_verts_ordered_set(spring, medge[i].v1, medge[i].v2);
1136                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1137                         clmd->sim_parms->avg_spring_len += spring->restlen;
1138                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1139                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1140                         cloth->verts[spring->ij].spring_count++;
1141                         cloth->verts[spring->kl].spring_count++;
1142                         spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1143                         spring->flags = 0;
1144                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1145                         struct_springs++;
1146                         
1147                         BLI_linklist_prepend ( &cloth->springs, spring );
1148                 }
1149                 else {
1150                         cloth_free_errorsprings(cloth, edgelist);
1151                         return 0;
1152                 }
1153         }
1154
1155         if (struct_springs > 0)
1156                 clmd->sim_parms->avg_spring_len /= struct_springs;
1157         
1158         for (i = 0; i < numverts; i++) {
1159                 cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1160         }
1161
1162         // shear springs
1163         for ( i = 0; i < numfaces; i++ ) {
1164                 // triangle faces already have shear springs due to structural geometry
1165                 if ( !mface[i].v4 )
1166                         continue;
1167
1168                 spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1169                 
1170                 if (!spring) {
1171                         cloth_free_errorsprings(cloth, edgelist);
1172                         return 0;
1173                 }
1174
1175                 spring_verts_ordered_set(spring, mface[i].v1, mface[i].v3);
1176                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1177                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1178                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1179
1180                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1181                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1182                 shear_springs++;
1183
1184                 BLI_linklist_prepend ( &cloth->springs, spring );
1185
1186                 
1187                 // if ( mface[i].v4 ) --> Quad face
1188                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1189                 
1190                 if (!spring) {
1191                         cloth_free_errorsprings(cloth, edgelist);
1192                         return 0;
1193                 }
1194
1195                 spring_verts_ordered_set(spring, mface[i].v2, mface[i].v4);
1196                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1197                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1198                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1199
1200                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1201                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1202                 shear_springs++;
1203
1204                 BLI_linklist_prepend ( &cloth->springs, spring );
1205         }
1206
1207         edgehash = BLI_edgehash_new_ex(__func__, numedges);
1208         cloth->edgehash = edgehash;
1209
1210         if (numfaces) {
1211                 // bending springs
1212                 search2 = cloth->springs;
1213                 for ( i = struct_springs; i < struct_springs+shear_springs; i++ ) {
1214                         if ( !search2 )
1215                                 break;
1216
1217                         tspring2 = search2->link;
1218                         search = edgelist[tspring2->kl];
1219                         while ( search ) {
1220                                 tspring = search->link;
1221                                 index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
1222
1223                                 // check for existing spring
1224                                 // check also if startpoint is equal to endpoint
1225                                 if ((index2 != tspring2->ij) &&
1226                                     !BLI_edgehash_haskey(edgehash, tspring2->ij, index2))
1227                                 {
1228                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1229
1230                                         if (!spring) {
1231                                                 cloth_free_errorsprings(cloth, edgelist);
1232                                                 return 0;
1233                                         }
1234
1235                                         spring_verts_ordered_set(spring, tspring2->ij, index2);
1236                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1237                                         spring->type = CLOTH_SPRING_TYPE_BENDING;
1238                                         spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1239                                         BLI_edgehash_insert(edgehash, spring->ij, spring->kl, NULL);
1240                                         bend_springs++;
1241
1242                                         BLI_linklist_prepend ( &cloth->springs, spring );
1243                                 }
1244                                 search = search->next;
1245                         }
1246                         search2 = search2->next;
1247                 }
1248         }
1249         else if (struct_springs > 2) {
1250                 /* bending springs for hair strands */
1251                 /* The current algorightm only goes through the edges in order of the mesh edges list   */
1252                 /* and makes springs between the outer vert of edges sharing a vertice. This works just */
1253                 /* fine for hair, but not for user generated string meshes. This could/should be later  */
1254                 /* extended to work with non-ordered edges so that it can be used for general "rope             */
1255                 /* dynamics" without the need for the vertices or edges to be ordered through the length*/
1256                 /* of the strands. -jahka */
1257                 search = cloth->springs;
1258                 search2 = search->next;
1259                 while (search && search2) {
1260                         tspring = search->link;
1261                         tspring2 = search2->link;
1262
1263                         if (tspring->ij == tspring2->kl) {
1264                                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1265                                 
1266                                 if (!spring) {
1267                                         cloth_free_errorsprings(cloth, edgelist);
1268                                         return 0;
1269                                 }
1270
1271                                 spring->ij = tspring2->ij;
1272                                 spring->kl = tspring->kl;
1273                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1274                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1275                                 spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1276                                 bend_springs++;
1277
1278                                 BLI_linklist_prepend ( &cloth->springs, spring );
1279                         }
1280                         
1281                         search = search->next;
1282                         search2 = search2->next;
1283                 }
1284         }
1285         
1286         /* note: the edges may already exist so run reinsert */
1287
1288         /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
1289         for (i = 0; i < numedges; i++) { /* struct springs */
1290                 BLI_edgehash_reinsert(edgehash, medge[i].v1, medge[i].v2, NULL);
1291         }
1292
1293         for (i = 0; i < numfaces; i++) { /* edge springs */
1294                 if (mface[i].v4) {
1295                         BLI_edgehash_reinsert(edgehash, mface[i].v1, mface[i].v3, NULL);
1296                         
1297                         BLI_edgehash_reinsert(edgehash, mface[i].v2, mface[i].v4, NULL);
1298                 }
1299         }
1300         
1301         
1302         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1303         
1304         cloth_free_edgelist(edgelist, numverts);
1305
1306 #if 0
1307         if (G.debug_value > 0)
1308                 printf("avg_len: %f\n", clmd->sim_parms->avg_spring_len);
1309 #endif
1310
1311         return 1;
1312
1313 } /* cloth_build_springs */
1314 /***************************************************************************************
1315  * SPRING NETWORK BUILDING IMPLEMENTATION END
1316  ***************************************************************************************/
1317