Merge branch 'master' into blender2.8
[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                 printf("cloth_free_modifier cloth_build_springs\n");
808                 return 0;
809         }
810
811         // init our solver
812         BPH_cloth_solver_init(ob, clmd);
813
814         if (!first)
815                 BKE_cloth_solver_set_positions(clmd);
816
817         clmd->clothObject->bvhtree = bvhtree_build_from_cloth (clmd, clmd->coll_parms->epsilon);
818         clmd->clothObject->bvhselftree = bvhtree_build_from_cloth(clmd, clmd->coll_parms->selfepsilon);
819
820         return 1;
821 }
822
823 static void cloth_from_mesh ( ClothModifierData *clmd, Mesh *mesh )
824 {
825         const MLoop *mloop = mesh->mloop;
826         const MLoopTri *looptri = BKE_mesh_runtime_looptri_ensure(mesh);
827         const unsigned int mvert_num = mesh->totvert;
828         const unsigned int looptri_num = mesh->runtime.looptris.len;
829
830         /* Allocate our vertices. */
831         clmd->clothObject->mvert_num = mvert_num;
832         clmd->clothObject->verts = MEM_callocN(sizeof(ClothVertex) * clmd->clothObject->mvert_num, "clothVertex");
833         if (clmd->clothObject->verts == NULL) {
834                 cloth_free_modifier(clmd);
835                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts");
836                 printf("cloth_free_modifier clmd->clothObject->verts\n");
837                 return;
838         }
839
840         /* save face information */
841         clmd->clothObject->tri_num = looptri_num;
842         clmd->clothObject->tri = MEM_mallocN(sizeof(MVertTri) * looptri_num, "clothLoopTris");
843         if (clmd->clothObject->tri == NULL) {
844                 cloth_free_modifier(clmd);
845                 modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->looptri");
846                 printf("cloth_free_modifier clmd->clothObject->looptri\n");
847                 return;
848         }
849         BKE_mesh_runtime_verttri_from_looptri(clmd->clothObject->tri, mloop, looptri, looptri_num);
850
851         /* Free the springs since they can't be correct if the vertices
852          * changed.
853          */
854         if ( clmd->clothObject->springs != NULL )
855                 MEM_freeN ( clmd->clothObject->springs );
856
857 }
858
859 /***************************************************************************************
860  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION BEGIN
861  ***************************************************************************************/
862
863 BLI_INLINE void spring_verts_ordered_set(ClothSpring *spring, int v0, int v1)
864 {
865         if (v0 < v1) {
866                 spring->ij = v0;
867                 spring->kl = v1;
868         }
869         else {
870                 spring->ij = v1;
871                 spring->kl = v0;
872         }
873 }
874
875 static void cloth_free_edgelist(LinkNodePair *edgelist, unsigned int mvert_num)
876 {
877         if (edgelist) {
878                 unsigned int i;
879                 for (i = 0; i < mvert_num; i++) {
880                         BLI_linklist_free(edgelist[i].list, NULL);
881                 }
882
883                 MEM_freeN(edgelist);
884         }
885 }
886
887 static void cloth_free_errorsprings(Cloth *cloth, LinkNodePair *edgelist, BendSpringRef *spring_ref)
888 {
889         if ( cloth->springs != NULL ) {
890                 LinkNode *search = cloth->springs;
891                 while (search) {
892                         ClothSpring *spring = search->link;
893
894                         MEM_SAFE_FREE(spring->pa);
895                         MEM_SAFE_FREE(spring->pb);
896
897                         MEM_freeN ( spring );
898                         search = search->next;
899                 }
900                 BLI_linklist_free(cloth->springs, NULL);
901
902                 cloth->springs = NULL;
903         }
904
905         cloth_free_edgelist(edgelist, cloth->mvert_num);
906
907         MEM_SAFE_FREE(spring_ref);
908
909         if (cloth->edgeset) {
910                 BLI_edgeset_free(cloth->edgeset);
911                 cloth->edgeset = NULL;
912         }
913 }
914
915 BLI_INLINE void cloth_bend_poly_dir(ClothVertex *verts, int i, int j, int *inds, int len, float r_dir[3])
916 {
917         float cent[3] = {0};
918         float fact = 1.0f / len;
919
920         for (int x = 0; x < len; x++) {
921                 madd_v3_v3fl(cent, verts[inds[x]].xrest, fact);
922         }
923
924         normal_tri_v3(r_dir, verts[i].xrest, verts[j].xrest, cent);
925 }
926
927 static float cloth_spring_angle(ClothVertex *verts, int i, int j, int *i_a, int *i_b, int len_a, int len_b)
928 {
929         float dir_a[3], dir_b[3];
930         float tmp[3], vec_e[3];
931         float sin, cos;
932
933         /* Poly vectors. */
934         cloth_bend_poly_dir(verts, j, i, i_a, len_a, dir_a);
935         cloth_bend_poly_dir(verts, i, j, i_b, len_b, dir_b);
936
937         /* Edge vector. */
938         sub_v3_v3v3(vec_e, verts[i].xrest, verts[j].xrest);
939         normalize_v3(vec_e);
940
941         /* Compute angle. */
942         cos = dot_v3v3(dir_a, dir_b);
943
944         cross_v3_v3v3(tmp, dir_a, dir_b);
945         sin = dot_v3v3(tmp, vec_e);
946
947         return atan2f(sin, cos);
948 }
949
950 static void cloth_hair_update_bending_targets(ClothModifierData *clmd)
951 {
952         Cloth *cloth = clmd->clothObject;
953         LinkNode *search = NULL;
954         float hair_frame[3][3], dir_old[3], dir_new[3];
955         int prev_mn; /* to find hair chains */
956
957         if (!clmd->hairdata)
958                 return;
959
960         /* XXX Note: we need to propagate frames from the root up,
961          * but structural hair springs are stored in reverse order.
962          * The bending springs however are then inserted in the same
963          * order as vertices again ...
964          * This messy situation can be resolved when solver data is
965          * generated directly from a dedicated hair system.
966          */
967
968         prev_mn = -1;
969         for (search = cloth->springs; search; search = search->next) {
970                 ClothSpring *spring = search->link;
971                 ClothHairData *hair_ij, *hair_kl;
972                 bool is_root = spring->kl != prev_mn;
973
974                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
975                         continue;
976                 }
977
978                 hair_ij = &clmd->hairdata[spring->ij];
979                 hair_kl = &clmd->hairdata[spring->kl];
980                 if (is_root) {
981                         /* initial hair frame from root orientation */
982                         copy_m3_m3(hair_frame, hair_ij->rot);
983                         /* surface normal is the initial direction,
984                          * parallel transport then keeps it aligned to the hair direction
985                          */
986                         copy_v3_v3(dir_new, hair_frame[2]);
987                 }
988
989                 copy_v3_v3(dir_old, dir_new);
990                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].x, cloth->verts[spring->kl].x);
991                 normalize_v3(dir_new);
992
993                 /* get local targets for kl/mn vertices by putting rest targets into the current frame,
994                  * then multiply with the rest length to get the actual goals
995                  */
996
997                 mul_v3_m3v3(spring->target, hair_frame, hair_kl->rest_target);
998                 mul_v3_fl(spring->target, spring->restlen);
999
1000                 /* move frame to next hair segment */
1001                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
1002
1003                 prev_mn = spring->mn;
1004         }
1005 }
1006
1007 static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd)
1008 {
1009         Cloth *cloth = clmd->clothObject;
1010         LinkNode *search = NULL;
1011         float hair_frame[3][3], dir_old[3], dir_new[3];
1012         int prev_mn; /* to find hair roots */
1013
1014         if (!clmd->hairdata)
1015                 return;
1016
1017         /* XXX Note: we need to propagate frames from the root up,
1018          * but structural hair springs are stored in reverse order.
1019          * The bending springs however are then inserted in the same
1020          * order as vertices again ...
1021          * This messy situation can be resolved when solver data is
1022          * generated directly from a dedicated hair system.
1023          */
1024
1025         prev_mn = -1;
1026         for (search = cloth->springs; search; search = search->next) {
1027                 ClothSpring *spring = search->link;
1028                 ClothHairData *hair_ij, *hair_kl;
1029                 bool is_root = spring->kl != prev_mn;
1030
1031                 if (spring->type != CLOTH_SPRING_TYPE_BENDING_HAIR) {
1032                         continue;
1033                 }
1034
1035                 hair_ij = &clmd->hairdata[spring->ij];
1036                 hair_kl = &clmd->hairdata[spring->kl];
1037                 if (is_root) {
1038                         /* initial hair frame from root orientation */
1039                         copy_m3_m3(hair_frame, hair_ij->rot);
1040                         /* surface normal is the initial direction,
1041                          * parallel transport then keeps it aligned to the hair direction
1042                          */
1043                         copy_v3_v3(dir_new, hair_frame[2]);
1044                 }
1045
1046                 copy_v3_v3(dir_old, dir_new);
1047                 sub_v3_v3v3(dir_new, cloth->verts[spring->mn].xrest, cloth->verts[spring->kl].xrest);
1048                 normalize_v3(dir_new);
1049
1050                 /* dir expressed in the hair frame defines the rest target direction */
1051                 copy_v3_v3(hair_kl->rest_target, dir_new);
1052                 mul_transposed_m3_v3(hair_frame, hair_kl->rest_target);
1053
1054                 /* move frame to next hair segment */
1055                 cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new);
1056
1057                 prev_mn = spring->mn;
1058         }
1059 }
1060
1061 /* update stiffness if vertex group values are changing from frame to frame */
1062 static void cloth_update_springs( ClothModifierData *clmd )
1063 {
1064         Cloth *cloth = clmd->clothObject;
1065         LinkNode *search = NULL;
1066
1067         search = cloth->springs;
1068         while (search) {
1069                 ClothSpring *spring = search->link;
1070
1071                 spring->lin_stiffness = 0.0f;
1072
1073                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1074                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1075                                 spring->ang_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1076                         }
1077                 }
1078
1079                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1080                         spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1081                 }
1082                 else if (spring->type & CLOTH_SPRING_TYPE_SHEAR) {
1083                         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1084                 }
1085                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING) {
1086                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1087                 }
1088                 else if (spring->type == CLOTH_SPRING_TYPE_BENDING_HAIR) {
1089                         ClothVertex *v1 = &cloth->verts[spring->ij];
1090                         ClothVertex *v2 = &cloth->verts[spring->kl];
1091                         if (clmd->hairdata) {
1092                                 /* copy extra hair data to generic cloth vertices */
1093                                 v1->bend_stiff = clmd->hairdata[spring->ij].bending_stiffness;
1094                                 v2->bend_stiff = clmd->hairdata[spring->kl].bending_stiffness;
1095                         }
1096                         spring->lin_stiffness = (v1->bend_stiff + v2->bend_stiff) / 2.0f;
1097                 }
1098                 else if (spring->type == CLOTH_SPRING_TYPE_GOAL) {
1099                         /* Warning: Appending NEW goal springs does not work because implicit solver would need reset! */
1100
1101                         /* Activate / Deactivate existing springs */
1102                         if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) &&
1103                             (cloth->verts[spring->ij].goal > ALMOST_ZERO))
1104                         {
1105                                 spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE;
1106                         }
1107                         else {
1108                                 spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE;
1109                         }
1110                 }
1111
1112                 search = search->next;
1113         }
1114
1115         cloth_hair_update_bending_targets(clmd);
1116 }
1117
1118 /* Update rest verts, for dynamically deformable cloth */
1119 static void cloth_update_verts( Object *ob, ClothModifierData *clmd, Mesh *mesh )
1120 {
1121         unsigned int i = 0;
1122         MVert *mvert = mesh->mvert;
1123         ClothVertex *verts = clmd->clothObject->verts;
1124
1125         /* vertex count is already ensured to match */
1126         for ( i = 0; i < mesh->totvert; i++, verts++ ) {
1127                 copy_v3_v3(verts->xrest, mvert[i].co);
1128                 mul_m4_v3(ob->obmat, verts->xrest);
1129         }
1130 }
1131
1132 /* Update spring rest length, for dynamically deformable cloth */
1133 static void cloth_update_spring_lengths( ClothModifierData *clmd, Mesh *mesh )
1134 {
1135         Cloth *cloth = clmd->clothObject;
1136         LinkNode *search = cloth->springs;
1137         unsigned int struct_springs = 0;
1138         unsigned int i = 0;
1139         unsigned int mvert_num = (unsigned int)mesh->totvert;
1140         float shrink_factor;
1141
1142         clmd->sim_parms->avg_spring_len = 0.0f;
1143
1144         for (i = 0; i < mvert_num; i++) {
1145                 cloth->verts[i].avg_spring_len = 0.0f;
1146         }
1147
1148         while (search) {
1149                 ClothSpring *spring = search->link;
1150
1151                 if (spring->type != CLOTH_SPRING_TYPE_SEWING) {
1152                         if (spring->type & (CLOTH_SPRING_TYPE_STRUCTURAL | CLOTH_SPRING_TYPE_SHEAR | CLOTH_SPRING_TYPE_BENDING)) {
1153                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1154                         }
1155                         else {
1156                                 shrink_factor = 1.0f;
1157                         }
1158
1159                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1160
1161                         if (spring->type & CLOTH_SPRING_TYPE_BENDING) {
1162                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1163                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1164                         }
1165                 }
1166
1167                 if (spring->type & CLOTH_SPRING_TYPE_STRUCTURAL) {
1168                         clmd->sim_parms->avg_spring_len += spring->restlen;
1169                         cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1170                         cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1171                         struct_springs++;
1172                 }
1173
1174                 search = search->next;
1175         }
1176
1177         if (struct_springs > 0) {
1178                 clmd->sim_parms->avg_spring_len /= struct_springs;
1179         }
1180
1181         for (i = 0; i < mvert_num; i++) {
1182                 if (cloth->verts[i].spring_count > 0) {
1183                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1184                 }
1185         }
1186 }
1187
1188 BLI_INLINE void cross_identity_v3(float r[3][3], const float v[3])
1189 {
1190         zero_m3(r);
1191         r[0][1] = v[2];
1192         r[0][2] = -v[1];
1193         r[1][0] = -v[2];
1194         r[1][2] = v[0];
1195         r[2][0] = v[1];
1196         r[2][1] = -v[0];
1197 }
1198
1199 BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f)
1200 {
1201         r[0][0] += m[0][0] * f;
1202         r[0][1] += m[0][1] * f;
1203         r[0][2] += m[0][2] * f;
1204         r[1][0] += m[1][0] * f;
1205         r[1][1] += m[1][1] * f;
1206         r[1][2] += m[1][2] * f;
1207         r[2][0] += m[2][0] * f;
1208         r[2][1] += m[2][1] * f;
1209         r[2][2] += m[2][2] * f;
1210 }
1211
1212 void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3])
1213 {
1214         float rot[3][3];
1215
1216         /* rotation between segments */
1217         rotation_between_vecs_to_mat3(rot, dir_old, dir_new);
1218
1219         /* rotate the frame */
1220         mul_m3_m3m3(mat, rot, mat);
1221 }
1222
1223 /* Add a shear and a bend spring between two verts within a poly. */
1224 static bool cloth_add_shear_bend_spring(ClothModifierData *clmd, LinkNodePair *edgelist,
1225                                         const MLoop *mloop, const MPoly *mpoly, int i, int j, int k)
1226 {
1227         Cloth *cloth = clmd->clothObject;
1228         ClothSpring *spring;
1229         const MLoop *tmp_loop;
1230         float shrink_factor;
1231         int x, y;
1232
1233         /* Combined shear/bend properties. */
1234         spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1235
1236         if (!spring) {
1237                 return false;
1238         }
1239
1240         spring_verts_ordered_set(spring,
1241                                  mloop[mpoly[i].loopstart + j].v,
1242                                  mloop[mpoly[i].loopstart + k].v);
1243
1244         shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1245         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1246         spring->type |= CLOTH_SPRING_TYPE_SHEAR;
1247         spring->lin_stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f;
1248
1249         if (edgelist) {
1250                 BLI_linklist_append(&edgelist[spring->ij], spring);
1251                 BLI_linklist_append(&edgelist[spring->kl], spring);
1252         }
1253
1254         /* Bending specific properties. */
1255         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1256                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1257
1258                 spring->la = k - j + 1;
1259                 spring->lb = mpoly[i].totloop - k + j + 1;
1260
1261                 spring->pa = MEM_mallocN(sizeof(*spring->pa) * spring->la, "spring poly");
1262                 if (!spring->pa) {
1263                         return false;
1264                 }
1265
1266                 spring->pb = MEM_mallocN(sizeof(*spring->pb) * spring->lb, "spring poly");
1267                 if (!spring->pb) {
1268                         return false;
1269                 }
1270
1271                 tmp_loop = mloop + mpoly[i].loopstart;
1272
1273                 for (x = 0; x < spring->la; x++) {
1274                         spring->pa[x] = tmp_loop[j + x].v;
1275                 }
1276
1277                 for (x = 0; x <= j; x++) {
1278                         spring->pb[x] = tmp_loop[x].v;
1279                 }
1280
1281                 for (y = k; y < mpoly[i].totloop; x++, y++) {
1282                         spring->pb[x] = tmp_loop[y].v;
1283                 }
1284
1285                 spring->mn = -1;
1286
1287                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1288                                                      spring->pa, spring->pb, spring->la, spring->lb);
1289
1290                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1291         }
1292
1293         BLI_linklist_prepend(&cloth->springs, spring);
1294
1295         return true;
1296 }
1297
1298 BLI_INLINE bool cloth_bend_set_poly_vert_array(int **poly, int len, const MLoop *mloop)
1299 {
1300         int *p = MEM_mallocN(sizeof(int) * len, "spring poly");
1301
1302         if (!p) {
1303                 return false;
1304         }
1305
1306         for (int i = 0; i < len; i++, mloop++) {
1307                 p[i] = mloop->v;
1308         }
1309
1310         *poly = p;
1311
1312         return true;
1313 }
1314
1315 static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh )
1316 {
1317         Cloth *cloth = clmd->clothObject;
1318         ClothSpring *spring = NULL, *tspring = NULL, *tspring2 = NULL;
1319         unsigned int struct_springs = 0, shear_springs=0, bend_springs = 0, struct_springs_real = 0;
1320         unsigned int mvert_num = (unsigned int)mesh->totvert;
1321         unsigned int numedges = (unsigned int)mesh->totedge;
1322         unsigned int numpolys = (unsigned int)mesh->totpoly;
1323         float shrink_factor;
1324         const MEdge *medge = mesh->medge;
1325         const MPoly *mpoly = mesh->mpoly;
1326         const MLoop *mloop = mesh->mloop;
1327         int index2 = 0; // our second vertex index
1328         LinkNodePair *edgelist = NULL;
1329         EdgeSet *edgeset = NULL;
1330         LinkNode *search = NULL, *search2 = NULL;
1331         BendSpringRef *spring_ref = NULL;
1332
1333         // error handling
1334         if ( numedges==0 )
1335                 return 0;
1336
1337         /* NOTE: handling ownership of springs and edgeset is quite sloppy
1338          * currently they are never initialized but assert just to be sure */
1339         BLI_assert(cloth->springs == NULL);
1340         BLI_assert(cloth->edgeset == NULL);
1341
1342         cloth->springs = NULL;
1343         cloth->edgeset = NULL;
1344
1345         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1346                 spring_ref = MEM_callocN(sizeof(*spring_ref) * numedges, "temp bend spring reference");
1347
1348                 if (!spring_ref) {
1349                         return 0;
1350                 }
1351         }
1352         else {
1353                 edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" );
1354
1355                 if (!edgelist) {
1356                         return 0;
1357                 }
1358         }
1359
1360         /* Structural springs. */
1361         for (int i = 0; i < numedges; i++) {
1362                 spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1363
1364                 if ( spring ) {
1365                         spring_verts_ordered_set(spring, medge[i].v1, medge[i].v2);
1366                         if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SEW && medge[i].flag & ME_LOOSEEDGE) {
1367                                 // handle sewing (loose edges will be pulled together)
1368                                 spring->restlen = 0.0f;
1369                                 spring->lin_stiffness = 1.0f;
1370                                 spring->type = CLOTH_SPRING_TYPE_SEWING;
1371                         }
1372                         else {
1373                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1374                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1375                                 spring->lin_stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f;
1376                                 spring->type = CLOTH_SPRING_TYPE_STRUCTURAL;
1377
1378                                 clmd->sim_parms->avg_spring_len += spring->restlen;
1379                                 cloth->verts[spring->ij].avg_spring_len += spring->restlen;
1380                                 cloth->verts[spring->kl].avg_spring_len += spring->restlen;
1381                                 cloth->verts[spring->ij].spring_count++;
1382                                 cloth->verts[spring->kl].spring_count++;
1383                                 struct_springs_real++;
1384                         }
1385
1386                         spring->flags = 0;
1387                         struct_springs++;
1388
1389                         BLI_linklist_prepend ( &cloth->springs, spring );
1390
1391                         if (spring_ref) {
1392                                 spring_ref[i].spring = spring;
1393                         }
1394                 }
1395                 else {
1396                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1397                         return 0;
1398                 }
1399         }
1400
1401         if (struct_springs_real > 0)
1402                 clmd->sim_parms->avg_spring_len /= struct_springs_real;
1403
1404         for (int i = 0; i < mvert_num; i++) {
1405                 if (cloth->verts[i].spring_count > 0)
1406                         cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count);
1407         }
1408
1409         edgeset = BLI_edgeset_new_ex(__func__, numedges);
1410         cloth->edgeset = edgeset;
1411
1412         if (numpolys) {
1413                 for (int i = 0; i < numpolys; i++) {
1414                         /* Shear springs. */
1415                         /* Triangle faces already have shear springs due to structural geometry. */
1416                         if (mpoly[i].totloop > 3) {
1417                                 for (int j = 1; j < mpoly[i].totloop - 1; j++) {
1418                                         if (j > 1) {
1419                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, 0, j)) {
1420                                                         shear_springs++;
1421
1422                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1423                                                                 bend_springs++;
1424                                                         }
1425                                                 }
1426                                                 else {
1427                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1428                                                         return 0;
1429                                                 }
1430                                         }
1431
1432                                         for (int k = j + 2; k < mpoly[i].totloop; k++) {
1433                                                 if (cloth_add_shear_bend_spring(clmd, edgelist, mloop, mpoly, i, j, k)) {
1434                                                         shear_springs++;
1435
1436                                                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1437                                                                 bend_springs++;
1438                                                         }
1439                                                 }
1440                                                 else {
1441                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1442                                                         return 0;
1443                                                 }
1444                                         }
1445                                 }
1446                         }
1447
1448                         /* Angular bending springs along struct springs. */
1449                         if (clmd->sim_parms->bending_model == CLOTH_BENDING_ANGULAR) {
1450                                 const MLoop *ml = mloop + mpoly[i].loopstart;
1451
1452                                 for (int j = 0; j < mpoly[i].totloop; j++, ml++) {
1453                                         BendSpringRef *curr_ref = &spring_ref[ml->e];
1454                                         curr_ref->polys++;
1455
1456                                         /* First poly found for this edge, store poly index. */
1457                                         if (curr_ref->polys == 1) {
1458                                                 curr_ref->index = i;
1459                                         }
1460                                         /* Second poly found for this edge, add bending data. */
1461                                         else if (curr_ref->polys == 2) {
1462                                                 spring = curr_ref->spring;
1463
1464                                                 spring->type |= CLOTH_SPRING_TYPE_BENDING;
1465
1466                                                 spring->la = mpoly[curr_ref->index].totloop;
1467                                                 spring->lb = mpoly[i].totloop;
1468
1469                                                 if (!cloth_bend_set_poly_vert_array(&spring->pa, spring->la, &mloop[mpoly[curr_ref->index].loopstart]) ||
1470                                                     !cloth_bend_set_poly_vert_array(&spring->pb, spring->lb, &mloop[mpoly[i].loopstart]))
1471                                                 {
1472                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1473                                                         return 0;
1474                                                 }
1475
1476                                                 spring->mn = ml->e;
1477
1478                                                 spring->restang = cloth_spring_angle(cloth->verts, spring->ij, spring->kl,
1479                                                                                      spring->pa, spring->pb, spring->la, spring->lb);
1480
1481                                                 spring->ang_stiffness = (cloth->verts[spring->ij].bend_stiff + cloth->verts[spring->kl].bend_stiff) / 2.0f;
1482
1483                                                 bend_springs++;
1484                                         }
1485                                         /* Third poly found for this edge, remove bending data. */
1486                                         else if (curr_ref->polys == 3) {
1487                                                 spring = curr_ref->spring;
1488
1489                                                 spring->type &= ~CLOTH_SPRING_TYPE_BENDING;
1490                                                 MEM_freeN(spring->pa);
1491                                                 MEM_freeN(spring->pb);
1492                                                 spring->pa = NULL;
1493                                                 spring->pb = NULL;
1494
1495                                                 bend_springs--;
1496                                         }
1497                                 }
1498                         }
1499                 }
1500
1501                 /* Linear bending springs. */
1502                 if (clmd->sim_parms->bending_model == CLOTH_BENDING_LINEAR) {
1503                         search2 = cloth->springs;
1504
1505                         for (int i = struct_springs; i < struct_springs+shear_springs; i++) {
1506                                 if (!search2) {
1507                                         break;
1508                                 }
1509
1510                                 tspring2 = search2->link;
1511                                 search = edgelist[tspring2->kl].list;
1512
1513                                 while (search) {
1514                                         tspring = search->link;
1515                                         index2 = ((tspring->ij == tspring2->kl) ? (tspring->kl) : (tspring->ij));
1516
1517                                         /* Check for existing spring. */
1518                                         /* Check also if startpoint is equal to endpoint. */
1519                                         if ((index2 != tspring2->ij) &&
1520                                                 !BLI_edgeset_haskey(edgeset, tspring2->ij, index2))
1521                                         {
1522                                                 spring = (ClothSpring *)MEM_callocN(sizeof(ClothSpring), "cloth spring");
1523
1524                                                 if (!spring) {
1525                                                         cloth_free_errorsprings(cloth, edgelist, spring_ref);
1526                                                         return 0;
1527                                                 }
1528
1529                                                 spring_verts_ordered_set(spring, tspring2->ij, index2);
1530                                                 shrink_factor = cloth_shrink_factor(clmd, cloth->verts, spring->ij, spring->kl);
1531                                                 spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest) * shrink_factor;
1532                                                 spring->type = CLOTH_SPRING_TYPE_BENDING;
1533                                                 spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1534                                                 BLI_edgeset_insert(edgeset, spring->ij, spring->kl);
1535                                                 bend_springs++;
1536
1537                                                 BLI_linklist_prepend(&cloth->springs, spring);
1538                                         }
1539
1540                                         search = search->next;
1541                                 }
1542
1543                                 search2 = search2->next;
1544                         }
1545                 }
1546         }
1547         else if (struct_springs > 2) {
1548                 if (G.debug_value != 1112) {
1549                         search = cloth->springs;
1550                         search2 = search->next;
1551                         while (search && search2) {
1552                                 tspring = search->link;
1553                                 tspring2 = search2->link;
1554
1555                                 if (tspring->ij == tspring2->kl) {
1556                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1557
1558                                         if (!spring) {
1559                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1560                                                 return 0;
1561                                         }
1562
1563                                         spring->ij = tspring2->ij;
1564                                         spring->kl = tspring->ij;
1565                                         spring->mn = tspring->kl;
1566                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1567                                         spring->type = CLOTH_SPRING_TYPE_BENDING_HAIR;
1568                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1569                                         bend_springs++;
1570
1571                                         BLI_linklist_prepend ( &cloth->springs, spring );
1572                                 }
1573
1574                                 search = search->next;
1575                                 search2 = search2->next;
1576                         }
1577                 }
1578                 else {
1579                         /* bending springs for hair strands
1580                          * The current algorithm only goes through the edges in order of the mesh edges list
1581                          * and makes springs between the outer vert of edges sharing a vertice. This works just
1582                          * fine for hair, but not for user generated string meshes. This could/should be later
1583                          * extended to work with non-ordered edges so that it can be used for general "rope
1584                          * dynamics" without the need for the vertices or edges to be ordered through the length
1585                          * of the strands. -jahka */
1586                         search = cloth->springs;
1587                         search2 = search->next;
1588                         while (search && search2) {
1589                                 tspring = search->link;
1590                                 tspring2 = search2->link;
1591
1592                                 if (tspring->ij == tspring2->kl) {
1593                                         spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" );
1594
1595                                         if (!spring) {
1596                                                 cloth_free_errorsprings(cloth, edgelist, spring_ref);
1597                                                 return 0;
1598                                         }
1599
1600                                         spring->ij = tspring2->ij;
1601                                         spring->kl = tspring->kl;
1602                                         spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest);
1603                                         spring->type = CLOTH_SPRING_TYPE_BENDING;
1604                                         spring->lin_stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f;
1605                                         bend_springs++;
1606
1607                                         BLI_linklist_prepend ( &cloth->springs, spring );
1608                                 }
1609
1610                                 search = search->next;
1611                                 search2 = search2->next;
1612                         }
1613                 }
1614
1615                 cloth_hair_update_bending_rest_targets(clmd);
1616         }
1617
1618         /* note: the edges may already exist so run reinsert */
1619
1620         /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */
1621         for (int i = 0; i < numedges; i++) { /* struct springs */
1622                 BLI_edgeset_add(edgeset, medge[i].v1, medge[i].v2);
1623         }
1624
1625         for (int i = 0; i < numpolys; i++) { /* edge springs */
1626                 if (mpoly[i].totloop == 4) {
1627                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 0].v, mloop[mpoly[i].loopstart + 2].v);
1628                         BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 1].v, mloop[mpoly[i].loopstart + 3].v);
1629                 }
1630         }
1631
1632         MEM_SAFE_FREE(spring_ref);
1633
1634         cloth->numsprings = struct_springs + shear_springs + bend_springs;
1635
1636         cloth_free_edgelist(edgelist, mvert_num);
1637
1638 #if 0
1639         if (G.debug_value > 0)
1640                 printf("avg_len: %f\n", clmd->sim_parms->avg_spring_len);
1641 #endif
1642
1643         return 1;
1644
1645 } /* cloth_build_springs */
1646 /***************************************************************************************
1647  * SPRING NETWORK GPU_BATCH_BUILDING IMPLEMENTATION END
1648  ***************************************************************************************/