Merge branch 'blender2.7'
[blender.git] / source / blender / blenkernel / intern / cloth.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Genrich
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/cloth.c
27  *  \ingroup bke
28  */
29
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_cloth_types.h"
34 #include "DNA_scene_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_meshdata_types.h"
38
39 #include "BLI_utildefines.h"
40 #include "BLI_math.h"
41 #include "BLI_edgehash.h"
42 #include "BLI_linklist.h"
43
44 #include "DEG_depsgraph.h"
45 #include "DEG_depsgraph_query.h"
46
47 #include "BKE_bvhutils.h"
48 #include "BKE_cloth.h"
49 #include "BKE_effect.h"
50 #include "BKE_global.h"
51 #include "BKE_mesh_runtime.h"
52 #include "BKE_modifier.h"
53 #include "BKE_pointcache.h"
54
55 #include "BPH_mass_spring.h"
56
57 // #include "PIL_time.h"  /* timing for debug prints */
58
59 /* ********** cloth engine ******* */
60 /* Prototypes for internal functions.
61  */
62 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3]);
63 static void cloth_from_mesh ( ClothModifierData *clmd, Mesh *mesh );
64 static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, float framenr, int first);
65 static void cloth_update_springs( ClothModifierData *clmd );
66 static void cloth_update_verts( Object *ob, ClothModifierData *clmd, Mesh *mesh );
67 static void cloth_update_spring_lengths( ClothModifierData *clmd, Mesh *mesh );
68 static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh );
69 static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh );
70
71 typedef struct BendSpringRef {
72         int index;
73         int polys;
74         ClothSpring *spring;
75 } BendSpringRef;
76
77 /******************************************************************************
78  *
79  * External interface called by modifier.c clothModifier functions.
80  *
81  ******************************************************************************/
82 /**
83  * cloth_init - creates a new cloth simulation.
84  *
85  * 1. create object
86  * 2. fill object with standard values or with the GUI settings if given
87  */
88 void cloth_init(ClothModifierData *clmd )
89 {
90         /* Initialize our new data structure to reasonable values. */
91         clmd->sim_parms->gravity[0] = 0.0;
92         clmd->sim_parms->gravity[1] = 0.0;
93         clmd->sim_parms->gravity[2] = -9.81;
94         clmd->sim_parms->tension = 15.0;
95         clmd->sim_parms->max_tension = 15.0;
96         clmd->sim_parms->compression = 15.0;
97         clmd->sim_parms->max_compression = 15.0;
98         clmd->sim_parms->shear = 5.0;
99         clmd->sim_parms->max_shear = 5.0;
100         clmd->sim_parms->bending = 0.5;
101         clmd->sim_parms->max_bend = 0.5;
102         clmd->sim_parms->tension_damp = 5.0;
103         clmd->sim_parms->compression_damp = 5.0;
104         clmd->sim_parms->shear_damp = 5.0;
105         clmd->sim_parms->bending_damping = 0.5;
106         clmd->sim_parms->Cvi = 1.0;
107         clmd->sim_parms->mass = 0.3f;
108         clmd->sim_parms->stepsPerFrame = 5;
109         clmd->sim_parms->flags = 0;
110         clmd->sim_parms->solver_type = 0;
111         clmd->sim_parms->maxspringlen = 10;
112         clmd->sim_parms->vgroup_mass = 0;
113         clmd->sim_parms->vgroup_shrink = 0;
114         clmd->sim_parms->shrink_min = 0.0f; /* min amount the fabric will shrink by 0.0 = no shrinking, 1.0 = shrink to nothing*/
115         clmd->sim_parms->avg_spring_len = 0.0;
116         clmd->sim_parms->presets = 2; /* cotton as start setting */
117         clmd->sim_parms->timescale = 1.0f; /* speed factor, describes how fast cloth moves */
118         clmd->sim_parms->time_scale = 1.0f; /* multiplies cloth speed */
119         clmd->sim_parms->reset = 0;
120
121         clmd->coll_parms->self_friction = 5.0;
122         clmd->coll_parms->friction = 5.0;
123         clmd->coll_parms->loop_count = 2;
124         clmd->coll_parms->epsilon = 0.015f;
125         clmd->coll_parms->flags = CLOTH_COLLSETTINGS_FLAG_ENABLED;
126         clmd->coll_parms->collision_list = NULL;
127         clmd->coll_parms->selfepsilon = 0.015;
128         clmd->coll_parms->vgroup_selfcol = 0;
129
130         /* These defaults are copied from softbody.c's
131          * softbody_calc_forces() function.
132          */
133         clmd->sim_parms->eff_force_scale = 1000.0;
134         clmd->sim_parms->eff_wind_scale = 250.0;
135
136         // also from softbodies
137         clmd->sim_parms->maxgoal = 1.0f;
138         clmd->sim_parms->mingoal = 0.0f;
139         clmd->sim_parms->defgoal = 0.0f;
140         clmd->sim_parms->goalspring = 1.0f;
141         clmd->sim_parms->goalfrict = 0.0f;
142         clmd->sim_parms->velocity_smooth = 0.0f;
143
144         clmd->sim_parms->voxel_cell_size = 0.1f;
145
146         clmd->sim_parms->bending_model = CLOTH_BENDING_ANGULAR;
147
148         if (!clmd->sim_parms->effector_weights)
149                 clmd->sim_parms->effector_weights = BKE_effector_add_weights(NULL);
150
151         if (clmd->point_cache)
152                 clmd->point_cache->step = 1;
153 }
154
155 static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon)
156 {
157         unsigned int i;
158         BVHTree *bvhtree;
159         Cloth *cloth;
160         ClothVertex *verts;
161         const MVertTri *vt;
162
163         if (!clmd)
164                 return NULL;
165
166         cloth = clmd->clothObject;
167
168         if (!cloth)
169                 return NULL;
170
171         verts = cloth->verts;
172         vt = cloth->tri;
173
174         /* in the moment, return zero if no faces there */
175         if (!cloth->tri_num)
176                 return NULL;
177
178         /* create quadtree with k=26 */
179         bvhtree = BLI_bvhtree_new(cloth->tri_num, epsilon, 4, 26);
180
181         /* fill tree */
182         for (i = 0; i < cloth->tri_num; i++, vt++) {
183                 float co[3][3];
184
185                 copy_v3_v3(co[0], verts[vt->tri[0]].xold);
186                 copy_v3_v3(co[1], verts[vt->tri[1]].xold);
187                 copy_v3_v3(co[2], verts[vt->tri[2]].xold);
188
189                 BLI_bvhtree_insert(bvhtree, i, co[0], 3);
190         }
191
192         /* balance tree */
193         BLI_bvhtree_balance(bvhtree);
194
195         return bvhtree;
196 }
197
198 void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving, bool self)
199 {
200         unsigned int i = 0;
201         Cloth *cloth = clmd->clothObject;
202         BVHTree *bvhtree;
203         ClothVertex *verts = cloth->verts;
204         const MVertTri *vt;
205
206         if (self) {
207                 bvhtree = cloth->bvhselftree;
208         }
209         else {
210                 bvhtree = cloth->bvhtree;
211         }
212
213         if (!bvhtree)
214                 return;
215
216         vt = cloth->tri;
217
218         /* update vertex position in bvh tree */
219         if (verts && vt) {
220                 for (i = 0; i < cloth->tri_num; i++, vt++) {
221                         float co[3][3], co_moving[3][3];
222                         bool ret;
223
224                         /* copy new locations into array */
225                         if (moving) {
226                                 copy_v3_v3(co[0], verts[vt->tri[0]].txold);
227                                 copy_v3_v3(co[1], verts[vt->tri[1]].txold);
228                                 copy_v3_v3(co[2], verts[vt->tri[2]].txold);
229
230                                 /* update moving positions */
231                                 copy_v3_v3(co_moving[0], verts[vt->tri[0]].tx);
232                                 copy_v3_v3(co_moving[1], verts[vt->tri[1]].tx);
233                                 copy_v3_v3(co_moving[2], verts[vt->tri[2]].tx);
234
235                                 ret = BLI_bvhtree_update_node(bvhtree, i, co[0], co_moving[0], 3);
236                         }
237                         else {
238                                 copy_v3_v3(co[0], verts[vt->tri[0]].tx);
239                                 copy_v3_v3(co[1], verts[vt->tri[1]].tx);
240                                 copy_v3_v3(co[2], verts[vt->tri[2]].tx);
241
242                                 ret = BLI_bvhtree_update_node(bvhtree, i, co[0], NULL, 3);
243                         }
244
245                         /* check if tree is already full */
246                         if (ret == false) {
247                                 break;
248                         }
249                 }
250
251                 BLI_bvhtree_update_tree(bvhtree);
252         }
253 }
254
255 void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr)
256 {
257         PTCacheID pid;
258
259         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
260
261         // don't do anything as long as we're in editmode!
262         if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT)
263                 return;
264
265         BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr);
266 }
267
268 static int do_init_cloth(Object *ob, ClothModifierData *clmd, Mesh *result, int framenr)
269 {
270         PointCache *cache;
271
272         cache= clmd->point_cache;
273
274         /* initialize simulation data if it didn't exist already */
275         if (clmd->clothObject == NULL) {
276                 if (!cloth_from_object(ob, clmd, result, framenr, 1)) {
277                         BKE_ptcache_invalidate(cache);
278                         modifier_setError(&(clmd->modifier), "Can't initialize cloth");
279                         return 0;
280                 }
281
282                 if (clmd->clothObject == NULL) {
283                         BKE_ptcache_invalidate(cache);
284                         modifier_setError(&(clmd->modifier), "Null cloth object");
285                         return 0;
286                 }
287
288                 BKE_cloth_solver_set_positions(clmd);
289
290                 clmd->clothObject->last_frame= MINFRAME-1;
291                 clmd->sim_parms->dt = 1.0f / clmd->sim_parms->stepsPerFrame;
292         }
293
294         return 1;
295 }
296
297 static int do_step_cloth(Depsgraph *depsgraph, Object *ob, ClothModifierData *clmd, Mesh *result, int framenr)
298 {
299         ClothVertex *verts = NULL;
300         Cloth *cloth;
301         ListBase *effectors = NULL;
302         MVert *mvert;
303         unsigned int i = 0;
304         int ret = 0;
305
306         /* simulate 1 frame forward */
307         cloth = clmd->clothObject;
308         verts = cloth->verts;
309         mvert = result->mvert;
310
311         /* force any pinned verts to their constrained location. */
312         for (i = 0; i < clmd->clothObject->mvert_num; i++, verts++) {
313                 /* save the previous position. */
314                 copy_v3_v3(verts->xold, verts->xconst);
315                 copy_v3_v3(verts->txold, verts->x);
316
317                 /* Get the current position. */
318                 copy_v3_v3(verts->xconst, mvert[i].co);
319                 mul_m4_v3(ob->obmat, verts->xconst);
320         }
321
322         effectors = BKE_effectors_create(depsgraph, ob, NULL, clmd->sim_parms->effector_weights);
323
324         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH )
325                 cloth_update_verts ( ob, clmd, result );
326
327         /* Support for dynamic vertex groups, changing from frame to frame */
328         cloth_apply_vgroup ( clmd, result );
329
330         if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH) ||
331             (clmd->sim_parms->vgroup_shrink > 0) || (clmd->sim_parms->shrink_min > 0.0f))
332         {
333                 cloth_update_spring_lengths ( clmd, result );
334         }
335
336         cloth_update_springs( clmd );
337
338         // TIMEIT_START(cloth_step)
339
340         /* call the solver. */
341         ret = BPH_cloth_solve(depsgraph, ob, framenr, clmd, effectors);
342
343         // TIMEIT_END(cloth_step)
344
345         BKE_effectors_free(effectors);
346
347         // printf ( "%f\n", ( float ) tval() );
348
349         return ret;
350 }
351
352 /************************************************
353  * clothModifier_do - main simulation function
354  ************************************************/
355 void clothModifier_do(ClothModifierData *clmd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *mesh, float (*vertexCos)[3])
356 {
357         PointCache *cache;
358         PTCacheID pid;
359         float timescale;
360         int framenr, startframe, endframe;
361         int cache_result;
362
363         framenr = DEG_get_ctime(depsgraph);
364         cache= clmd->point_cache;
365
366         BKE_ptcache_id_from_cloth(&pid, ob, clmd);
367         BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, &timescale);
368         clmd->sim_parms->timescale= timescale * clmd->sim_parms->time_scale;
369
370         if (clmd->sim_parms->reset || (clmd->clothObject && mesh->totvert != clmd->clothObject->mvert_num)) {
371                 clmd->sim_parms->reset = 0;
372                 cache->flag |= PTCACHE_OUTDATED;
373                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
374                 BKE_ptcache_validate(cache, 0);
375                 cache->last_exact= 0;
376                 cache->flag &= ~PTCACHE_REDO_NEEDED;
377         }
378
379         /* simulation is only active during a specific period */
380         if (framenr < startframe) {
381                 BKE_ptcache_invalidate(cache);
382                 return;
383         }
384         else if (framenr > endframe) {
385                 framenr= endframe;
386         }
387
388         /* initialize simulation data if it didn't exist already */
389         if (!do_init_cloth(ob, clmd, mesh, framenr))
390                 return;
391
392         if (framenr == startframe) {
393                 BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED);
394                 do_init_cloth(ob, clmd, mesh, framenr);
395                 BKE_ptcache_validate(cache, framenr);
396                 cache->flag &= ~PTCACHE_REDO_NEEDED;
397                 clmd->clothObject->last_frame= framenr;
398                 return;
399         }
400
401         /* try to read from cache */
402         bool can_simulate = (framenr == clmd->clothObject->last_frame+1) && !(cache->flag & PTCACHE_BAKED);
403
404         cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe, can_simulate);
405
406         if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED ||
407             (!can_simulate && cache_result == PTCACHE_READ_OLD))
408         {
409                 BKE_cloth_solver_set_positions(clmd);
410                 cloth_to_object (ob, clmd, vertexCos);
411
412                 BKE_ptcache_validate(cache, framenr);
413
414                 if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED)
415                         BKE_ptcache_write(&pid, framenr);
416
417                 clmd->clothObject->last_frame= framenr;
418
419                 return;
420         }
421         else if (cache_result==PTCACHE_READ_OLD) {
422                 BKE_cloth_solver_set_positions(clmd);
423         }
424         else if ( /*ob->id.lib ||*/ (cache->flag & PTCACHE_BAKED)) { /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */
425                 /* if baked and nothing in cache, do nothing */
426                 BKE_ptcache_invalidate(cache);
427                 return;
428         }
429
430         /* if on second frame, write cache for first frame */
431         if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0))
432                 BKE_ptcache_write(&pid, startframe);
433
434         clmd->sim_parms->timescale *= framenr - cache->simframe;
435
436         /* do simulation */
437         BKE_ptcache_validate(cache, framenr);
438
439         if (!do_step_cloth(depsgraph, ob, clmd, mesh, framenr)) {
440                 BKE_ptcache_invalidate(cache);
441         }
442         else
443                 BKE_ptcache_write(&pid, framenr);
444
445         cloth_to_object (ob, clmd, vertexCos);
446         clmd->clothObject->last_frame= framenr;
447 }
448
449 /* frees all */
450 void cloth_free_modifier(ClothModifierData *clmd )
451 {
452         Cloth   *cloth = NULL;
453
454         if ( !clmd )
455                 return;
456
457         cloth = clmd->clothObject;
458
459
460         if ( cloth ) {
461                 BPH_cloth_solver_free(clmd);
462
463                 // Free the verts.
464                 if ( cloth->verts != NULL )
465                         MEM_freeN ( cloth->verts );
466
467                 cloth->verts = NULL;
468                 cloth->mvert_num = 0;
469
470                 // Free the springs.
471                 if ( cloth->springs != NULL ) {
472                         LinkNode *search = cloth->springs;
473                         while (search) {
474                                 ClothSpring *spring = search->link;
475
476                                 MEM_SAFE_FREE(spring->pa);
477                                 MEM_SAFE_FREE(spring->pb);
478
479                                 MEM_freeN ( spring );
480                                 search = search->next;
481                         }
482                         BLI_linklist_free(cloth->springs, NULL);
483
484                         cloth->springs = NULL;
485                 }
486
487                 cloth->springs = NULL;
488                 cloth->numsprings = 0;
489
490                 // free BVH collision tree
491                 if ( cloth->bvhtree )
492                         BLI_bvhtree_free ( cloth->bvhtree );
493
494                 if ( cloth->bvhselftree )
495                         BLI_bvhtree_free ( cloth->bvhselftree );
496
497                 // we save our faces for collision objects
498                 if (cloth->tri)
499                         MEM_freeN(cloth->tri);
500
501                 if (cloth->edgeset)
502                         BLI_edgeset_free(cloth->edgeset);
503
504 #if 0
505                 if (clmd->clothObject->facemarks) {
506                         MEM_freeN(clmd->clothObject->facemarks);
507                 }
508 #endif
509                 MEM_freeN ( cloth );
510                 clmd->clothObject = NULL;
511         }
512 }
513
514 /* frees all */
515 void cloth_free_modifier_extern(ClothModifierData *clmd )
516 {
517         Cloth   *cloth = NULL;
518         if (G.debug_value > 0)
519                 printf("cloth_free_modifier_extern\n");
520
521         if ( !clmd )
522                 return;
523
524         cloth = clmd->clothObject;
525
526         if ( cloth ) {
527                 if (G.debug_value > 0)
528                         printf("cloth_free_modifier_extern in\n");
529
530                 BPH_cloth_solver_free(clmd);
531
532                 // Free the verts.
533                 if ( cloth->verts != NULL )
534                         MEM_freeN ( cloth->verts );
535
536                 cloth->verts = NULL;
537                 cloth->mvert_num = 0;
538
539                 // Free the springs.
540                 if ( cloth->springs != NULL ) {
541                         LinkNode *search = cloth->springs;
542                         while (search) {
543                                 ClothSpring *spring = search->link;
544
545                                 MEM_SAFE_FREE(spring->pa);
546                                 MEM_SAFE_FREE(spring->pb);
547
548                                 MEM_freeN ( spring );
549                                 search = search->next;
550                         }
551                         BLI_linklist_free(cloth->springs, NULL);
552
553                         cloth->springs = NULL;
554                 }
555
556                 cloth->springs = NULL;
557                 cloth->numsprings = 0;
558
559                 // free BVH collision tree
560                 if ( cloth->bvhtree )
561                         BLI_bvhtree_free ( cloth->bvhtree );
562
563                 if ( cloth->bvhselftree )
564                         BLI_bvhtree_free ( cloth->bvhselftree );
565
566                 // we save our faces for collision objects
567                 if (cloth->tri)
568                         MEM_freeN(cloth->tri);
569
570                 if (cloth->edgeset)
571                         BLI_edgeset_free(cloth->edgeset);
572
573
574 #if 0
575                 if (clmd->clothObject->facemarks) {
576                         MEM_freeN(clmd->clothObject->facemarks);
577                 }
578 #endif
579                 MEM_freeN ( cloth );
580                 clmd->clothObject = NULL;
581         }
582 }
583
584 /******************************************************************************
585  *
586  * Internal functions.
587  *
588  ******************************************************************************/
589
590 /**
591  * cloth_to_object - copies the deformed vertices to the object.
592  *
593  **/
594 static void cloth_to_object (Object *ob,  ClothModifierData *clmd, float (*vertexCos)[3])
595 {
596         unsigned int i = 0;
597         Cloth *cloth = clmd->clothObject;
598
599         if (clmd->clothObject) {
600                 /* inverse matrix is not uptodate... */
601                 invert_m4_m4(ob->imat, ob->obmat);
602
603                 for (i = 0; i < cloth->mvert_num; i++) {
604                         copy_v3_v3 (vertexCos[i], cloth->verts[i].x);
605                         mul_m4_v3(ob->imat, vertexCos[i]);      /* cloth is in global coords */
606                 }
607         }
608 }
609
610
611 int cloth_uses_vgroup(ClothModifierData *clmd)
612 {
613         return (((clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF) && (clmd->coll_parms->vgroup_selfcol > 0)) ||
614                 (clmd->sim_parms->vgroup_struct > 0) ||
615                 (clmd->sim_parms->vgroup_bend > 0) ||
616                 (clmd->sim_parms->vgroup_shrink > 0) ||
617                 (clmd->sim_parms->vgroup_mass > 0));
618 }
619
620 /**
621  * cloth_apply_vgroup - applies a vertex group as specified by type
622  *
623  **/
624 /* can be optimized to do all groups in one loop */
625 static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh )
626 {
627         int i = 0;
628         int j = 0;
629         MDeformVert *dvert = NULL;
630         Cloth *clothObj = NULL;
631         int mvert_num;
632         /* float goalfac = 0; */ /* UNUSED */
633         ClothVertex *verts = NULL;
634
635         if (!clmd || !mesh) return;
636
637         clothObj = clmd->clothObject;
638
639         mvert_num = mesh->totvert;
640
641         verts = clothObj->verts;
642
643         if (cloth_uses_vgroup(clmd)) {
644                 for (i = 0; i < mvert_num; i++, verts++) {
645
646                         /* Reset Goal values to standard */
647                         if (clmd->sim_parms->vgroup_mass > 0)
648                                 verts->goal= clmd->sim_parms->defgoal;
649                         else
650                                 verts->goal= 0.0f;
651
652                         /* Compute base cloth shrink weight */
653                         verts->shrink_factor = 0.0f;
654
655                         /* Reset vertex flags */
656                         verts->flags &= ~CLOTH_VERT_FLAG_PINNED;
657                         verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL;
658
659                         dvert = CustomData_get(&mesh->vdata, i, CD_MDEFORMVERT);
660                         if ( dvert ) {
661                                 for ( j = 0; j < dvert->totweight; j++ ) {
662                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass - 1)) {
663                                                 verts->goal = dvert->dw [j].weight;
664
665                                                 /* goalfac= 1.0f; */ /* UNUSED */
666
667                                                 // Kicking goal factor to simplify things...who uses that anyway?
668                                                 // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal );
669
670                                                 verts->goal  = pow4f(verts->goal);
671                                                 if ( verts->goal >= SOFTGOALSNAP )
672                                                         verts->flags |= CLOTH_VERT_FLAG_PINNED;
673                                         }
674
675                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct - 1)) {
676                                                 verts->struct_stiff = dvert->dw[j].weight;
677                                         }
678
679                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_shear - 1)) {
680                                                 verts->shear_stiff = dvert->dw[j].weight;
681                                         }
682
683                                         if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend - 1)) {
684                                                 verts->bend_stiff = dvert->dw[j].weight;
685                                         }
686
687                                         if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
688                                                 if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) {
689                                                         if (dvert->dw [j].weight > 0.0f) {
690                                                                 verts->flags |= CLOTH_VERT_FLAG_NOSELFCOLL;
691                                                         }
692                                                 }
693                                         }
694                                         if (clmd->sim_parms->vgroup_shrink > 0) {
695                                                 if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_shrink - 1)) {
696                                                         /* Used for linear interpolation between min and max shrink factor based on weight. */
697                                                         verts->shrink_factor = dvert->dw[j].weight;
698                                                 }
699                                         }
700                                 }
701                         }
702                 }
703         }
704 }
705
706 static float cloth_shrink_factor(ClothModifierData *clmd, ClothVertex *verts, int i1, int i2)
707 {
708         /* Linear interpolation between min and max shrink factor based on weight. */
709         float base = 1.0f - clmd->sim_parms->shrink_min;
710         float delta = clmd->sim_parms->shrink_min - clmd->sim_parms->shrink_max;
711
712         float k1 = base + delta * verts[i1].shrink_factor;
713         float k2 = base + delta * verts[i2].shrink_factor;
714
715         /* Use geometrical mean to average two factors since it behaves better
716            for diagonals when a rectangle transforms into a trapezoid. */
717         return sqrtf(k1 * k2);
718 }
719
720 static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, float UNUSED(framenr), int first)
721 {
722         int i = 0;
723         MVert *mvert = NULL;
724         ClothVertex *verts = NULL;
725         float (*shapekey_rest)[3] = NULL;
726         float tnull[3] = {0, 0, 0};
727
728         // If we have a clothObject, free it.
729         if ( clmd->clothObject != NULL ) {
730                 cloth_free_modifier ( clmd );
731                 if (G.debug_value > 0)
732                         printf("cloth_free_modifier cloth_from_object\n");
733         }
734
735         // Allocate a new cloth object.
736         clmd->clothObject = MEM_callocN ( sizeof ( Cloth ), "cloth" );
737         if ( clmd->clothObject ) {
738                 clmd->clothObject->old_solver_type = 255;
739                 clmd->clothObject->edgeset = NULL;
740         }
741         else if (!clmd->clothObject) {
742                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject");
743                 return 0;
744         }
745
746         // mesh input objects need Mesh
747         if ( !mesh )
748                 return 0;
749
750         cloth_from_mesh ( clmd, mesh );
751
752         // create springs
753         clmd->clothObject->springs = NULL;
754         clmd->clothObject->numsprings = -1;
755
756         if ( clmd->sim_parms->shapekey_rest && !(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH ) )
757                 shapekey_rest = CustomData_get_layer(&mesh->vdata, CD_CLOTH_ORCO);
758
759         mvert = mesh->mvert;
760
761         verts = clmd->clothObject->verts;
762
763         // set initial values
764         for ( i = 0; i < mesh->totvert; i++, verts++ ) {
765                 if (first) {
766                         copy_v3_v3(verts->x, mvert[i].co);
767
768                         mul_m4_v3(ob->obmat, verts->x);
769
770                         if ( shapekey_rest ) {
771                                 copy_v3_v3(verts->xrest, shapekey_rest[i]);
772                                 mul_m4_v3(ob->obmat, verts->xrest);
773                         }
774                         else
775                                 copy_v3_v3(verts->xrest, verts->x);
776                 }
777
778                 /* no GUI interface yet */
779                 verts->mass = clmd->sim_parms->mass;
780                 verts->impulse_count = 0;
781
782                 if (clmd->sim_parms->vgroup_mass > 0)
783                         verts->goal= clmd->sim_parms->defgoal;
784                 else
785                         verts->goal= 0.0f;
786
787                 verts->shrink_factor = 0.0f;
788
789                 verts->flags = 0;
790                 copy_v3_v3 ( verts->xold, verts->x );
791                 copy_v3_v3 ( verts->xconst, verts->x );
792                 copy_v3_v3 ( verts->txold, verts->x );
793                 copy_v3_v3 ( verts->tx, verts->x );
794                 mul_v3_fl(verts->v, 0.0f);
795
796                 verts->impulse_count = 0;
797                 copy_v3_v3 ( verts->impulse, tnull );
798         }
799
800         // apply / set vertex groups
801         // has to be happen before springs are build!
802         cloth_apply_vgroup (clmd, mesh);
803
804         if ( !cloth_build_springs ( clmd, mesh ) ) {
805                 cloth_free_modifier ( clmd );
806                 modifier_setError(&(clmd->modifier), "Cannot build springs");
807                 return 0;
808         }
809
810         // init our solver
811         BPH_cloth_solver_init(ob, clmd);
812
813         if (!first)
814                 BKE_cloth_solver_set_positions(clmd);
815
816         clmd->clothObject->bvhtree = bvhtree_build_from_cloth (clmd, clmd->coll_parms->epsilon);
817         clmd->clothObject->bvhselftree = bvhtree_build_from_cloth(clmd, clmd->coll_parms->selfepsilon);
818
819         return 1;
820 }
821
822 static void cloth_from_mesh ( ClothModifierData *clmd, Mesh *mesh )
823 {
824         const MLoop *mloop = mesh->mloop;
825         const MLoopTri *looptri = BKE_mesh_runtime_looptri_ensure(mesh);
826         const unsigned int mvert_num = mesh->totvert;
827         const unsigned int looptri_num = mesh->runtime.looptris.len;
828
829         /* Allocate our vertices. */
830         clmd->clothObject->mvert_num = mvert_num;
831         clmd->clothObject->verts = MEM_callocN(sizeof(ClothVertex) * clmd->clothObject->mvert_num, "clothVertex");
832         if (clmd->clothObject->verts == NULL) {
833                 cloth_free_modifier(clmd);
834                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
835                 printf("cloth_free_modifier clmd->clothObject->verts\n");
836                 return;
837         }
838
839         /* save face information */
840         clmd->clothObject->tri_num = looptri_num;
841         clmd->clothObject->tri = MEM_mallocN(sizeof(MVertTri) * looptri_num, "clothLoopTris");
842         if (clmd->clothObject->tri == NULL) {
843                 cloth_free_modifier(clmd);
844                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->looptri");
845                 printf("cloth_free_modifier clmd->clothObject->looptri\n");
846                 return;
847         }
848         BKE_mesh_runtime_verttri_from_looptri(clmd->clothObject->tri, mloop, looptri, looptri_num);
849
850         /* Free the springs since they can't be correct if the vertices
851          * changed.
852          */
853         if ( clmd->clothObject->springs != NULL )
854                 MEM_freeN ( clmd->clothObject->springs );
855
856 }
857
858 /***************************************************************************************
859  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION BEGIN
860  ***************************************************************************************/
861
862 BLI_INLINE void spring_verts_ordered_set(ClothSpring *spring, int v0, int v1)
863 {
864         if (v0 < v1) {
865                 spring->ij = v0;
866                 spring->kl = v1;
867         }
868         else {
869                 spring->ij = v1;
870                 spring->kl = v0;
871         }
872 }
873
874 static void cloth_free_edgelist(LinkNodePair *edgelist, unsigned int mvert_num)
875 {
876         if (edgelist) {
877                 unsigned int i;
878                 for (i = 0; i < mvert_num; i++) {
879                         BLI_linklist_free(edgelist[i].list, NULL);
880                 }
881
882                 MEM_freeN(edgelist);
883         }
884 }
885
886 static void cloth_free_errorsprings(Cloth *cloth, LinkNodePair *edgelist, BendSpringRef *spring_ref)
887 {
888         if ( cloth->springs != NULL ) {
889                 LinkNode *search = cloth->springs;
890                 while (search) {
891                         ClothSpring *spring = search->link;
892
893                         MEM_SAFE_FREE(spring->pa);
894                         MEM_SAFE_FREE(spring->pb);
895
896                         MEM_freeN ( spring );
897                         search = search->next;
898                 }
899                 BLI_linklist_free(cloth->springs, NULL);
900
901                 cloth->springs = NULL;
902         }
903
904         cloth_free_edgelist(edgelist, cloth->mvert_num);
905
906         MEM_SAFE_FREE(spring_ref);
907
908         if (cloth->edgeset) {
909                 BLI_edgeset_free(cloth->edgeset);
910                 cloth->edgeset = NULL;
911         }
912 }
913
914 BLI_INLINE void cloth_bend_poly_dir(ClothVertex *verts, int i, int j, int *inds, int len, float r_dir[3])
915 {
916         float cent[3] = {0};
917         float fact = 1.0f / len;
918
919         for (int x = 0; x < len; x++) {
920                 madd_v3_v3fl(cent, verts[inds[x]].xrest, fact);
921         }
922
923         normal_tri_v3(r_dir, verts[i].xrest, verts[j].xrest, cent);
924 }
925
926 static float cloth_spring_angle(ClothVertex *verts, int i, int j, int *i_a, int *i_b, int len_a, int len_b)
927 {
928         float dir_a[3], dir_b[3];
929         float tmp[3], vec_e[3];
930         float sin, cos;
931
932         /* Poly vectors. */
933         cloth_bend_poly_dir(verts, j, i, i_a, len_a, dir_a);
934         cloth_bend_poly_dir(verts, i, j, i_b, len_b, dir_b);
935
936         /* Edge vector. */
937         sub_v3_v3v3(vec_e, verts[i].xrest, verts[j].xrest);
938         normalize_v3(vec_e);
939
940         /* Compute angle. */
941         cos = dot_v3v3(dir_a, dir_b);
942
943         cross_v3_v3v3(tmp, dir_a, dir_b);
944         sin = dot_v3v3(tmp, vec_e);
945
946         return atan2f(sin, cos);
947 }
948
949 static void cloth_hair_update_bending_targets(ClothModifierData *clmd)
950 {
951         Cloth *cloth = clmd->clothObject;
952         LinkNode *search = NULL;
953         float hair_frame[3][3], dir_old[3], dir_new[3];
954         int prev_mn; /* to find hair chains */
955
956         if (!clmd->hairdata)
957                 return;
958
959         /* XXX Note: we need to propagate frames from the root up,
960          * but structural hair springs are stored in reverse order.
961          * The bending springs however are then inserted in the same
962          * order as vertices again ...
963          * This messy situation can be resolved when solver data is
964          * generated directly from a dedicated hair system.
965          */
966
967         prev_mn = -1;
968         for (search = cloth->springs; search; search = search->next) {
969                 ClothSpring *spring = search->link;
970                 ClothHairData *hair_ij, *hair_kl;
971                 bool is_root = spring->kl != prev_mn;
972
973                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
974                         continue;
975                 }
976
977                 hair_ij = &clmd->hairdata[spring->ij];
978                 hair_kl = &clmd->hairdata[spring->kl];
979                 if (is_root) {
980                         /* initial hair frame from root orientation */
981                         copy_m3_m3(hair_frame, hair_ij->rot);
982                         /* surface normal is the initial direction,
983                          * parallel transport then keeps it aligned to the hair direction
984                          */
985                         copy_v3_v3(dir_new, hair_frame[2]);
986                 }
987
988                 copy_v3_v3(dir_old, dir_new);
989                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].x, cloth->verts[spring->kl].x);
990                 normalize_v3(dir_new);
991
992                 /* get local targets for kl/mn vertices by putting rest targets into the current frame,
993                  * then multiply with the rest length to get the actual goals
994                  */
995
996                 mul_v3_m3v3(spring->target, hair_frame, hair_kl->rest_target);
997                 mul_v3_fl(spring->target, spring->restlen);
998
999                 /* move frame to next hair segment */
1000                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
1001
1002                 prev_mn = spring->mn;
1003         }
1004 }
1005
1006 static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd)
1007 {
1008         Cloth *cloth = clmd->clothObject;
1009         LinkNode *search = NULL;
1010         float hair_frame[3][3], dir_old[3], dir_new[3];
1011         int prev_mn; /* to find hair roots */
1012
1013         if (!clmd->hairdata)
1014                 return;
1015
1016         /* XXX Note: we need to propagate frames from the root up,
1017          * but structural hair springs are stored in reverse order.
1018          * The bending springs however are then inserted in the same
1019          * order as vertices again ...
1020          * This messy situation can be resolved when solver data is
1021          * generated directly from a dedicated hair system.
1022          */
1023
1024         prev_mn = -1;
1025         for (search = cloth->springs; search; search = search->next) {
1026                 ClothSpring *spring = search->link;
1027                 ClothHairData *hair_ij, *hair_kl;
1028                 bool is_root = spring->kl != prev_mn;
1029
1030                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
1031                         continue;
1032                 }
1033
1034                 hair_ij = &clmd->hairdata[spring->ij];
1035                 hair_kl = &clmd->hairdata[spring->kl];
1036                 if (is_root) {
1037                         /* initial hair frame from root orientation */
1038                         copy_m3_m3(hair_frame, hair_ij->rot);
1039                         /* surface normal is the initial direction,
1040                          * parallel transport then keeps it aligned to the hair direction
1041                          */
1042                         copy_v3_v3(dir_new, hair_frame[2]);
1043                 }
1044
1045                 copy_v3_v3(dir_old, dir_new);
1046                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].xrest, cloth->verts[spring->kl].xrest);
1047                 normalize_v3(dir_new);
1048
1049                 /* dir expressed in the hair frame defines the rest target direction */
1050                 copy_v3_v3(hair_kl->rest_target, dir_new);
1051                 mul_transposed_m3_v3(hair_frame, hair_kl->rest_target);
1052
1053                 /* move frame to next hair segment */
1054                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
1055
1056                 prev_mn = spring->mn;
1057         }
1058 }
1059
1060 /* update stiffness if vertex group values are changing from frame to frame */
1061 static void cloth_update_springs( ClothModifierData *clmd )
1062 {
1063         Cloth *cloth = clmd->clothObject;
1064         LinkNode *search = NULL;
1065
1066         search = cloth->springs;
1067         while (search) {
1068                 ClothSpring *spring = search->link;
1069
1070                 spring->lin_stiffness = 0.0f;
1071
1072                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1073                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1074                                 spring->ang_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1075                         }
1076                 }
1077
1078                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1079                         spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1080                 }
1081                 else if (spring->type & CLOTH_SPRING_TYPE_SHEAR) {
1082                         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1083                 }
1084                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
1085                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1086                 }
1087                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING_HAIR) {
1088                         ClothVertex *v1 = &cloth->verts[spring->ij];
1089                         ClothVertex *v2 = &cloth->verts[spring->kl];
1090                         if (clmd->hairdata) {
1091                                 /* copy extra hair data to generic cloth vertices */
1092                                 v1->bend_stiff = clmd->hairdata[spring->ij].bending_stiffness;
1093                                 v2->bend_stiff = clmd->hairdata[spring->kl].bending_stiffness;
1094                         }
1095                         spring->lin_stiffness = (v1->bend_stiff + v2->bend_stiff) / 2.0f;
1096                 }
1097                 else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
1098                         /* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
1099
1100                         /* Activate / Deactivate existing springs */
1101                         if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
1102                             (cloth->verts[spring->ij].goal > ALMOST_ZERO))
1103                         {
1104                                 spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
1105                         }
1106                         else {
1107                                 spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
1108                         }
1109                 }
1110
1111                 search = search->next;
1112         }
1113
1114         cloth_hair_update_bending_targets(clmd);
1115 }
1116
1117 /* Update rest verts, for dynamically deformable cloth */
1118 static void cloth_update_verts( Object *ob, ClothModifierData *clmd, Mesh *mesh )
1119 {
1120         unsigned int i = 0;
1121         MVert *mvert = mesh->mvert;
1122         ClothVertex *verts = clmd->clothObject->verts;
1123
1124         /* vertex count is already ensured to match */
1125         for ( i = 0; i < mesh->totvert; i++, verts++ ) {
1126                 copy_v3_v3(verts->xrest, mvert[i].co);
1127                 mul_m4_v3(ob->obmat, verts->xrest);
1128         }
1129 }
1130
1131 /* Update spring rest length, for dynamically deformable cloth */
1132 static void cloth_update_spring_lengths( ClothModifierData *clmd, Mesh *mesh )
1133 {
1134         Cloth *cloth = clmd->clothObject;
1135         LinkNode *search = cloth->springs;
1136         unsigned int struct_springs = 0;
1137         unsigned int i = 0;
1138         unsigned int mvert_num = (unsigned int)mesh->totvert;
1139         float shrink_factor;
1140
1141         clmd->sim_parms->avg_spring_len = 0.0f;
1142
1143         for (i = 0; i < mvert_num; i++) {
1144                 cloth->verts[i].avg_spring_len = 0.0f;
1145         }
1146
1147         while (search) {
1148                 ClothSpring *spring = search->link;
1149
1150                 if (spring->type != CLOTH_SPRING_TYPE_SEWING) {
1151                         if (spring->type & (CLOTH_SPRING_TYPE_STRUCTURAL | CLOTH_SPRING_TYPE_SHEAR | CLOTH_SPRING_TYPE_BENDING)) {
1152                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1153                         }
1154                         else {
1155                                 shrink_factor = 1.0f;
1156                         }
1157
1158                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1159
1160                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1161                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1162                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1163                         }
1164                 }
1165
1166                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1167                         clmd->sim_parms->avg_spring_len += spring->restlen;
1168                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1169                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1170                         struct_springs++;
1171                 }
1172
1173                 search = search->next;
1174         }
1175
1176         if (struct_springs > 0) {
1177                 clmd->sim_parms->avg_spring_len /= struct_springs;
1178         }
1179
1180         for (i = 0; i < mvert_num; i++) {
1181                 if (cloth->verts[i].spring_count > 0) {
1182                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1183                 }
1184         }
1185 }
1186
1187 BLI_INLINE void cross_identity_v3(float r[3][3], const float v[3])
1188 {
1189         zero_m3(r);
1190         r[0][1] = v[2];
1191         r[0][2] = -v[1];
1192         r[1][0] = -v[2];
1193         r[1][2] = v[0];
1194         r[2][0] = v[1];
1195         r[2][1] = -v[0];
1196 }
1197
1198 BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f)
1199 {
1200         r[0][0] += m[0][0] * f;
1201         r[0][1] += m[0][1] * f;
1202         r[0][2] += m[0][2] * f;
1203         r[1][0] += m[1][0] * f;
1204         r[1][1] += m[1][1] * f;
1205         r[1][2] += m[1][2] * f;
1206         r[2][0] += m[2][0] * f;
1207         r[2][1] += m[2][1] * f;
1208         r[2][2] += m[2][2] * f;
1209 }
1210
1211 void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3])
1212 {
1213         float rot[3][3];
1214
1215         /* rotation between segments */
1216         rotation_between_vecs_to_mat3(rot, dir_old, dir_new);
1217
1218         /* rotate the frame */
1219         mul_m3_m3m3(mat, rot, mat);
1220 }
1221
1222 /* Add a shear and a bend spring between two verts within a poly. */
1223 static bool cloth_add_shear_bend_spring(ClothModifierData *clmd, LinkNodePair *edgelist,
1224                                         const MLoop *mloop, const MPoly *mpoly, int i, int j, int k)
1225 {
1226         Cloth *cloth = clmd->clothObject;
1227         ClothSpring *spring;
1228         const MLoop *tmp_loop;
1229         float shrink_factor;
1230         int x, y;
1231
1232         /* Combined shear/bend properties. */
1233         spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1234
1235         if (!spring) {
1236                 return false;
1237         }
1238
1239         spring_verts_ordered_set(spring,
1240                                  mloop[mpoly[i].loopstart + j].v,
1241                                  mloop[mpoly[i].loopstart + k].v);
1242
1243         shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1244         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1245         spring->type |= CLOTH_SPRING_TYPE_SHEAR;
1246         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1247
1248         if (edgelist) {
1249                 BLI_linklist_append(&edgelist[spring->ij], spring);
1250                 BLI_linklist_append(&edgelist[spring->kl], spring);
1251         }
1252
1253         /* Bending specific properties. */
1254         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1255                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1256
1257                 spring->la = k - j + 1;
1258                 spring->lb = mpoly[i].totloop - k + j + 1;
1259
1260                 spring->pa = MEM_mallocN(sizeof(*spring->pa) * spring->la, "spring poly");
1261                 if (!spring->pa) {
1262                         return false;
1263                 }
1264
1265                 spring->pb = MEM_mallocN(sizeof(*spring->pb) * spring->lb, "spring poly");
1266                 if (!spring->pb) {
1267                         return false;
1268                 }
1269
1270                 tmp_loop = mloop + mpoly[i].loopstart;
1271
1272                 for (x = 0; x < spring->la; x++) {
1273                         spring->pa[x] = tmp_loop[j + x].v;
1274                 }
1275
1276                 for (x = 0; x <= j; x++) {
1277                         spring->pb[x] = tmp_loop[x].v;
1278                 }
1279
1280                 for (y = k; y < mpoly[i].totloop; x++, y++) {
1281                         spring->pb[x] = tmp_loop[y].v;
1282                 }
1283
1284                 spring->mn = -1;
1285
1286                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1287                                                      spring->pa, spring->pb, spring->la, spring->lb);
1288
1289                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1290         }
1291
1292         BLI_linklist_prepend(&cloth->springs, spring);
1293
1294         return true;
1295 }
1296
1297 BLI_INLINE bool cloth_bend_set_poly_vert_array(int **poly, int len, const MLoop *mloop)
1298 {
1299         int *p = MEM_mallocN(sizeof(int) * len, "spring poly");
1300
1301         if (!p) {
1302                 return false;
1303         }
1304
1305         for (int i = 0; i < len; i++, mloop++) {
1306                 p[i] = mloop->v;
1307         }
1308
1309         *poly = p;
1310
1311         return true;
1312 }
1313
1314 static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh )
1315 {
1316         Cloth *cloth = clmd->clothObject;
1317         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1318         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0, struct_springs_real = 0;
1319         unsigned int mvert_num = (unsigned int)mesh->totvert;
1320         unsigned int numedges = (unsigned int)mesh->totedge;
1321         unsigned int numpolys = (unsigned int)mesh->totpoly;
1322         float shrink_factor;
1323         const MEdge *medge = mesh->medge;
1324         const MPoly *mpoly = mesh->mpoly;
1325         const MLoop *mloop = mesh->mloop;
1326         int index2 = 0; // our second vertex index
1327         LinkNodePair *edgelist = NULL;
1328         EdgeSet *edgeset = NULL;
1329         LinkNode *search = NULL, *search2 = NULL;
1330         BendSpringRef *spring_ref = NULL;
1331
1332         // error handling
1333         if ( numedges==0 )
1334                 return 0;
1335
1336         /* NOTE: handling ownership of springs and edgeset is quite sloppy
1337          * currently they are never initialized but assert just to be sure */
1338         BLI_assert(cloth->springs == NULL);
1339         BLI_assert(cloth->edgeset == NULL);
1340
1341         cloth->springs = NULL;
1342         cloth->edgeset = NULL;
1343
1344         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1345                 spring_ref = MEM_callocN(sizeof(*spring_ref) * numedges, "temp bend spring reference");
1346
1347                 if (!spring_ref) {
1348                         return 0;
1349                 }
1350         }
1351         else {
1352                 edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" );
1353
1354                 if (!edgelist) {
1355                         return 0;
1356                 }
1357         }
1358
1359         clmd->sim_parms->avg_spring_len = 0.0f;
1360         for (int i = 0; i < mvert_num; i++) {
1361                 cloth->verts[i].avg_spring_len = 0.0f;
1362         }
1363
1364         /* Structural springs. */
1365         for (int i = 0; i < numedges; i++) {
1366                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1367
1368                 if ( spring ) {
1369                         spring_verts_ordered_set(spring, medge[i].v1, medge[i].v2);
1370                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SEW && medge[i].flag & ME_LOOSEEDGE) {
1371                                 // handle sewing (loose edges will be pulled together)
1372                                 spring->restlen = 0.0f;
1373                                 spring->lin_stiffness = 1.0f;
1374                                 spring->type = CLOTH_SPRING_TYPE_SEWING;
1375                         }
1376                         else {
1377                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1378                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1379                                 spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1380                                 spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1381
1382                                 clmd->sim_parms->avg_spring_len += spring->restlen;
1383                                 cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1384                                 cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1385                                 cloth->verts[spring->ij].spring_count++;
1386                                 cloth->verts[spring->kl].spring_count++;
1387                                 struct_springs_real++;
1388                         }
1389
1390                         spring->flags = 0;
1391                         struct_springs++;
1392
1393                         BLI_linklist_prepend ( &cloth->springs, spring );
1394
1395                         if (spring_ref) {
1396                                 spring_ref[i].spring = spring;
1397                         }
1398                 }
1399                 else {
1400                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1401                         return 0;
1402                 }
1403         }
1404
1405         if (struct_springs_real > 0)
1406                 clmd->sim_parms->avg_spring_len /= struct_springs_real;
1407
1408         for (int i = 0; i < mvert_num; i++) {
1409                 if (cloth->verts[i].spring_count > 0)
1410                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1411         }
1412
1413         edgeset = BLI_edgeset_new_ex(__func__, numedges);
1414         cloth->edgeset = edgeset;
1415
1416         if (numpolys) {
1417                 for (int i = 0; i < numpolys; i++) {
1418                         /* Shear springs. */
1419                         /* Triangle faces already have shear springs due to structural geometry. */
1420                         if (mpoly[i].totloop > 3) {
1421                                 for (int j = 1; j < mpoly[i].totloop - 1; j++) {
1422                                         if (j > 1) {
1423                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, 0, j)) {
1424                                                         shear_springs++;
1425
1426                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1427                                                                 bend_springs++;
1428                                                         }
1429                                                 }
1430                                                 else {
1431                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1432                                                         return 0;
1433                                                 }
1434                                         }
1435
1436                                         for (int k = j + 2; k < mpoly[i].totloop; k++) {
1437                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, j, k)) {
1438                                                         shear_springs++;
1439
1440                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1441                                                                 bend_springs++;
1442                                                         }
1443                                                 }
1444                                                 else {
1445                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1446                                                         return 0;
1447                                                 }
1448                                         }
1449                                 }
1450                         }
1451
1452                         /* Angular bending springs along struct springs. */
1453                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1454                                 const MLoop *ml = mloop + mpoly[i].loopstart;
1455
1456                                 for (int j = 0; j < mpoly[i].totloop; j++, ml++) {
1457                                         BendSpringRef *curr_ref = &spring_ref[ml->e];
1458                                         curr_ref->polys++;
1459
1460                                         /* First poly found for this edge, store poly index. */
1461                                         if (curr_ref->polys == 1) {
1462                                                 curr_ref->index = i;
1463                                         }
1464                                         /* Second poly found for this edge, add bending data. */
1465                                         else if (curr_ref->polys == 2) {
1466                                                 spring = curr_ref->spring;
1467
1468                                                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1469
1470                                                 spring->la = mpoly[curr_ref->index].totloop;
1471                                                 spring->lb = mpoly[i].totloop;
1472
1473                                                 if (!cloth_bend_set_poly_vert_array(&spring->pa, spring->la, &mloop[mpoly[curr_ref->index].loopstart]) ||
1474                                                     !cloth_bend_set_poly_vert_array(&spring->pb, spring->lb, &mloop[mpoly[i].loopstart]))
1475                                                 {
1476                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1477                                                         return 0;
1478                                                 }
1479
1480                                                 spring->mn = ml->e;
1481
1482                                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1483                                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1484
1485                                                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1486
1487                                                 bend_springs++;
1488                                         }
1489                                         /* Third poly found for this edge, remove bending data. */
1490                                         else if (curr_ref->polys == 3) {
1491                                                 spring = curr_ref->spring;
1492
1493                                                 spring->type &= ~CLOTH_SPRING_TYPE_BENDING;
1494                                                 MEM_freeN(spring->pa);
1495                                                 MEM_freeN(spring->pb);
1496                                                 spring->pa = NULL;
1497                                                 spring->pb = NULL;
1498
1499                                                 bend_springs--;
1500                                         }
1501                                 }
1502                         }
1503                 }
1504
1505                 /* Linear bending springs. */
1506                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_LINEAR) {
1507                         search2 = cloth->springs;
1508
1509                         for (int i = struct_springs; i < struct_springs+shear_springs; i++) {
1510                                 if (!search2) {
1511                                         break;
1512                                 }
1513
1514                                 tspring2 = search2->link;
1515                                 search = edgelist[tspring2->kl].list;
1516
1517                                 while (search) {
1518                                         tspring = search->link;
1519                                         index2 = ((tspring->ij == tspring2->kl) ? (tspring->kl) : (tspring->ij));
1520
1521                                         /* Check for existing spring. */
1522                                         /* Check also if startpoint is equal to endpoint. */
1523                                         if ((index2 != tspring2->ij) &&
1524                                                 !BLI_edgeset_haskey(edgeset, tspring2->ij, index2))
1525                                         {
1526                                                 spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1527
1528                                                 if (!spring) {
1529                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1530                                                         return 0;
1531                                                 }
1532
1533                                                 spring_verts_ordered_set(spring, tspring2->ij, index2);
1534                                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1535                                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1536                                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1537                                                 spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1538                                                 BLI_edgeset_insert(edgeset, spring->ij, spring->kl);
1539                                                 bend_springs++;
1540
1541                                                 BLI_linklist_prepend(&cloth->springs, spring);
1542                                         }
1543
1544                                         search = search->next;
1545                                 }
1546
1547                                 search2 = search2->next;
1548                         }
1549                 }
1550         }
1551         else if (struct_springs > 2) {
1552                 if (G.debug_value != 1112) {
1553                         search = cloth->springs;
1554                         search2 = search->next;
1555                         while (search && search2) {
1556                                 tspring = search->link;
1557                                 tspring2 = search2->link;
1558
1559                                 if (tspring->ij == tspring2->kl) {
1560                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1561
1562                                         if (!spring) {
1563                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1564                                                 return 0;
1565                                         }
1566
1567                                         spring->ij = tspring2->ij;
1568                                         spring->kl = tspring->ij;
1569                                         spring->mn = tspring->kl;
1570                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1571                                         spring->type = CLOTH_SPRING_TYPE_BENDING_HAIR;
1572                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1573                                         bend_springs++;
1574
1575                                         BLI_linklist_prepend ( &cloth->springs, spring );
1576                                 }
1577
1578                                 search = search->next;
1579                                 search2 = search2->next;
1580                         }
1581                 }
1582                 else {
1583                         /* bending springs for hair strands
1584                          * The current algorithm only goes through the edges in order of the mesh edges list
1585                          * and makes springs between the outer vert of edges sharing a vertice. This works just
1586                          * fine for hair, but not for user generated string meshes. This could/should be later
1587                          * extended to work with non-ordered edges so that it can be used for general "rope
1588                          * dynamics" without the need for the vertices or edges to be ordered through the length
1589                          * of the strands. -jahka */
1590                         search = cloth->springs;
1591                         search2 = search->next;
1592                         while (search && search2) {
1593                                 tspring = search->link;
1594                                 tspring2 = search2->link;
1595
1596                                 if (tspring->ij == tspring2->kl) {
1597                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1598
1599                                         if (!spring) {
1600                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1601                                                 return 0;
1602                                         }
1603
1604                                         spring->ij = tspring2->ij;
1605                                         spring->kl = tspring->kl;
1606                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1607                                         spring->type = CLOTH_SPRING_TYPE_BENDING;
1608                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1609                                         bend_springs++;
1610
1611                                         BLI_linklist_prepend ( &cloth->springs, spring );
1612                                 }
1613
1614                                 search = search->next;
1615                                 search2 = search2->next;
1616                         }
1617                 }
1618
1619                 cloth_hair_update_bending_rest_targets(clmd);
1620         }
1621
1622         /* note: the edges may already exist so run reinsert */
1623
1624         /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */
1625         for (int i = 0; i < numedges; i++) { /* struct springs */
1626                 BLI_edgeset_add(edgeset, medge[i].v1, medge[i].v2);
1627         }
1628
1629         for (int i = 0; i < numpolys; i++) { /* edge springs */
1630                 if (mpoly[i].totloop == 4) {
1631                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 0].v, mloop[mpoly[i].loopstart + 2].v);
1632                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 1].v, mloop[mpoly[i].loopstart + 3].v);
1633                 }
1634         }
1635
1636         MEM_SAFE_FREE(spring_ref);
1637
1638         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1639
1640         cloth_free_edgelist(edgelist, mvert_num);
1641
1642 #if 0
1643         if (G.debug_value > 0)
1644                 printf("avg_len: %f\n", clmd->sim_parms->avg_spring_len);
1645 #endif
1646
1647         return 1;
1648
1649 } /* cloth_build_springs */
1650 /***************************************************************************************
1651  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION END
1652  ***************************************************************************************/