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