6eb9f73105647a4131353f22c6a666e74b404cf2
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*  cloth.c
2 *
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) Blender Foundation
21 * All rights reserved.
22 *
23 * Contributor(s): Daniel Genrich
24 *
25 * ***** END GPL LICENSE BLOCK *****
26 */
27
28 #include "MEM_guardedalloc.h"
29
30 #include "BKE_cloth.h"
31
32 #include "DNA_cloth_types.h"
33 #include "DNA_mesh_types.h"
34 #include "DNA_object_force.h"
35 #include "DNA_scene_types.h"
36
37 #include "BKE_deform.h"
38 #include "BKE_DerivedMesh.h"
39 #include "BKE_cdderivedmesh.h"
40 #include "BKE_effect.h"
41 #include "BKE_global.h"
42 #include "BKE_object.h"
43 #include "BKE_modifier.h"
44 #include "BKE_utildefines.h"
45
46 #include "BKE_pointcache.h"
47
48 #include "BLI_kdopbvh.h"
49
50 #include <time.h>
51
52 #ifdef _WIN32
53 void tstart ( void )
54 {}
55 void tend ( void )
56 {
57 }
58 double tval()
59 {
60         return 0;
61 }
62 #else
63 #include <sys/time.h>
64                          static struct timeval _tstart, _tend;
65          static struct timezone tz;
66          void tstart ( void )
67 {
68         gettimeofday ( &_tstart, &tz );
69 }
70 void tend ( void )
71 {
72         gettimeofday ( &_tend,&tz );
73 }
74 double tval()
75 {
76         double t1, t2;
77         t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );
78         t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 );
79         return t2-t1;
80 }
81 #endif
82
83
84 /* Util macros */
85 #define TO_STR(a)       #a
86 #define JOIN(a,b)       a##b
87
88 /* Benchmark macros */
89 #if 1
90
91 #define BENCH(a)        \
92         do {                    \
93                 clock_t _clock_init = clock();  \
94                 (a);                                                    \
95                 printf("%s: %fms\n", #a, (float)(clock()-_clock_init)*1000/CLOCKS_PER_SEC);     \
96 } while(0)
97
98 #define BENCH_VAR(name)         clock_t JOIN(_bench_step,name) = 0, JOIN(_bench_total,name) = 0
99 #define BENCH_BEGIN(name)       JOIN(_bench_step, name) = clock()
100 #define BENCH_END(name)         JOIN(_bench_total,name) += clock() - JOIN(_bench_step,name)
101 #define BENCH_RESET(name)       JOIN(_bench_total, name) = 0
102 #define BENCH_REPORT(name)      printf("%s: %fms\n", TO_STR(name), JOIN(_bench_total,name)*1000.0f/CLOCKS_PER_SEC)
103
104 #else
105
106 #define BENCH(a)        (a)
107 #define BENCH_VAR(name)
108 #define BENCH_BEGIN(name)
109 #define BENCH_END(name)
110 #define BENCH_RESET(name)
111 #define BENCH_REPORT(name)
112
113 #endif
114
115
116
117 /* Our available solvers. */
118 // 255 is the magic reserved number, so NEVER try to put 255 solvers in here!
119 // 254 = MAX!
120 static CM_SOLVER_DEF    solvers [] =
121 {
122         { "Implicit", CM_IMPLICIT, implicit_init, implicit_solver, implicit_free },
123         // { "Implicit C++", CM_IMPLICITCPP, implicitcpp_init, implicitcpp_solver, implicitcpp_free },
124 };
125
126 /* ********** cloth engine ******* */
127 /* Prototypes for internal functions.
128 */
129 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, DerivedMesh *dm);
130 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm );
131 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first);
132 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm );
133 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm );
134
135
136 /******************************************************************************
137 *
138 * External interface called by modifier.c clothModifier functions.
139 *
140 ******************************************************************************/
141 /**
142  * cloth_init -  creates a new cloth simulation.
143  *
144  * 1. create object
145  * 2. fill object with standard values or with the GUI settings if given
146  */
147 void cloth_init ( ClothModifierData *clmd )
148 {       
149         /* Initialize our new data structure to reasonable values. */
150         clmd->sim_parms->gravity [0] = 0.0;
151         clmd->sim_parms->gravity [1] = 0.0;
152         clmd->sim_parms->gravity [2] = -9.81;
153         clmd->sim_parms->structural = 15.0;
154         clmd->sim_parms->shear = 15.0;
155         clmd->sim_parms->bending = 0.5;
156         clmd->sim_parms->Cdis = 5.0; 
157         clmd->sim_parms->Cvi = 1.0;
158         clmd->sim_parms->mass = 0.3f;
159         clmd->sim_parms->stepsPerFrame = 5;
160         clmd->sim_parms->flags = 0;
161         clmd->sim_parms->solver_type = 0;
162         clmd->sim_parms->preroll = 0;
163         clmd->sim_parms->maxspringlen = 10;
164         clmd->sim_parms->vgroup_mass = 0;
165         clmd->sim_parms->avg_spring_len = 0.0;
166         clmd->sim_parms->presets = 2; /* cotton as start setting */
167         clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
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 BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
193 {
194         int i;
195         BVHTree *bvhtree;
196         Cloth *cloth = clmd->clothObject;
197         ClothVertex *verts;
198         MFace *mfaces;
199         float co[12];
200
201         if(!clmd)
202                 return NULL;
203
204         cloth = clmd->clothObject;
205
206         if(!cloth)
207                 return NULL;
208         
209         verts = cloth->verts;
210         mfaces = cloth->mfaces;
211         
212         // in the moment, return zero if no faces there
213         if(!cloth->numfaces)
214                 return NULL;
215         
216         // create quadtree with k=26
217         bvhtree = BLI_bvhtree_new(cloth->numfaces, epsilon, 8, 6);
218         
219         // fill tree
220         for(i = 0; i < cloth->numfaces; i++, mfaces++)
221         {
222                 VECCOPY(&co[0*3], verts[mfaces->v1].xold);
223                 VECCOPY(&co[1*3], verts[mfaces->v2].xold);
224                 VECCOPY(&co[2*3], verts[mfaces->v3].xold);
225                 
226                 if(mfaces->v4)
227                         VECCOPY(&co[3*3], verts[mfaces->v4].xold);
228                 
229                 BLI_bvhtree_insert(bvhtree, i, co, (mfaces->v4 ? 4 : 3));
230         }
231         
232         // balance tree
233         BLI_bvhtree_balance(bvhtree);
234         
235         return bvhtree;
236 }
237
238 void bvhtree_update_from_cloth(ClothModifierData *clmd, int moving)
239 {       
240         unsigned int i = 0;
241         Cloth *cloth = clmd->clothObject;
242         BVHTree *bvhtree = cloth->bvhtree;
243         ClothVertex *verts = cloth->verts;
244         MFace *mfaces;
245         float co[12], co_moving[12];
246         int ret = 0;
247         
248         if(!bvhtree)
249                 return;
250         
251         mfaces = cloth->mfaces;
252         
253         // update vertex position in bvh tree
254         if(verts && mfaces)
255         {
256                 for(i = 0; i < cloth->numfaces; i++, mfaces++)
257                 {
258                         VECCOPY(&co[0*3], verts[mfaces->v1].txold);
259                         VECCOPY(&co[1*3], verts[mfaces->v2].txold);
260                         VECCOPY(&co[2*3], verts[mfaces->v3].txold);
261                         
262                         if(mfaces->v4)
263                                 VECCOPY(&co[3*3], verts[mfaces->v4].txold);
264                 
265                         // copy new locations into array
266                         if(moving)
267                         {
268                                 // update moving positions
269                                 VECCOPY(&co_moving[0*3], verts[mfaces->v1].tx);
270                                 VECCOPY(&co_moving[1*3], verts[mfaces->v2].tx);
271                                 VECCOPY(&co_moving[2*3], verts[mfaces->v3].tx);
272                                 
273                                 if(mfaces->v4)
274                                         VECCOPY(&co_moving[3*3], verts[mfaces->v4].tx);
275                                 
276                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, co_moving, (mfaces->v4 ? 4 : 3));
277                         }
278                         else
279                         {
280                                 ret = BLI_bvhtree_update_node(bvhtree, i, co, NULL, (mfaces->v4 ? 4 : 3));
281                         }
282                         
283                         // check if tree is already full
284                         if(!ret)
285                                 break;
286                 }
287                 
288                 BLI_bvhtree_update_tree(bvhtree);
289         }
290 }
291
292 int modifiers_indexInObject(Object *ob, ModifierData *md_seek);
293
294 int cloth_read_cache(Object *ob, ClothModifierData *clmd, float framenr)
295 {
296         PTCacheID pid;
297         PTCacheFile *pf;
298         Cloth *cloth = clmd->clothObject;
299         unsigned int a, ret = 1;
300         
301         if(!cloth)
302                 return 0;
303         
304         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
305         pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, framenr);
306         if(pf) {
307                 for(a = 0; a < cloth->numverts; a++) {
308                         if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].x, 3)) {
309                                 ret = 0;
310                                 break;
311                         }
312                         if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].xconst, 3)) {
313                                 ret = 0;
314                                 break;
315                         }
316                         if(!BKE_ptcache_file_read_floats(pf, cloth->verts[a].v, 3)) {
317                                 ret = 0;
318                                 break;
319                         }
320                 }
321                 
322                 BKE_ptcache_file_close(pf);
323         }
324         else
325                 ret = 0;
326         
327         return ret;
328 }
329
330 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
331 {
332         PTCacheID pid;
333         
334         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
335
336         // don't do anything as long as we're in editmode!
337         if(pid.cache->flag & PTCACHE_BAKE_EDIT_ACTIVE)
338                 return;
339         
340         BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
341 }
342
343 void cloth_write_cache(Object *ob, ClothModifierData *clmd, float framenr)
344 {
345         Cloth *cloth = clmd->clothObject;
346         PTCacheID pid;
347         PTCacheFile *pf;
348         unsigned int a;
349         
350         if(!cloth)
351                 return;
352         
353         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
354         pf = BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, framenr);
355         if(!pf)
356                 return;
357         
358         for(a = 0; a < cloth->numverts; a++) {
359                 BKE_ptcache_file_write_floats(pf, cloth->verts[a].x, 3);
360                 BKE_ptcache_file_write_floats(pf, cloth->verts[a].xconst, 3);
361                 BKE_ptcache_file_write_floats(pf, cloth->verts[a].v, 3);
362         }
363         
364         BKE_ptcache_file_close(pf);
365 }
366
367 static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
368 {
369         PointCache *cache;
370
371         cache= clmd->point_cache;
372
373         /* initialize simulation data if it didn't exist already */
374         if(clmd->clothObject == NULL) { 
375                 if(!cloth_from_object(ob, clmd, result, framenr, 1)) {
376                         cache->flag &= ~PTCACHE_SIMULATION_VALID;
377                         cache->simframe= 0;
378                         return 0;
379                 }
380         
381                 if(clmd->clothObject == NULL) {
382                         cache->flag &= ~PTCACHE_SIMULATION_VALID;
383                         cache->simframe= 0;
384                         return 0;
385                 }
386         
387                 implicit_set_positions(clmd);
388         }
389
390         return 1;
391 }
392
393 static int do_step_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *result, int framenr)
394 {
395         ClothVertex *verts = NULL;
396         Cloth *cloth;
397         ListBase *effectors = NULL;
398         MVert *mvert;
399         int i, ret = 0;
400
401         /* simulate 1 frame forward */
402         cloth = clmd->clothObject;
403         verts = cloth->verts;
404         mvert = result->getVertArray(result);
405
406         /* force any pinned verts to their constrained location. */
407         for(i = 0; i < clmd->clothObject->numverts; i++, verts++) {
408                 /* save the previous position. */
409                 VECCOPY(verts->xold, verts->xconst);
410                 VECCOPY(verts->txold, verts->x);
411
412                 /* Get the current position. */
413                 VECCOPY(verts->xconst, mvert[i].co);
414                 Mat4MulVecfl(ob->obmat, verts->xconst);
415         }
416         
417         tstart();
418
419         /* call the solver. */
420         if(solvers [clmd->sim_parms->solver_type].solver)
421                 ret = solvers[clmd->sim_parms->solver_type].solver(ob, framenr, clmd, effectors);
422
423         tend();
424
425         printf ( "Cloth simulation time: %f\n", ( float ) tval() ); 
426         
427         return ret;
428 }
429
430 /************************************************
431  * clothModifier_do - main simulation function
432 ************************************************/
433 DerivedMesh *clothModifier_do(ClothModifierData *clmd, Object *ob, DerivedMesh *dm, int useRenderParams, int isFinalCalc)
434 {
435         DerivedMesh *result;
436         PointCache *cache;
437         PTCacheID pid;
438         float timescale;
439         int framedelta, framenr, startframe, endframe;
440
441         framenr= (int)G.scene->r.cfra;
442         cache= clmd->point_cache;
443         result = CDDM_copy(dm);
444
445         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
446         BKE_ptcache_id_time(&pid, framenr, &startframe, &endframe, &timescale);
447         clmd->sim_parms->timescale= timescale;
448
449         if(!result) {
450                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
451                 cache->simframe= 0;
452                 return dm;
453         }
454         
455         /* verify we still have the same number of vertices, if not do nothing.
456          * note that this should only happen if the number of vertices changes
457          * during an animation due to a preceding modifier, this should not
458          * happen because of object changes! */
459         if(clmd->clothObject) {
460                 if(result->getNumVerts(result) != clmd->clothObject->numverts) {
461                         cache->flag &= ~PTCACHE_SIMULATION_VALID;
462                         cache->simframe= 0;
463                         return result;
464                 }
465         }
466         
467         // unused in the moment, calculated seperately in implicit.c
468         clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
469
470         /* handle continuous simulation with the play button */
471         if(BKE_ptcache_get_continue_physics()) {
472                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
473                 cache->simframe= 0;
474
475                 /* do simulation */
476                 if(!do_init_cloth(ob, clmd, result, framenr))
477                         return result;
478
479                 do_step_cloth(ob, clmd, result, framenr);
480                 cloth_to_object(ob, clmd, result);
481
482                 return result;
483         }
484
485         /* simulation is only active during a specific period */
486         if(framenr < startframe) {
487                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
488                 cache->simframe= 0;
489                 return result;
490         }
491         else if(framenr > endframe) {
492                 framenr= endframe;
493         }
494
495         if(cache->flag & PTCACHE_SIMULATION_VALID)
496                 framedelta= framenr - cache->simframe;
497         else
498                 framedelta= -1;
499
500         /* initialize simulation data if it didn't exist already */
501         if(!do_init_cloth(ob, clmd, result, framenr))
502                 return result;
503
504         /* try to read from cache */
505         if(cloth_read_cache(ob, clmd, framenr)) {
506                 cache->flag |= PTCACHE_SIMULATION_VALID;
507                 cache->simframe= framenr;
508
509                 implicit_set_positions(clmd);
510                 cloth_to_object (ob, clmd, result);
511
512                 return result;
513         }
514         else if(ob->id.lib || (cache->flag & PTCACHE_BAKED)) {
515                 /* if baked and nothing in cache, do nothing */
516                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
517                 cache->simframe= 0;
518                 return result;
519         }
520
521         if(framenr == startframe) {
522                 cache->flag |= PTCACHE_SIMULATION_VALID;
523                 cache->simframe= framenr;
524
525                 /* don't write cache on first frame, but on second frame write
526                  * cache for frame 1 and 2 */
527         }
528         else if(framedelta == 1) {
529                 /* if on second frame, write cache for first frame */
530                 if(framenr == startframe+1)
531                         cloth_write_cache(ob, clmd, startframe);
532
533                 /* do simulation */
534                 cache->flag |= PTCACHE_SIMULATION_VALID;
535                 cache->simframe= framenr;
536
537                 if(!do_step_cloth(ob, clmd, result, framenr)) {
538                         cache->flag &= ~PTCACHE_SIMULATION_VALID;
539                         cache->simframe= 0;
540                 }
541                 else
542                         cloth_write_cache(ob, clmd, framenr);
543
544                 cloth_to_object (ob, clmd, result);
545         }
546         else {
547                 cache->flag &= ~PTCACHE_SIMULATION_VALID;
548                 cache->simframe= 0;
549         }
550
551         return result;
552 }
553
554 /* frees all */
555 void cloth_free_modifier ( Object *ob, ClothModifierData *clmd )
556 {
557         Cloth   *cloth = NULL;
558         
559         if ( !clmd )
560                 return;
561
562         cloth = clmd->clothObject;
563
564         
565         if ( cloth )
566         {       
567                 // If our solver provides a free function, call it
568                 if ( solvers [clmd->sim_parms->solver_type].free )
569                 {
570                         solvers [clmd->sim_parms->solver_type].free ( clmd );
571                 }
572
573                 // Free the verts.
574                 if ( cloth->verts != NULL )
575                         MEM_freeN ( cloth->verts );
576
577                 cloth->verts = NULL;
578                 cloth->numverts = 0;
579
580                 // Free the springs.
581                 if ( cloth->springs != NULL )
582                 {
583                         LinkNode *search = cloth->springs;
584                         while(search)
585                         {
586                                 ClothSpring *spring = search->link;
587                                                 
588                                 MEM_freeN ( spring );
589                                 search = search->next;
590                         }
591                         BLI_linklist_free(cloth->springs, NULL);
592                 
593                         cloth->springs = NULL;
594                 }
595
596                 cloth->springs = NULL;
597                 cloth->numsprings = 0;
598
599                 // free BVH collision tree
600                 if ( cloth->bvhtree )
601                         BLI_bvhtree_free ( cloth->bvhtree );
602
603                 // we save our faces for collision objects
604                 if ( cloth->mfaces )
605                         MEM_freeN ( cloth->mfaces );
606                 
607                 if(cloth->edgehash)
608                         BLI_edgehash_free ( cloth->edgehash, NULL );
609                 
610                 
611                 /*
612                 if(clmd->clothObject->facemarks)
613                 MEM_freeN(clmd->clothObject->facemarks);
614                 */
615                 MEM_freeN ( cloth );
616                 clmd->clothObject = NULL;
617         }
618 }
619
620 /* frees all */
621 void cloth_free_modifier_extern ( ClothModifierData *clmd )
622 {
623         Cloth   *cloth = NULL;
624         if(G.rt > 0)
625                 printf("cloth_free_modifier_extern\n");
626         
627         if ( !clmd )
628                 return;
629
630         cloth = clmd->clothObject;
631         
632         if ( cloth )
633         {       
634                 if(G.rt > 0)
635                         printf("cloth_free_modifier_extern in\n");
636                 
637                 // If our solver provides a free function, call it
638                 if ( solvers [clmd->sim_parms->solver_type].free )
639                 {
640                         solvers [clmd->sim_parms->solver_type].free ( clmd );
641                 }
642
643                 // Free the verts.
644                 if ( cloth->verts != NULL )
645                         MEM_freeN ( cloth->verts );
646
647                 cloth->verts = NULL;
648                 cloth->numverts = 0;
649
650                 // Free the springs.
651                 if ( cloth->springs != NULL )
652                 {
653                         LinkNode *search = cloth->springs;
654                         while(search)
655                         {
656                                 ClothSpring *spring = search->link;
657                                                 
658                                 MEM_freeN ( spring );
659                                 search = search->next;
660                         }
661                         BLI_linklist_free(cloth->springs, NULL);
662                 
663                         cloth->springs = NULL;
664                 }
665
666                 cloth->springs = NULL;
667                 cloth->numsprings = 0;
668
669                 // free BVH collision tree
670                 if ( cloth->bvhtree )
671                         BLI_bvhtree_free ( cloth->bvhtree );
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, DerivedMesh *dm)
701 {
702         unsigned int    i = 0;
703         MVert *mvert = NULL;
704         unsigned int numverts;
705         Cloth *cloth = clmd->clothObject;
706
707         if (clmd->clothObject) {
708                 /* inverse matrix is not uptodate... */
709                 Mat4Invert (ob->imat, ob->obmat);
710
711                 mvert = CDDM_get_verts(dm);
712                 numverts = dm->getNumVerts(dm);
713
714                 for (i = 0; i < numverts; i++)
715                 {
716                         VECCOPY (mvert[i].co, cloth->verts[i].x);
717                         Mat4MulVecfl (ob->imat, mvert[i].co);   /* cloth is in global coords */
718                 }
719         }
720 }
721
722
723 /**
724  * cloth_apply_vgroup - applies a vertex group as specified by type
725  *
726  **/
727 /* can be optimized to do all groups in one loop */
728 static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm )
729 {
730         unsigned int i = 0;
731         unsigned int j = 0;
732         MDeformVert *dvert = NULL;
733         Cloth *clothObj = NULL;
734         unsigned int numverts = dm->getNumVerts ( dm );
735         float goalfac = 0;
736         ClothVertex *verts = NULL;
737
738         clothObj = clmd->clothObject;
739
740         if ( !dm )
741                 return;
742         
743         numverts = dm->getNumVerts ( dm );
744
745         verts = clothObj->verts;
746         
747         if (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || 
748                      (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) && 
749                      ((clmd->sim_parms->vgroup_mass>0) || 
750                      (clmd->sim_parms->vgroup_struct>0)||
751                      (clmd->sim_parms->vgroup_bend>0)))
752         {
753                 for ( i = 0; i < numverts; i++, verts++ )
754                 {       
755                         dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT );
756                         if ( dvert )
757                         {
758                                 for ( j = 0; j < dvert->totweight; j++ )
759                                 {
760                                         if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ))
761                                         {
762                                                 verts->goal = dvert->dw [j].weight;
763                                                 goalfac= 1.0f;
764                                                 
765                                                 /*
766                                                 // Kicking goal factor to simplify things...who uses that anyway?
767                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
768                                                 */
769                                                 
770                                                 verts->goal  = ( float ) pow ( verts->goal , 4.0f );
771                                                 if ( verts->goal >=SOFTGOALSNAP )
772                                                 {
773                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
774                                                 }
775                                         }
776                                         
777                                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING )
778                                         {
779                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1))
780                                                 {
781                                                         verts->struct_stiff = dvert->dw [j].weight;
782                                                         verts->shear_stiff = dvert->dw [j].weight;
783                                                 }
784                                                 
785                                                 if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1))
786                                                 {
787                                                         verts->bend_stiff = dvert->dw [j].weight;
788                                                 }
789                                         }
790                                         /*
791                                         // for later
792                                         if( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_weight-1))
793                                         {
794                                                 verts->mass = dvert->dw [j].weight;
795                                         }
796                                         */
797                                 }
798                         }
799                 }
800         }
801 }
802
803 static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *dm, float framenr, int first)
804 {
805         unsigned int i = 0;
806         MVert *mvert = NULL;
807         ClothVertex *verts = NULL;
808         float tnull[3] = {0,0,0};
809         Cloth *cloth = NULL;
810
811         // If we have a clothObject, free it. 
812         if ( clmd->clothObject != NULL )
813         {
814                 cloth_free_modifier ( ob, clmd );
815                 if(G.rt > 0)
816                         printf("cloth_free_modifier cloth_from_object\n");
817         }
818
819         // Allocate a new cloth object.
820         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
821         if ( clmd->clothObject )
822         {
823                 clmd->clothObject->old_solver_type = 255;
824                 // clmd->clothObject->old_collision_type = 255;
825                 cloth = clmd->clothObject;
826                 clmd->clothObject->edgehash = NULL;
827         }
828         else if ( !clmd->clothObject )
829         {
830                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject." );
831                 return 0;
832         }
833
834         // mesh input objects need DerivedMesh
835         if ( !dm )
836                 return 0;
837
838         cloth_from_mesh ( ob, clmd, dm );
839
840         // create springs 
841         clmd->clothObject->springs = NULL;
842         clmd->clothObject->numsprings = -1;
843         
844         mvert = dm->getVertArray ( dm );
845         verts = clmd->clothObject->verts;
846
847         // set initial values
848         for ( i = 0; i < dm->getNumVerts(dm); i++, verts++ )
849         {
850                 if(first)
851                 {
852                         VECCOPY ( verts->x, mvert[i].co );
853                         Mat4MulVecfl ( ob->obmat, verts->x );
854                 }
855                 
856                 /* no GUI interface yet */
857                 verts->mass = clmd->sim_parms->mass; 
858                 verts->impulse_count = 0;
859
860                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
861                         verts->goal= clmd->sim_parms->defgoal;
862                 else
863                         verts->goal= 0.0f;
864
865                 verts->flags = 0;
866                 VECCOPY ( verts->xold, verts->x );
867                 VECCOPY ( verts->xconst, verts->x );
868                 VECCOPY ( verts->txold, verts->x );
869                 VECCOPY ( verts->tx, verts->x );
870                 VecMulf ( verts->v, 0.0f );
871
872                 verts->impulse_count = 0;
873                 VECCOPY ( verts->impulse, tnull );
874         }
875         
876         // apply / set vertex groups
877         // has to be happen before springs are build!
878         cloth_apply_vgroup (clmd, dm);
879         
880         
881         if ( !cloth_build_springs ( clmd, dm ) )
882         {
883                 cloth_free_modifier ( ob, clmd );
884                 modifier_setError ( & ( clmd->modifier ), "Can't build springs." );
885                 printf("cloth_free_modifier cloth_build_springs\n");
886                 return 0;
887         }
888         
889         for ( i = 0; i < dm->getNumVerts(dm); i++)
890         {
891                 if((!(cloth->verts[i].flags & CLOTH_VERT_FLAG_PINNED)) && (cloth->verts[i].goal > ALMOST_ZERO))
892                 {
893                         cloth_add_spring (clmd, i, i, 0.0, CLOTH_SPRING_TYPE_GOAL);
894                 }
895         }
896         
897         // init our solver
898         if ( solvers [clmd->sim_parms->solver_type].init ) {
899                 solvers [clmd->sim_parms->solver_type].init ( ob, clmd );
900         }
901         
902         if(!first)
903                 implicit_set_positions(clmd);
904
905         BENCH(clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, clmd->coll_parms->epsilon ));
906         
907         return 1;
908 }
909
910 static void cloth_from_mesh ( Object *ob, ClothModifierData *clmd, DerivedMesh *dm )
911 {
912         unsigned int numverts = dm->getNumVerts ( dm );
913         unsigned int numfaces = dm->getNumFaces ( dm );
914         MFace *mface = CDDM_get_faces(dm);
915         unsigned int i = 0;
916
917         /* Allocate our vertices. */
918         clmd->clothObject->numverts = numverts;
919         clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" );
920         if ( clmd->clothObject->verts == NULL )
921         {
922                 cloth_free_modifier ( ob, clmd );
923                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->verts." );
924                 printf("cloth_free_modifier clmd->clothObject->verts\n");
925                 return;
926         }
927
928         // save face information
929         clmd->clothObject->numfaces = numfaces;
930         clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" );
931         if ( clmd->clothObject->mfaces == NULL )
932         {
933                 cloth_free_modifier ( ob, clmd );
934                 modifier_setError ( & ( clmd->modifier ), "Out of memory on allocating clmd->clothObject->mfaces." );
935                 printf("cloth_free_modifier clmd->clothObject->mfaces\n");
936                 return;
937         }
938         for ( i = 0; i < numfaces; i++ )
939                 memcpy ( &clmd->clothObject->mfaces[i], &mface[i], sizeof ( MFace ) );
940
941         /* Free the springs since they can't be correct if the vertices
942         * changed.
943         */
944         if ( clmd->clothObject->springs != NULL )
945                 MEM_freeN ( clmd->clothObject->springs );
946
947 }
948
949 /***************************************************************************************
950 * SPRING NETWORK BUILDING IMPLEMENTATION BEGIN
951 ***************************************************************************************/
952
953 // be carefull: implicit solver has to be resettet when using this one!
954 // --> only for implicit handling of this spring!
955 int cloth_add_spring ( ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type)
956 {
957         Cloth *cloth = clmd->clothObject;
958         ClothSpring *spring = NULL;
959         
960         if(cloth)
961         {
962                 // TODO: look if this spring is already there
963                 
964                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
965                 
966                 if(!spring)
967                         return 0;
968                 
969                 spring->ij = indexA;
970                 spring->kl = indexB;
971                 spring->restlen =  restlength;
972                 spring->type = spring_type;
973                 spring->flags = 0;
974                 spring->stiffness = 0;
975                 
976                 cloth->numsprings++;
977         
978                 BLI_linklist_prepend ( &cloth->springs, spring );
979                 
980                 return 1;
981         }
982         return 0;
983 }
984
985 void cloth_free_errorsprings(Cloth *cloth, EdgeHash *edgehash, LinkNode **edgelist)
986 {
987         unsigned int i = 0;
988         
989         if ( cloth->springs != NULL )
990         {
991                 LinkNode *search = cloth->springs;
992                 while(search)
993                 {
994                         ClothSpring *spring = search->link;
995                                                 
996                         MEM_freeN ( spring );
997                         search = search->next;
998                 }
999                 BLI_linklist_free(cloth->springs, NULL);
1000                 
1001                 cloth->springs = NULL;
1002         }
1003         
1004         if(edgelist)
1005         {
1006                 for ( i = 0; i < cloth->numverts; i++ )
1007                 {
1008                         BLI_linklist_free ( edgelist[i],NULL );
1009                 }
1010
1011                 MEM_freeN ( edgelist );
1012         }
1013         
1014         if(cloth->edgehash)
1015                 BLI_edgehash_free ( cloth->edgehash, NULL );
1016 }
1017
1018 int cloth_build_springs ( ClothModifierData *clmd, DerivedMesh *dm )
1019 {
1020         Cloth *cloth = clmd->clothObject;
1021         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1022         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0;
1023         unsigned int i = 0;
1024         unsigned int numverts = dm->getNumVerts ( dm );
1025         unsigned int numedges = dm->getNumEdges ( dm );
1026         unsigned int numfaces = dm->getNumFaces ( dm );
1027         MEdge *medge = CDDM_get_edges ( dm );
1028         MFace *mface = CDDM_get_faces ( dm );
1029         unsigned int index2 = 0; // our second vertex index
1030         LinkNode **edgelist = NULL;
1031         EdgeHash *edgehash = NULL;
1032         LinkNode *search = NULL, *search2 = NULL;
1033         float temp[3];
1034         
1035         // error handling
1036         if ( numedges==0 )
1037                 return 0;
1038
1039         cloth->springs = NULL;
1040
1041         edgelist = MEM_callocN ( sizeof ( LinkNode * ) * numverts, "cloth_edgelist_alloc" );
1042         
1043         if(!edgelist)
1044                 return 0;
1045         
1046         for ( i = 0; i < numverts; i++ )
1047         {
1048                 edgelist[i] = NULL;
1049         }
1050
1051         if ( cloth->springs )
1052                 MEM_freeN ( cloth->springs );
1053
1054         // create spring network hash
1055         edgehash = BLI_edgehash_new();
1056
1057         // structural springs
1058         for ( i = 0; i < numedges; i++ )
1059         {
1060                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1061
1062                 if ( spring )
1063                 {
1064                         spring->ij = MIN2(medge[i].v1, medge[i].v2);
1065                         spring->kl = MAX2(medge[i].v2, medge[i].v1);
1066                         VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1067                         spring->restlen =  sqrt ( INPR ( temp, temp ) );
1068                         clmd->sim_parms->avg_spring_len += spring->restlen;
1069                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1070                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1071                         cloth->verts[spring->ij].spring_count++;
1072                         cloth->verts[spring->kl].spring_count++;
1073                         spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1074                         spring->flags = 0;
1075                         spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0;
1076                         struct_springs++;
1077                         
1078                         BLI_linklist_prepend ( &cloth->springs, spring );
1079                 }
1080                 else
1081                 {
1082                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1083                         return 0;
1084                 }
1085         }
1086         
1087         if(struct_springs > 0)
1088                 clmd->sim_parms->avg_spring_len /= struct_springs;
1089         
1090         for(i = 0; i < numverts; i++)
1091         {
1092                 cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49 / ((float)cloth->verts[i].spring_count);
1093         }
1094         
1095         // shear springs
1096         for ( i = 0; i < numfaces; i++ )
1097         {
1098                 // triangle faces already have shear springs due to structural geometry
1099                 if ( !mface[i].v4 )
1100                         continue; 
1101                 
1102                 spring = ( ClothSpring *) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1103                 
1104                 if(!spring)
1105                 {
1106                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1107                         return 0;
1108                 }
1109
1110                 spring->ij = MIN2(mface[i].v1, mface[i].v3);
1111                 spring->kl = MAX2(mface[i].v3, mface[i].v1);
1112                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1113                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1114                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1115                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1116
1117                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1118                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1119                 shear_springs++;
1120
1121                 BLI_linklist_prepend ( &cloth->springs, spring );
1122
1123                 
1124                 // if ( mface[i].v4 ) --> Quad face
1125                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1126                 
1127                 if(!spring)
1128                 {
1129                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1130                         return 0;
1131                 }
1132
1133                 spring->ij = MIN2(mface[i].v2, mface[i].v4);
1134                 spring->kl = MAX2(mface[i].v4, mface[i].v2);
1135                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1136                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1137                 spring->type = CLOTH_SPRING_TYPE_SHEAR;
1138                 spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0;
1139
1140                 BLI_linklist_append ( &edgelist[spring->ij], spring );
1141                 BLI_linklist_append ( &edgelist[spring->kl], spring );
1142                 shear_springs++;
1143
1144                 BLI_linklist_prepend ( &cloth->springs, spring );
1145         }
1146         
1147         // bending springs
1148         search2 = cloth->springs;
1149         for ( i = struct_springs; i < struct_springs+shear_springs; i++ )
1150         {
1151                 if ( !search2 )
1152                         break;
1153
1154                 tspring2 = search2->link;
1155                 search = edgelist[tspring2->kl];
1156                 while ( search )
1157                 {
1158                         tspring = search->link;
1159                         index2 = ( ( tspring->ij==tspring2->kl ) ? ( tspring->kl ) : ( tspring->ij ) );
1160                         
1161                         // check for existing spring
1162                         // check also if startpoint is equal to endpoint
1163                         if ( !BLI_edgehash_haskey ( edgehash, MIN2(tspring2->ij, index2), MAX2(tspring2->ij, index2) )
1164                         && ( index2!=tspring2->ij ) )
1165                         {
1166                                 spring = ( ClothSpring * ) MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1167                                 
1168                                 if(!spring)
1169                                 {
1170                                         cloth_free_errorsprings(cloth, edgehash, edgelist);
1171                                         return 0;
1172                                 }
1173
1174                                 spring->ij = MIN2(tspring2->ij, index2);
1175                                 spring->kl = MAX2(tspring2->ij, index2);
1176                                 VECSUB ( temp, cloth->verts[spring->kl].x, cloth->verts[spring->ij].x );
1177                                 spring->restlen =  sqrt ( INPR ( temp, temp ) );
1178                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1179                                 spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0;
1180                                 BLI_edgehash_insert ( edgehash, spring->ij, spring->kl, NULL );
1181                                 bend_springs++;
1182
1183                                 BLI_linklist_prepend ( &cloth->springs, spring );
1184                         }
1185                         search = search->next;
1186                 }
1187                 search2 = search2->next;
1188         }
1189         
1190         /* insert other near springs in edgehash AFTER bending springs are calculated (for selfcolls) */
1191         for ( i = 0; i < numedges; i++ ) // struct springs
1192                 BLI_edgehash_insert ( edgehash, MIN2(medge[i].v1, medge[i].v2), MAX2(medge[i].v2, medge[i].v1), NULL );
1193         
1194         for ( i = 0; i < numfaces; i++ ) // edge springs
1195         {
1196                 if(mface[i].v4)
1197                 {
1198                         BLI_edgehash_insert ( edgehash, MIN2(mface[i].v1, mface[i].v3), MAX2(mface[i].v3, mface[i].v1), NULL );
1199                         
1200                         BLI_edgehash_insert ( edgehash, MIN2(mface[i].v2, mface[i].v4), MAX2(mface[i].v2, mface[i].v4), NULL );
1201                 }
1202         }
1203         
1204         
1205         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1206         
1207         if ( edgelist )
1208         {
1209                 for ( i = 0; i < numverts; i++ )
1210                 {
1211                         BLI_linklist_free ( edgelist[i],NULL );
1212                 }
1213         
1214                 MEM_freeN ( edgelist );
1215         }
1216         
1217         cloth->edgehash = edgehash;
1218         
1219         if(G.rt>0)
1220                 printf("avg_len: %f\n",clmd->sim_parms->avg_spring_len);
1221
1222         return 1;
1223
1224 } /* cloth_build_springs */
1225 /***************************************************************************************
1226 * SPRING NETWORK BUILDING IMPLEMENTATION END
1227 ***************************************************************************************/
1228