Bugfix for wrong initial cloth settings pretending to be cotton
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*  cloth.c
2 *
3 *
4 * ***** BEGIN GPL/BL DUAL 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. The Blender
10 * Foundation also sells licenses for use in proprietary software under
11 * the Blender License.  See http://www.blender.org/BL/ for information
12 * about this.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22 *
23 * The Original Code is Copyright (C) Blender Foundation
24 * All rights reserved.
25 *
26 * Contributor(s): Daniel Genrich
27 *
28 * ***** END GPL/BL DUAL LICENSE BLOCK *****
29 */
30
31
32 #include <math.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 /* types */
39 #include "DNA_curve_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_object_force.h"
42 #include "DNA_cloth_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_mesh_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_lattice_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_modifier_types.h"
49
50 #include "BLI_blenlib.h"
51 #include "BLI_arithb.h"
52 #include "BLI_editVert.h"
53 #include "BLI_edgehash.h"
54 #include "BLI_linklist.h"
55
56 #include "BKE_curve.h"
57 #include "BKE_deform.h"
58 #include "BKE_DerivedMesh.h"
59 #include "BKE_cdderivedmesh.h"
60 #include "BKE_displist.h"
61 #include "BKE_effect.h"
62 #include "BKE_global.h"
63 #include "BKE_key.h"
64 #include "BKE_mesh.h"
65 #include "BKE_object.h"
66 #include "BKE_cloth.h"
67 #include "BKE_modifier.h"
68 #include "BKE_utildefines.h"
69 #include "BKE_DerivedMesh.h"
70 #include "BIF_editdeform.h"
71 #include "BIF_editkey.h"
72 #include "DNA_screen_types.h"
73 #include "BSE_headerbuttons.h"
74 #include "BIF_screen.h"
75 #include "BIF_space.h"
76 #include "mydevice.h"
77
78 #include "BKE_pointcache.h"
79
80 #ifdef _WIN32
81 void tstart ( void )
82 {}
83 void tend ( void )
84 {
85 }
86 double tval()
87 {
88         return 0;
89 }
90 #else
91 #include <sys/time.h>
92                          static struct timeval _tstart, _tend;
93          static struct timezone tz;
94          void tstart ( void )
95 {
96         gettimeofday ( &_tstart, &tz );
97 }
98 void tend ( void )
99 {
100         gettimeofday ( &_tend,&tz );
101 }
102 double tval()
103 {
104         double t1, t2;
105         t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );
106         t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 );
107         return t2-t1;
108 }
109 #endif
110
111 /* Our available solvers. */
112 // 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
113 // 254 = MAX!
114 static CM_SOLVER_DEF    solvers [] =
115 {
116         { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
117         // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
118 };
119
120 /* ********** cloth engine ******* */
121 /* Prototypes for internal functions.
122 */
123 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, DerivedMesh *dm);
124 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm );
125 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr);
126 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
127 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
128
129
130 /******************************************************************************
131 *
132 * External interface called by modifier.c clothModifier functions.
133 *
134 ******************************************************************************/
135 /**
136  * cloth_init -  creates a new cloth simulation.
137  *
138  * 1. create object
139  * 2. fill object with standard values or with the GUI settings if given
140  */
141 void cloth_init ( ClothModifierData *clmd )
142 {       
143         /* Initialize our new data structure to reasonable values. */
144         clmd->sim_parms->gravity [0] = 0.0;
145         clmd->sim_parms->gravity [1] = 0.0;
146         clmd->sim_parms->gravity [2] = -9.81;
147         clmd->sim_parms->structural = 15.0;
148         clmd->sim_parms->shear = 15.0;
149         clmd->sim_parms->bending = 0.5;
150         clmd->sim_parms->Cdis = 5.0; 
151         clmd->sim_parms->Cvi = 1.0;
152         clmd->sim_parms->mass = 0.3f;
153         clmd->sim_parms->stepsPerFrame = 5;
154         clmd->sim_parms->sim_time = 1.0;
155         clmd->sim_parms->flags = CLOTH_SIMSETTINGS_FLAG_AUTOPROTECT;
156         clmd->sim_parms->solver_type = 0;
157         clmd->sim_parms->preroll = 0;
158         clmd->sim_parms->maxspringlen = 10;
159         clmd->sim_parms->firstframe = 1;
160         clmd->sim_parms->lastframe = 250;
161         clmd->sim_parms->vgroup_mass = 0;
162         clmd->sim_parms->lastcachedframe = 0;
163         clmd->sim_parms->editedframe = 0;
164         clmd->sim_parms->autoprotect = 25;
165         clmd->sim_parms->firstcachedframe = -1.0;
166         clmd->sim_parms->avg_spring_len = 0.0;
167         clmd->sim_parms->presets = 2; /* cotton as start setting */
168         
169         clmd->coll_parms->self_friction = 5.0;
170         clmd->coll_parms->friction = 5.0;
171         clmd->coll_parms->loop_count = 3;
172         clmd->coll_parms->epsilon = 0.015f;
173         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
174         clmd->coll_parms->collision_list = NULL;
175         clmd->coll_parms->self_loop_count = 1.0;
176         clmd->coll_parms->selfepsilon = 0.75;
177
178         /* These defaults are copied from softbody.c's
179         * softbody_calc_forces() function.
180         */
181         clmd->sim_parms->eff_force_scale = 1000.0;
182         clmd->sim_parms->eff_wind_scale = 250.0;
183
184         // also from softbodies
185         clmd->sim_parms->maxgoal = 1.0f;
186         clmd->sim_parms->mingoal = 0.0f;
187         clmd->sim_parms->defgoal = 0.0f;
188         clmd->sim_parms->goalspring = 1.0f;
189         clmd->sim_parms->goalfrict = 0.0f;
190 }
191
192
193 BVH *bvh_build_from_cloth (ClothModifierData *clmd, float epsilon)
194 {
195         unsigned int i = 0;
196         BVH     *bvh=NULL;
197         Cloth *cloth = clmd->clothObject;
198         ClothVertex *verts = NULL;
199
200         if(!clmd)
201                 return NULL;
202
203         cloth = clmd->clothObject;
204
205         if(!cloth)
206                 return NULL;
207         
208         verts = cloth->verts;
209         
210         // in the moment, return zero if no faces there
211         if(!cloth->numfaces)
212                 return NULL;
213         
214         bvh = MEM_callocN(sizeof(BVH), "BVH");
215         if (bvh == NULL) 
216         {
217                 printf("bvh: Out of memory.\n");
218                 return NULL;
219         }
220         
221         // springs = cloth->springs;
222         // numsprings = cloth->numsprings;
223         
224         bvh->flags = 0;
225         bvh->leaf_tree = NULL;
226         bvh->leaf_root = NULL;
227         bvh->tree = NULL;
228
229         bvh->epsilon = epsilon;
230         bvh->numfaces = cloth->numfaces;
231         bvh->mfaces = cloth->mfaces;
232
233         bvh->numverts = cloth->numverts;
234         
235         bvh->current_x = MEM_callocN ( sizeof ( MVert ) * bvh->numverts, "bvh->current_x" );
236         
237         if (bvh->current_x == NULL) 
238         {
239                 printf("bvh: Out of memory.\n");
240                 MEM_freeN(bvh);
241                 return NULL;
242         }
243         
244         bvh->current_xold = MEM_callocN ( sizeof ( MVert ) * bvh->numverts, "bvh->current_xold" );
245         
246         if (bvh->current_xold == NULL) 
247         {
248                 printf("bvh: Out of memory.\n");
249                 MEM_freeN(bvh->current_x);
250                 MEM_freeN(bvh);
251                 return NULL;
252         }
253         
254         for(i = 0; i < bvh->numverts; i++)
255         {
256                 VECCOPY(bvh->current_x[i].co, verts[i].tx);
257                 VECCOPY(bvh->current_xold[i].co, verts[i].txold);
258         }
259         
260         bvh_build (bvh);
261         
262         return bvh;
263 }
264
265 void bvh_update_from_cloth(ClothModifierData *clmd, int moving)
266 {
267         unsigned int i = 0;
268         Cloth *cloth = clmd->clothObject;
269         BVH *bvh = cloth->tree;
270         ClothVertex *verts = cloth->verts;
271         
272         if(!bvh)
273                 return;
274         
275         if(cloth->numverts!=bvh->numverts)
276                 return;
277         
278         if(cloth->verts)
279         {
280                 for(i = 0; i < bvh->numverts; i++)
281                 {
282                         VECCOPY(bvh->current_x[i].co, verts[i].tx);
283                         VECCOPY(bvh->current_xold[i].co, verts[i].txold);
284                 }
285         }
286         
287         bvh_update(bvh, moving);
288 }
289
290 DerivedMesh *CDDM_create_tearing ( ClothModifierData *clmd, DerivedMesh *dm )
291 {
292         DerivedMesh *result = NULL;
293         unsigned int i = 0, a = 0, j=0;
294         int numverts = dm->getNumVerts ( dm );
295         int numfaces = dm->getNumFaces ( dm );
296
297         MVert *mvert = CDDM_get_verts ( dm );
298         MFace *mface = CDDM_get_faces ( dm );
299
300         MVert *mvert2;
301         MFace *mface2;
302         EdgeHash *edgehash = NULL;
303         Cloth *cloth = clmd->clothObject;
304         ClothSpring *springs = (ClothSpring *)cloth->springs;
305         unsigned int numsprings = cloth->numsprings;
306
307         // create spring tearing hash
308         edgehash = BLI_edgehash_new();
309
310         for ( i = 0; i < numsprings; i++ )
311         {
312                 if ( ( springs[i].flags & CLOTH_SPRING_FLAG_DEACTIVATE )
313                 && ( !BLI_edgehash_haskey ( edgehash, springs[i].ij, springs[i].kl ) ) )
314                 {
315                         BLI_edgehash_insert ( edgehash, springs[i].ij, springs[i].kl, NULL );
316                         BLI_edgehash_insert ( edgehash, springs[i].kl, springs[i].ij, NULL );
317                         j++;
318                 }
319         }
320
321         // printf("found %d tears\n", j);
322
323         result = CDDM_from_template ( dm, numverts, 0, numfaces );
324
325         if ( !result )
326                 return NULL;
327
328         // do verts
329         mvert2 = CDDM_get_verts ( result );
330         for ( a=0; a<numverts; a++ )
331         {
332                 MVert *inMV;
333                 MVert *mv = &mvert2[a];
334
335                 inMV = &mvert[a];
336
337                 DM_copy_vert_data ( dm, result, a, a, 1 );
338                 *mv = *inMV;
339         }
340
341
342         // do faces
343         mface2 = CDDM_get_faces ( result );
344         for ( a=0, i=0; a<numfaces; a++ )
345         {
346                 MFace *mf = &mface2[i];
347                 MFace *inMF;
348                 inMF = &mface[a];
349
350                 /*
351                 DM_copy_face_data(dm, result, a, i, 1);
352
353                 *mf = *inMF;
354                 */
355
356                 if ( ( !BLI_edgehash_haskey ( edgehash, mface[a].v1, mface[a].v2 ) )
357                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v2, mface[a].v3 ) )
358                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v3, mface[a].v4 ) )
359                                       && ( !BLI_edgehash_haskey ( edgehash, mface[a].v4, mface[a].v1 ) ) )
360                 {
361                         mf->v1 = mface[a].v1;
362                         mf->v2 = mface[a].v2;
363                         mf->v3 = mface[a].v3;
364                         mf->v4 = mface[a].v4;
365
366                         test_index_face ( mf, NULL, 0, 4 );
367
368                         i++;
369                 }
370         }
371
372         CDDM_lower_num_faces ( result, i );
373         CDDM_calc_edges ( result );
374         CDDM_calc_normals ( result );
375
376         BLI_edgehash_free ( edgehash, NULL );
377
378         return result;
379 }
380
381 int modifiers_indexInObject(Object *ob, ModifierData *md_seek);
382
383 int cloth_read_cache(Object *ob, ClothModifierData *clmd, float framenr)
384 {
385         FILE *fp = NULL;
386         int stack_index = -1;
387         unsigned int a, ret = 1;
388         Cloth *cloth = clmd->clothObject;
389         
390         if(!cloth)
391                 return 0;
392         
393         stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
394         
395         fp = BKE_ptcache_id_fopen((ID *)ob, 'r', framenr, stack_index);
396         if(!fp)
397                 ret = 0;
398         else {
399                 for(a = 0; a < cloth->numverts; a++)
400                 {
401                         if(fread(&cloth->verts[a].x, sizeof(float), 3, fp) != 3) 
402                         {
403                                 ret = 0;
404                                 break;
405                         }
406                         if(fread(&cloth->verts[a].xconst, sizeof(float), 3, fp) != 3) 
407                         {
408                                 ret = 0;
409                                 break;
410                         }
411                         if(fread(&cloth->verts[a].v, sizeof(float), 3, fp) != 3) 
412                         {
413                                 ret = 0;
414                                 break;
415                         }
416                 }
417                 
418                 fclose(fp);
419                 
420                 if(clmd->sim_parms->lastcachedframe < framenr)
421                 {
422                         if(G.rt > 0)
423                                 printf("cloth_read_cache problem: lnex - f#: %f, lastCF: %d\n", framenr, clmd->sim_parms->lastcachedframe);
424                 }
425                 
426                 if(G.rt > 0)
427                         printf("cloth_read_cache: %f successfully \n", framenr);
428         }
429         
430         if(G.rt > 0)
431                 printf("cloth_read_cache: %f\n", framenr);
432         
433         return ret;
434 }
435
436 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
437 {
438         int stack_index = -1;
439         
440         // don't do anything as long as we're in editmode!
441         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_EDITMODE)
442         {
443                 /* delete cache free request */
444                 clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
445                 
446                 return;
447         }
448         
449         /* clear cache if specific frame cleaning requested or cache is not protected */
450         if((!(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT)) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE))
451         {
452                 stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
453                 
454                 BKE_ptcache_id_clear((ID *)ob, PTCACHE_CLEAR_AFTER, framenr, stack_index);
455                 
456                 /* update last cached frame # */
457                 clmd->sim_parms->lastcachedframe = framenr;
458                 
459                 /* update first cached frame # */
460                 if((framenr < clmd->sim_parms->firstcachedframe) && (clmd->sim_parms->firstcachedframe >=0.0))
461                         clmd->sim_parms->firstcachedframe = -1.0;
462                 
463                 if(G.rt > 0)
464                         printf("cloth_clear_cache: %f\n", framenr);
465         }
466         
467         /* delete cache free request */
468         clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
469         
470         
471 }
472 void cloth_write_cache(Object *ob, ClothModifierData *clmd, float framenr)
473 {
474         FILE *fp = NULL;
475         int stack_index = -1;
476         unsigned int a;
477         Cloth *cloth = clmd->clothObject;
478         
479         if(G.rt > 0)
480                 printf("cloth_write_cache: %f\n", framenr);
481         
482         if(!cloth)
483         {
484                 if(G.rt > 0)
485                         printf("cloth_write_cache: no cloth\n");
486                 return;
487         }
488         
489         stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
490         
491         fp = BKE_ptcache_id_fopen((ID *)ob, 'w', framenr, stack_index);
492         if(!fp)
493         {
494                 if(G.rt > 0)
495                         printf("cloth_write_cache: no fp\n");
496                 return;
497         }
498         
499         for(a = 0; a < cloth->numverts; a++)
500         {
501                 fwrite(&cloth->verts[a].x, sizeof(float),3,fp);
502                 fwrite(&cloth->verts[a].xconst, sizeof(float),3,fp);
503                 fwrite(&cloth->verts[a].v, sizeof(float),3,fp);
504         }
505         
506         /* update last cached frame # */
507         clmd->sim_parms->lastcachedframe = MAX2(clmd->sim_parms->lastcachedframe, framenr);
508         
509         /* update first cached frame # */
510         if((clmd->sim_parms->firstcachedframe < 0.0) || ((framenr < clmd->sim_parms->firstcachedframe) && (clmd->sim_parms->firstcachedframe > 0.0)))
511                 clmd->sim_parms->firstcachedframe = framenr;
512         
513         if(G.rt > 0)
514                 printf("lcf: %d, framenr: %f\n", clmd->sim_parms->lastcachedframe, framenr);
515
516         fclose(fp);
517 }
518
519 /************************************************
520  * clothModifier_do - main simulation function
521 ************************************************/
522 DerivedMesh *clothModifier_do(ClothModifierData *clmd,Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
523
524 {
525         unsigned int i;
526         Cloth *cloth = clmd->clothObject;
527         float framenr = G.scene->r.cfra;
528         float current_time = bsystem_time ( ob, ( float ) G.scene->r.cfra, 0.0 );
529         ListBase *effectors = NULL;
530         ClothVertex *verts = NULL;
531         float deltaTime = current_time - clmd->sim_parms->sim_time;
532         unsigned int numverts = -1;
533         unsigned int numedges = -1;
534         unsigned int numfaces = -1;
535         MVert *mvert = NULL;
536         MEdge *medge = NULL;
537         MFace *mface = NULL;
538         DerivedMesh *result = NULL;
539         int ret = 0;
540         
541         if(G.rt > 0)
542                 printf("clothModifier_do start\n");
543         
544         /* we're getting called two times during file load,
545         resulting in a not valid G.relbase on the first time (cache makes problems)
546         --> just return back */
547         if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_LOADED) && (!G.relbase_valid)) 
548         {
549                 clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_LOADED;
550                 return dm;
551         }
552         
553         result = CDDM_copy(dm);
554         
555         if(!result)
556         {
557                 return dm;
558         }
559         
560         numverts = result->getNumVerts(result);
561         numedges = result->getNumEdges(result);
562         numfaces = result->getNumFaces(result);
563         mvert = dm->getVertArray(result);
564         medge = dm->getEdgeArray(result);
565         mface = dm->getFaceArray(result);
566         
567         /* check if cache is active / if file is already saved */
568         /*
569         if ((!G.relbase_valid) && ( deltaTime != 1.0f ))
570         {
571         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
572 }
573         */
574         
575         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_RESET)
576         {       
577                 cloth_free_modifier (ob, clmd);
578                 if(G.rt > 0)
579                         printf("clothModifier_do CLOTH_SIMSETTINGS_FLAG_RESET\n");
580                 
581                 // prevent rebuilding of cloth each time you move backward 
582                 if(deltaTime < 0.0)
583                         return result;
584         }
585         
586         // unused in the moment, calculated seperately in implicit.c
587         clmd->sim_parms->dt = 1.0f / clmd->sim_parms->stepsPerFrame;
588         
589         if ( ( clmd->clothObject == NULL ) || (clmd->clothObject && (numverts != clmd->clothObject->numverts )) )
590         {       
591                 /* only force free the cache if we have a different number of verts */
592                 if(clmd->clothObject && (numverts != clmd->clothObject->numverts ))
593                 {
594                         if(G.rt > 0)
595                                 printf("Force Freeing: numverts != clmd->clothObject->numverts\n");
596                         
597                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
598                         cloth_free_modifier ( ob, clmd );
599                 }
600                 
601                 cloth_clear_cache(ob, clmd, 0);
602                                 
603                 if ( !cloth_from_object ( ob, clmd, result, framenr ) )
604                         return result;
605         
606                 if ( clmd->clothObject == NULL )
607                         return result;
608         
609                 cloth = clmd->clothObject;
610                 
611                 if(!cloth_read_cache(ob, clmd, framenr))
612                 {
613                         /* save first frame in case we have a reseted object 
614                         and we move one frame forward.
615                         In that case we would only start with the SECOND frame
616                         if we don't save the current state before 
617                         TODO PROBLEM: IMHO we can't track external movement from the
618                         first frame in this case! */
619                         /*
620                         if ( deltaTime == 1.0f )
621                         cloth_write_cache(ob, clmd, framenr-1.0);
622                         */
623                         if(G.rt > 0)
624                                 printf("cloth_from_object NO cloth_read_cache cloth_write_cache\n");
625                 }
626                 else
627                 {
628                         if(G.rt > 0)
629                                 printf("cloth_from_object cloth_read_cache\n");
630                         
631                         implicit_set_positions(clmd);
632                 }
633                 
634                 clmd->sim_parms->sim_time = current_time;
635         }
636         
637         // only be active during a specific period:
638         // that's "first frame" and "last frame" on GUI
639         if ( current_time < clmd->sim_parms->firstframe )
640         {
641                 if(G.rt > 0)
642                         printf("current_time < clmd->sim_parms->firstframe\n");
643                 return result;
644         }
645         else if ( current_time > clmd->sim_parms->lastframe )
646         {
647                 int stack_index = modifiers_indexInObject(ob, (ModifierData *)clmd);
648                         
649                 if(G.rt > 0)
650                         printf("current_time > clmd->sim_parms->lastframe\n");
651                 
652                 if(BKE_ptcache_id_exist((ID *)ob, clmd->sim_parms->lastcachedframe, stack_index))
653                 {
654                         if(cloth_read_cache(ob, clmd, clmd->sim_parms->lastcachedframe))
655                         {
656                                 implicit_set_positions(clmd);
657                                 
658                                 // Copy the result back to the object.
659                                 cloth_to_object (ob, clmd, result);
660                         }
661                 }
662                 return result;
663         }
664         
665         // check for autoprotection, but only if cache active
666         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_AUTOPROTECT)
667         {
668                 if((framenr >= clmd->sim_parms->autoprotect) && (G.relbase_valid))
669                 {
670                         if(G.rt > 0)
671                                 printf("fr#: %f, auto: %d\n", framenr, clmd->sim_parms->autoprotect);
672                         
673                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT;
674                 }
675         }
676         
677         /* nice moving one frame forward */
678         if ( deltaTime == 1.0f )
679         {
680                 clmd->sim_parms->sim_time = current_time;
681                         
682                 if(G.rt > 0)
683                         printf("clothModifier_do deltaTime=1\n");
684                 
685                 if(!cloth_read_cache(ob, clmd, framenr))
686                 {
687                         verts = cloth->verts;
688
689                         // Force any pinned verts to their constrained location.
690                         for ( i = 0; i < clmd->clothObject->numverts; i++, verts++ )
691                         {
692                                 // Save the previous position.
693                                 VECCOPY ( verts->xold, verts->xconst );
694                                 VECCOPY ( verts->txold, verts->x );
695
696                                 // Get the current position.
697                                 VECCOPY ( verts->xconst, mvert[i].co );
698                                 Mat4MulVecfl ( ob->obmat, verts->xconst );
699                         }
700                         
701                         tstart();
702
703                         // Call the solver.
704                         if ( solvers [clmd->sim_parms->solver_type].solver )
705                         {
706                                 ret = solvers [clmd->sim_parms->solver_type].solver ( ob, framenr, clmd, effectors );
707                         }
708
709                         tend();
710                         // printf ( "Cloth simulation time: %f\n", ( float ) tval() );
711                         
712                         if(ret)
713                                 cloth_write_cache(ob, clmd, framenr);
714                         else
715                                 clmd->sim_parms->sim_time--;
716                 }
717                 else
718                 {
719                         if(G.rt > 0)
720                                 printf("clothModifier_do deltaTime=1 cacheread\n");
721                         implicit_set_positions(clmd);
722                 }
723                 
724                 // Copy the result back to the object.
725                 cloth_to_object (ob, clmd, result);
726         }
727         else if(deltaTime == 0.0f) 
728         {       
729                 if(G.rt > 0)
730                         printf("dt = 0, %f\n", framenr);
731                 if(cloth_read_cache(ob, clmd, framenr))
732                 {
733                         cloth_to_object (ob, clmd, result);
734                         implicit_set_positions(clmd);
735                 }
736                 else /* same cache parts are missing */
737                 {
738                         /* jump to a non-existing frame makes sim reset if cache is not protected */
739                         if(!(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT))
740                         {       
741                                 /* prevent freeing when used with vectorblur */
742                                 if(!useRenderParams)
743                                 {
744                                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_CCACHE_FFREE;
745                                         cloth_clear_cache(ob, clmd, 0);
746                                         
747                                         cloth_write_cache(ob, clmd, framenr);
748                                 }
749                         }
750                 }
751         }
752         else
753         {       
754                 if(G.rt > 0)
755                         printf("dt > 1.0 || dt < 0.0, %f, st: %f, ct: %f\n", framenr, clmd->sim_parms->sim_time, current_time);
756                 if(cloth_read_cache(ob, clmd, framenr))
757                 {
758                         cloth_to_object (ob, clmd, result);
759                         implicit_set_positions(clmd);
760                 }
761                 else
762                 {
763                         /* jump to a non-existing frame makes sim reset if cache is not protected */
764                         if(!(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_CCACHE_PROTECT))
765                         {
766                                 /* prevent freeing when used with vectorblur */
767                                 if(!useRenderParams)
768                                         clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_RESET;
769                         }
770                 }
771                 clmd->sim_parms->sim_time = current_time;
772         }
773         
774         return result;
775 }
776
777 /* frees all */
778 void cloth_free_modifier ( Object *ob, ClothModifierData *clmd )
779 {
780         Cloth   *cloth = NULL;
781         
782         if ( !clmd )
783                 return;
784
785         cloth = clmd->clothObject;
786
787         
788         if ( cloth )
789         {       
790                 // If our solver provides a free function, call it
791                 if ( solvers [clmd->sim_parms->solver_type].free )
792                 {
793                         solvers [clmd->sim_parms->solver_type].free ( clmd );
794                 }
795
796                 // Free the verts.
797                 if ( cloth->verts != NULL )
798                         MEM_freeN ( cloth->verts );
799
800                 cloth->verts = NULL;
801                 cloth->numverts = 0;
802
803                 // Free the springs.
804                 if ( cloth->springs != NULL )
805                 {
806                         LinkNode *search = cloth->springs;
807                         while(search)
808                         {
809                                 ClothSpring *spring = search->link;
810                                                 
811                                 MEM_freeN ( spring );
812                                 search = search->next;
813                         }
814                         BLI_linklist_free(cloth->springs, NULL);
815                 
816                         cloth->springs = NULL;
817                 }
818
819                 cloth->springs = NULL;
820                 cloth->numsprings = 0;
821
822                 // free BVH collision tree
823                 if ( cloth->tree )
824                         bvh_free ( ( BVH * ) cloth->tree );
825
826                 // we save our faces for collision objects
827                 if ( cloth->mfaces )
828                         MEM_freeN ( cloth->mfaces );
829                 
830                 if(cloth->edgehash)
831                         BLI_edgehash_free ( cloth->edgehash, NULL );
832                 
833                 
834                 /*
835                 if(clmd->clothObject->facemarks)
836                 MEM_freeN(clmd->clothObject->facemarks);
837                 */
838                 MEM_freeN ( cloth );
839                 clmd->clothObject = NULL;
840         }
841         clmd->sim_parms->flags &= ~CLOTH_SIMSETTINGS_FLAG_RESET;
842 }
843
844 /* frees all */
845 void cloth_free_modifier_extern ( ClothModifierData *clmd )
846 {
847         Cloth   *cloth = NULL;
848         if(G.rt > 0)
849                 printf("cloth_free_modifier_extern\n");
850         
851         if ( !clmd )
852                 return;
853
854         cloth = clmd->clothObject;
855         
856         if ( cloth )
857         {       
858                 if(G.rt > 0)
859                         printf("cloth_free_modifier_extern in\n");
860                 
861                 // If our solver provides a free function, call it
862                 if ( solvers [clmd->sim_parms->solver_type].free )
863                 {
864                         solvers [clmd->sim_parms->solver_type].free ( clmd );
865                 }
866
867                 // Free the verts.
868                 if ( cloth->verts != NULL )
869                         MEM_freeN ( cloth->verts );
870
871                 cloth->verts = NULL;
872                 cloth->numverts = 0;
873
874                 // Free the springs.
875                 if ( cloth->springs != NULL )
876                 {
877                         LinkNode *search = cloth->springs;
878                         while(search)
879                         {
880                                 ClothSpring *spring = search->link;
881                                                 
882                                 MEM_freeN ( spring );
883                                 search = search->next;
884                         }
885                         BLI_linklist_free(cloth->springs, NULL);
886                 
887                         cloth->springs = NULL;
888                 }
889
890                 cloth->springs = NULL;
891                 cloth->numsprings = 0;
892
893                 // free BVH collision tree
894                 if ( cloth->tree )
895                         bvh_free ( ( BVH * ) cloth->tree );
896
897                 // we save our faces for collision objects
898                 if ( cloth->mfaces )
899                         MEM_freeN ( cloth->mfaces );
900                 
901                 if(cloth->edgehash)
902                         BLI_edgehash_free ( cloth->edgehash, NULL );
903                 
904                 
905                 /*
906                 if(clmd->clothObject->facemarks)
907                 MEM_freeN(clmd->clothObject->facemarks);
908                 */
909                 MEM_freeN ( cloth );
910                 clmd->clothObject = NULL;
911         }
912 }
913
914 /******************************************************************************
915 *
916 * Internal functions.
917 *
918 ******************************************************************************/
919
920 /**
921  * cloth_to_object - copies the deformed vertices to the object.
922  *
923  **/
924 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, DerivedMesh *dm)
925 {
926         unsigned int    i = 0;
927         MVert *mvert = NULL;
928         unsigned int numverts;
929         Cloth *cloth = clmd->clothObject;
930
931         if (clmd->clothObject) {
932                 /* inverse matrix is not uptodate... */
933                 Mat4Invert (ob->imat, ob->obmat);
934
935                 mvert = CDDM_get_verts(dm);
936                 numverts = dm->getNumVerts(dm);
937
938                 for (i = 0; i < numverts; i++)
939                 {
940                         VECCOPY (mvert[i].co, cloth->verts[i].x);
941                         Mat4MulVecfl (ob->imat, mvert[i].co);   /* cloth is in global coords */
942                 }
943         }
944 }
945
946
947 /**
948  * cloth_apply_vgroup - applies a vertex group as specified by type
949  *
950  **/
951 /* can be optimized to do all groups in one loop */
952 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
953 {
954         unsigned int i = 0;
955         unsigned int j = 0;
956         MDeformVert *dvert = NULL;
957         Cloth *clothObj = NULL;
958         unsigned int numverts = dm->getNumVerts ( dm );
959         float goalfac = 0;
960         ClothVertex *verts = NULL;
961
962         clothObj = clmd->clothObject;
963
964         if ( !dm )
965                 return;
966         
967         numverts = dm->getNumVerts ( dm );
968
969         verts = clothObj->verts;
970         
971         if (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || 
972                      (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) && 
973                      ((clmd->sim_parms->vgroup_mass>0) || 
974                      (clmd->sim_parms->vgroup_struct>0)||
975                      (clmd->sim_parms->vgroup_bend>0)))
976         {
977                 for ( i = 0; i < numverts; i++, verts++ )
978                 {       
979                         dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
980                         if ( dvert )
981                         {
982                                 for ( j = 0; j < dvert->totweight; j++ )
983                                 {
984                                         if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ))
985                                         {
986                                                 verts->goal = dvert->dw [j].weight;
987                                                 goalfac= 1.0f;
988                                                 
989                                                 /*
990                                                 // Kicking goal factor to simplify things...who uses that anyway?
991                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
992                                                 */
993                                                 
994                                                 verts->goal  = ( float ) pow ( verts->goal , 4.0f );
995                                                 if ( verts->goal >=SOFTGOALSNAP )
996                                                 {
997                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
998                                                 }
999                                         }
1000                                         
1001                                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING )
1002                                         {
1003                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1))
1004                                                 {
1005                                                         verts->struct_stiff = dvert->dw [j].weight;
1006                                                         verts->shear_stiff = dvert->dw [j].weight;
1007                                                 }
1008                                                 
1009                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1))
1010                                                 {
1011                                                         verts->bend_stiff = dvert->dw [j].weight;
1012                                                 }
1013                                         }
1014                                         /*
1015                                         // for later
1016                                         if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_weight-1))
1017                                         {
1018                                                 verts->mass = dvert->dw [j].weight;
1019                                         }
1020                                         */
1021                                 }
1022                         }
1023                 }
1024         }
1025 }
1026
1027 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr)
1028 {
1029         unsigned int i = 0;
1030         MVert *mvert = NULL;
1031         ClothVertex *verts = NULL;
1032         float tnull[3] = {0,0,0};
1033         int cache_there = 0;
1034         Cloth *cloth = NULL;
1035
1036         // If we have a clothObject, free it. 
1037         if ( clmd->clothObject != NULL )
1038         {
1039                 cloth_free_modifier ( ob, clmd );
1040                 if(G.rt > 0)
1041                         printf("cloth_free_modifier cloth_from_object\n");
1042         }
1043
1044         // Allocate a new cloth object.
1045         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
1046         if ( clmd->clothObject )
1047         {
1048                 clmd->clothObject->old_solver_type = 255;
1049                 // clmd->clothObject->old_collision_type = 255;
1050                 cloth = clmd->clothObject;
1051                 clmd->clothObject->edgehash = NULL;
1052         }
1053         else if ( !clmd->clothObject )
1054         {
1055                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject." );
1056                 return 0;
1057         }
1058
1059         // mesh input objects need DerivedMesh
1060         if ( !dm )
1061                 return 0;
1062
1063         cloth_from_mesh ( ob, clmd, dm );
1064
1065         if((clmd->sim_parms->firstcachedframe < 0.0) || ((clmd->sim_parms->firstcachedframe >= 0.0) && (!cloth_read_cache(ob, clmd, clmd->sim_parms->firstcachedframe))))
1066         {
1067                 // no cache there
1068                 cache_there = 0;
1069                 if(G.rt > 0)
1070                         printf("cache_there = 0\n");
1071         }
1072         else
1073         {
1074                 // we have a cache
1075                 cache_there = 1;
1076                 if(G.rt > 0)
1077                         printf("cache_there = 1, fcf: %d\n", clmd->sim_parms->firstcachedframe);
1078         }
1079         
1080         // create springs 
1081         clmd->clothObject->springs = NULL;
1082         clmd->clothObject->numsprings = -1;
1083         
1084         mvert = dm->getVertArray ( dm );
1085         verts = clmd->clothObject->verts;
1086
1087         // set initial values
1088         for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ )
1089         {
1090                 if(!cache_there)
1091                 {
1092                         VECCOPY ( verts->x, mvert[i].co );
1093                         Mat4MulVecfl ( ob->obmat, verts->x );
1094                 }
1095                 
1096                 /* no GUI interface yet */
1097                 verts->mass = clmd->sim_parms->mass; 
1098                 verts->impulse_count = 0;
1099
1100                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1101                         verts->goal= clmd->sim_parms->defgoal;
1102                 else
1103                         verts->goal= 0.0f;
1104
1105                 verts->flags = 0;
1106                 VECCOPY ( verts->xold, verts->x );
1107                 VECCOPY ( verts->xconst, verts->x );
1108                 VECCOPY ( verts->txold, verts->x );
1109                 VecMulf ( verts->v, 0.0f );
1110
1111                 verts->impulse_count = 0;
1112                 VECCOPY ( verts->impulse, tnull );
1113         }
1114         
1115         // apply / set vertex groups
1116         // has to be happen before springs are build!
1117         cloth_apply_vgroup (clmd, dm);
1118         
1119         
1120         if ( !cloth_build_springs ( clmd, dm ) )
1121         {
1122                 cloth_free_modifier ( ob, clmd );
1123                 modifier_setError ( & ( clmd->modifier ), "Can't build springs." );
1124                 printf("cloth_free_modifier cloth_build_springs\n");
1125                 return 0;
1126         }
1127         
1128         for ( i = 0; i < dm->getNumVerts(dm); i++)
1129         {
1130                 if((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO))
1131                 {
1132                         cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
1133                 }
1134         }
1135         
1136         // init our solver
1137         if ( solvers [clmd->sim_parms->solver_type].init )
1138                 solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
1139         
1140         if(cache_there)
1141                 implicit_set_positions(clmd);
1142
1143         clmd->clothObject->tree = bvh_build_from_cloth ( clmd, clmd->coll_parms->epsilon );
1144
1145         return 1;
1146 }
1147
1148
1149 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm )
1150 {
1151         unsigned int numverts = dm->getNumVerts ( dm );
1152         unsigned int numfaces = dm->getNumFaces ( dm );
1153         MFace *mface = CDDM_get_faces(dm);
1154         unsigned int i = 0;
1155
1156         /* Allocate our vertices. */
1157         clmd->clothObject->numverts = numverts;
1158         clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
1159         if ( clmd->clothObject->verts == NULL )
1160         {
1161                 cloth_free_modifier ( ob, clmd );
1162                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->verts." );
1163                 printf("cloth_free_modifier clmd->clothObject->verts\n");
1164                 return;
1165         }
1166
1167         // save face information
1168         clmd->clothObject->numfaces = numfaces;
1169         clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
1170         if ( clmd->clothObject->mfaces == NULL )
1171         {
1172                 cloth_free_modifier ( ob, clmd );
1173                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->mfaces." );
1174                 printf("cloth_free_modifier clmd->clothObject->mfaces\n");
1175                 return;
1176         }
1177         for ( i = 0; i < numfaces; i++ )
1178                 memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
1179
1180         /* Free the springs since they can't be correct if the vertices
1181         * changed.
1182         */
1183         if ( clmd->clothObject->springs != NULL )
1184                 MEM_freeN ( clmd->clothObject->springs );
1185
1186 }
1187
1188 /***************************************************************************************
1189 * SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
1190 ***************************************************************************************/
1191
1192 // be carefull: implicit solver has to be resettet when using this one!
1193 // --> only for implicit handling of this spring!
1194 int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
1195 {
1196         Cloth *cloth = clmd->clothObject;
1197         ClothSpring *spring = NULL;
1198         
1199         if(cloth)
1200         {
1201                 // TODO: look if this spring is already there
1202                 
1203                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1204                 
1205                 if(!spring)
1206                         return 0;
1207                 
1208                 spring->ij = indexA;
1209                 spring->kl = indexB;
1210                 spring->restlen =  restlength;
1211                 spring->type = spring_type;
1212                 spring->flags = 0;
1213                 spring->stiffness = 0;
1214                 
1215                 cloth->numsprings++;
1216         
1217                 BLI_linklist_prepend ( &cloth->springs, spring );
1218                 
1219                 return 1;
1220         }
1221         return 0;
1222 }
1223
1224 void cloth_free_errorsprings(Cloth *cloth, EdgeHash *edgehash, LinkNode **edgelist)
1225 {
1226         unsigned int i = 0;
1227         
1228         if ( cloth->springs != NULL )
1229         {
1230                 LinkNode *search = cloth->springs;
1231                 while(search)
1232                 {
1233                         ClothSpring *spring = search->link;
1234                                                 
1235                         MEM_freeN ( spring );
1236                         search = search->next;
1237                 }
1238                 BLI_linklist_free(cloth->springs, NULL);
1239                 
1240                 cloth->springs = NULL;
1241         }
1242         
1243         if(edgelist)
1244         {
1245                 for ( i = 0; i < cloth->numverts; i++ )
1246                 {
1247                         BLI_linklist_free ( edgelist[i],NULL );
1248                 }
1249
1250                 MEM_freeN ( edgelist );
1251         }
1252         
1253         if(cloth->edgehash)
1254                 BLI_edgehash_free ( cloth->edgehash, NULL );
1255 }
1256
1257 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
1258 {
1259         Cloth *cloth = clmd->clothObject;
1260         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1261         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
1262         unsigned int i = 0;
1263         unsigned int numverts = dm->getNumVerts ( dm );
1264         unsigned int numedges = dm->getNumEdges ( dm );
1265         unsigned int numfaces = dm->getNumFaces ( dm );
1266         MEdge *medge = CDDM_get_edges ( dm );
1267         MFace *mface = CDDM_get_faces ( dm );
1268         unsigned int index2 = 0; // our second vertex index
1269         LinkNode **edgelist = NULL;
1270         EdgeHash *edgehash = NULL;
1271         LinkNode *search = NULL, *search2 = NULL;
1272         float temp[3];
1273         
1274         // error handling
1275         if ( numedges==0 )
1276                 return 0;
1277
1278         cloth->springs = NULL;
1279
1280         edgelist = MEM_callocN ( sizeof ( LinkNode * ) * numverts, "cloth_edgelist_alloc" );
1281         
1282         if(!edgelist)
1283                 return 0;
1284         
1285         for ( i = 0; i < numverts; i++ )
1286         {
1287                 edgelist[i] = NULL;
1288         }
1289
1290         if ( cloth->springs )
1291                 MEM_freeN ( cloth->springs );
1292
1293         // create spring network hash
1294         edgehash = BLI_edgehash_new();
1295
1296         // structural springs
1297         for ( i = 0; i < numedges; i++ )
1298         {
1299                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1300
1301                 if ( spring )
1302                 {
1303                         spring->ij = MIN2(medge[i].v1, medge[i].v2);
1304                         spring->kl = MAX2(medge[i].v2, medge[i].v1);
1305                         VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1306                         spring->restlen =  sqrt ( INPR ( temp, temp ) );
1307                         clmd->sim_parms->avg_spring_len += spring->restlen;
1308                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1309                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1310                         cloth->verts[spring->ij].spring_count++;
1311                         cloth->verts[spring->kl].spring_count++;
1312                         spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1313                         spring->flags = 0;
1314                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0;
1315                         struct_springs++;
1316                         
1317                         BLI_linklist_prepend ( &cloth->springs, spring );
1318                 }
1319                 else
1320                 {
1321                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1322                         return 0;
1323                 }
1324         }
1325         
1326         if(struct_springs > 0)
1327                 clmd->sim_parms->avg_spring_len /= struct_springs;
1328         
1329         for(i = 0; i < numverts; i++)
1330         {
1331                 cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49 / ((float)cloth->verts[i].spring_count);
1332         }
1333         
1334         // shear springs
1335         for ( i = 0; i < numfaces; i++ )
1336         {
1337                 // triangle faces already have shear springs due to structural geometry
1338                 if ( !mface[i].v4 )
1339                         continue; 
1340                 
1341                 spring = ( ClothSpring *) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1342                 
1343                 if(!spring)
1344                 {
1345                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1346                         return 0;
1347                 }
1348
1349                 spring->ij = MIN2(mface[i].v1, mface[i].v3);
1350                 spring->kl = MAX2(mface[i].v3, mface[i].v1);
1351                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1352                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1353                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1354                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1355
1356                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1357                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1358                 shear_springs++;
1359
1360                 BLI_linklist_prepend ( &cloth->springs, spring );
1361
1362                 
1363                 // if ( mface[i].v4 ) --> Quad face
1364                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1365                 
1366                 if(!spring)
1367                 {
1368                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1369                         return 0;
1370                 }
1371
1372                 spring->ij = MIN2(mface[i].v2, mface[i].v4);
1373                 spring->kl = MAX2(mface[i].v4, mface[i].v2);
1374                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1375                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1376                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1377                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1378
1379                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1380                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1381                 shear_springs++;
1382
1383                 BLI_linklist_prepend ( &cloth->springs, spring );
1384         }
1385         
1386         // bending springs
1387         search2 = cloth->springs;
1388         for ( i = struct_springs; i < struct_springs+shear_springs; i++ )
1389         {
1390                 if ( !search2 )
1391                         break;
1392
1393                 tspring2 = search2->link;
1394                 search = edgelist[tspring2->kl];
1395                 while ( search )
1396                 {
1397                         tspring = search->link;
1398                         index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
1399                         
1400                         // check for existing spring
1401                         // check also if startpoint is equal to endpoint
1402                         if ( !BLI_edgehash_haskey ( edgehash, MIN2(tspring2->ij, index2), MAX2(tspring2->ij, index2) )
1403                         && ( index2!=tspring2->ij ) )
1404                         {
1405                                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1406                                 
1407                                 if(!spring)
1408                                 {
1409                                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1410                                         return 0;
1411                                 }
1412
1413                                 spring->ij = MIN2(tspring2->ij, index2);
1414                                 spring->kl = MAX2(tspring2->ij, index2);
1415                                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1416                                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1417                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1418                                 spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0;
1419                                 BLI_edgehash_insert ( edgehash, spring->ij, spring->kl, NULL );
1420                                 bend_springs++;
1421
1422                                 BLI_linklist_prepend ( &cloth->springs, spring );
1423                         }
1424                         search = search->next;
1425                 }
1426                 search2 = search2->next;
1427         }
1428         
1429         /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
1430         for ( i = 0; i < numedges; i++ ) // struct springs
1431                 BLI_edgehash_insert ( edgehash, MIN2(medge[i].v1, medge[i].v2), MAX2(medge[i].v2, medge[i].v1), NULL );
1432         
1433         for ( i = 0; i < numfaces; i++ ) // edge springs
1434         {
1435                 if(mface[i].v4)
1436                 {
1437                         BLI_edgehash_insert ( edgehash, MIN2(mface[i].v1, mface[i].v3), MAX2(mface[i].v3, mface[i].v1), NULL );
1438                         
1439                         BLI_edgehash_insert ( edgehash, MIN2(mface[i].v2, mface[i].v4), MAX2(mface[i].v2, mface[i].v4), NULL );
1440                 }
1441         }
1442         
1443         
1444         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1445         
1446         if ( edgelist )
1447         {
1448                 for ( i = 0; i < numverts; i++ )
1449                 {
1450                         BLI_linklist_free ( edgelist[i],NULL );
1451                 }
1452         
1453                 MEM_freeN ( edgelist );
1454         }
1455         
1456         cloth->edgehash = edgehash;
1457         
1458         if(G.rt>0)
1459                 printf("avg_len: %f\n",clmd->sim_parms->avg_spring_len);
1460
1461         return 1;
1462
1463 } /* cloth_build_springs */
1464 /***************************************************************************************
1465 * SPRING NETWORK BUILDING IMPLEMENTATION END
1466 ***************************************************************************************/
1467