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