doxygen: add newline after \file
[blender.git] / source / blender / blenkernel / intern / softbody.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) Blender Foundation
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24
25 /**
26  * variables on the UI for now
27  * <pre>
28  * float mediafrict;  friction to env
29  * float nodemass;        softbody mass of *vertex*
30  * float grav;        softbody amount of gravitation to apply
31  *
32  * float goalspring;  softbody goal springs
33  * float goalfrict;   softbody goal springs friction
34  * float mingoal;     quick limits for goal
35  * float maxgoal;
36  *
37  * float inspring;        softbody inner springs
38  * float infrict;     softbody inner springs friction
39  * </pre>
40  */
41
42
43 #include <math.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "CLG_log.h"
48
49 #include "MEM_guardedalloc.h"
50
51 /* types */
52 #include "DNA_collection_types.h"
53 #include "DNA_curve_types.h"
54 #include "DNA_lattice_types.h"
55 #include "DNA_meshdata_types.h"
56 #include "DNA_mesh_types.h"
57 #include "DNA_object_types.h"
58 #include "DNA_scene_types.h"
59
60 #include "BLI_math.h"
61 #include "BLI_utildefines.h"
62 #include "BLI_listbase.h"
63 #include "BLI_ghash.h"
64 #include "BLI_threads.h"
65
66 #include "BKE_collection.h"
67 #include "BKE_collision.h"
68 #include "BKE_curve.h"
69 #include "BKE_effect.h"
70 #include "BKE_global.h"
71 #include "BKE_layer.h"
72 #include "BKE_modifier.h"
73 #include "BKE_softbody.h"
74 #include "BKE_pointcache.h"
75 #include "BKE_deform.h"
76 #include "BKE_mesh.h"
77 #include "BKE_scene.h"
78
79 #include "DEG_depsgraph.h"
80 #include "DEG_depsgraph_query.h"
81
82 #include  "PIL_time.h"
83
84 static CLG_LogRef LOG = {"bke.softbody"};
85
86 /* callbacks for errors and interrupts and some goo */
87 static int (*SB_localInterruptCallBack)(void) = NULL;
88
89
90 /* ********** soft body engine ******* */
91
92 typedef enum {SB_EDGE=1, SB_BEND=2, SB_STIFFQUAD=3, SB_HANDLE=4} type_spring;
93
94 typedef struct BodySpring {
95         int v1, v2;
96         float len, cf, load;
97         float ext_force[3]; /* edges colliding and sailing */
98         type_spring springtype;
99         short flag;
100 } BodySpring;
101
102 typedef struct BodyFace {
103         int v1, v2, v3;
104         float ext_force[3]; /* faces colliding */
105         short flag;
106 } BodyFace;
107
108 typedef struct ReferenceVert {
109         float pos[3]; /* position relative to com */
110         float mass;   /* node mass */
111 } ReferenceVert;
112
113 typedef struct ReferenceState {
114         float com[3]; /* center of mass*/
115         ReferenceVert *ivert; /* list of initial values */
116 } ReferenceState;
117
118
119 /*private scratch pad for caching and other data only needed when alive*/
120 typedef struct SBScratch {
121         GHash *colliderhash;
122         short needstobuildcollider;
123         short flag;
124         BodyFace *bodyface;
125         int totface;
126         float aabbmin[3], aabbmax[3];
127         ReferenceState Ref;
128 } SBScratch;
129
130 typedef struct  SB_thread_context {
131                 Scene *scene;
132                 Object *ob;
133                 float forcetime;
134                 float timenow;
135                 int ifirst;
136                 int ilast;
137                 ListBase *effectors;
138                 int do_deflector;
139                 float fieldfactor;
140                 float windfactor;
141                 int nr;
142                 int tot;
143 } SB_thread_context;
144
145 #define MID_PRESERVE 1
146
147 #define SOFTGOALSNAP  0.999f
148 /* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
149  * removes *unnecessary* stiffness from ODE system
150  */
151 #define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
152
153
154 #define BSF_INTERSECT   1 /* edge intersects collider face */
155
156 /* private definitions for bodypoint states */
157 #define SBF_DOFUZZY          1 /* Bodypoint do fuzzy */
158 #define SBF_OUTOFCOLLISION   2 /* Bodypoint does not collide  */
159
160
161 #define BFF_INTERSECT   1 /* collider edge   intrudes face */
162 #define BFF_CLOSEVERT   2 /* collider vertex repulses face */
163
164
165 static float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
166
167 /* local prototypes */
168 static void free_softbody_intern(SoftBody *sb);
169
170 /*+++ frame based timing +++*/
171
172 /*physical unit of force is [kg * m / sec^2]*/
173
174 static float sb_grav_force_scale(Object *UNUSED(ob))
175 /* since unit of g is [m/sec^2] and F = mass * g we rescale unit mass of node to 1 gramm
176  * put it to a function here, so we can add user options later without touching simulation code
177  */
178 {
179         return (0.001f);
180 }
181
182 static float sb_fric_force_scale(Object *UNUSED(ob))
183 /* rescaling unit of drag [1 / sec] to somehow reasonable
184  * put it to a function here, so we can add user options later without touching simulation code
185  */
186 {
187         return (0.01f);
188 }
189
190 static float sb_time_scale(Object *ob)
191 /* defining the frames to *real* time relation */
192 {
193         SoftBody *sb= ob->soft; /* is supposed to be there */
194         if (sb) {
195                 return(sb->physics_speed);
196                 /* hrms .. this could be IPO as well :)
197                  * estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)]
198                  * 1 approx = a unit 1 pendulum at g = 9.8 [earth conditions]  has period 65 frames
199                  * theory would give a 50 frames period .. so there must be something inaccurate .. looking for that (BM)
200                  */
201         }
202         return (1.0f);
203         /*
204          * this would be frames/sec independent timing assuming 25 fps is default
205          * but does not work very well with NLA
206          * return (25.0f/scene->r.frs_sec)
207          */
208 }
209 /*--- frame based timing ---*/
210
211 /* helper functions for everything is animatable jow_go_for2_5 +++++++*/
212 /* introducing them here, because i know: steps in properties  ( at frame timing )
213  * will cause unwanted responses of the softbody system (which does inter frame calculations )
214  * so first 'cure' would be: interpolate linear in time ..
215  * Q: why do i write this?
216  * A: because it happened once, that some eger coder 'streamlined' code to fail.
217  * We DO linear interpolation for goals .. and i think we should do on animated properties as well
218  */
219
220 /* animate sb->maxgoal, sb->mingoal */
221 static float _final_goal(Object *ob, BodyPoint *bp)/*jow_go_for2_5 */
222 {
223         float f = -1999.99f;
224         if (ob) {
225                 SoftBody *sb= ob->soft; /* is supposed to be there */
226                 if (!(ob->softflag & OB_SB_GOAL)) return (0.0f);
227                 if (sb&&bp) {
228                         if (bp->goal < 0.0f) return (0.0f);
229                         f = sb->mingoal + bp->goal * fabsf(sb->maxgoal - sb->mingoal);
230                         f = pow(f, 4.0f);
231                         return (f);
232                 }
233         }
234         CLOG_ERROR(&LOG, "sb or bp == NULL");
235         return f; /*using crude but spot able values some times helps debuggin */
236 }
237
238 static float _final_mass(Object *ob, BodyPoint *bp)
239 {
240         if (ob) {
241                 SoftBody *sb= ob->soft; /* is supposed to be there */
242                 if (sb&&bp) {
243                         return(bp->mass*sb->nodemass);
244                 }
245         }
246         CLOG_ERROR(&LOG, "sb or bp == NULL");
247         return 1.0f;
248 }
249 /* helper functions for everything is animateble jow_go_for2_5 ------*/
250
251 /*+++ collider caching and dicing +++*/
252
253 /*
254  * for each target object/face the axis aligned bounding box (AABB) is stored
255  * faces parallel to global axes
256  * so only simple "value" in [min, max] ckecks are used
257  * float operations still
258  */
259
260 /* just an ID here to reduce the prob for killing objects
261  * ob->sumohandle points to we should not kill :)
262  */
263 static const int CCD_SAVETY = 190561;
264
265 typedef struct ccdf_minmax {
266         float minx, miny, minz, maxx, maxy, maxz;
267 } ccdf_minmax;
268
269
270 typedef struct ccd_Mesh {
271         int mvert_num, tri_num;
272         const MVert *mvert;
273         const MVert *mprevvert;
274         const MVertTri *tri;
275         int savety;
276         ccdf_minmax *mima;
277         /* Axis Aligned Bounding Box AABB */
278         float bbmin[3];
279         float bbmax[3];
280 } ccd_Mesh;
281
282
283 static ccd_Mesh *ccd_mesh_make(Object *ob)
284 {
285         CollisionModifierData *cmd;
286         ccd_Mesh *pccd_M = NULL;
287         ccdf_minmax *mima;
288         const MVertTri *vt;
289         float hull;
290         int i;
291
292         cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
293
294         /* first some paranoia checks */
295         if (!cmd) return NULL;
296         if (!cmd->mvert_num || !cmd->tri_num) return NULL;
297
298         pccd_M = MEM_mallocN(sizeof(ccd_Mesh), "ccd_Mesh");
299         pccd_M->mvert_num = cmd->mvert_num;
300         pccd_M->tri_num = cmd->tri_num;
301         pccd_M->savety  = CCD_SAVETY;
302         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
303         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
304         pccd_M->mprevvert=NULL;
305
306         /* blow it up with forcefield ranges */
307         hull = max_ff(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
308
309         /* alloc and copy verts*/
310         pccd_M->mvert = MEM_dupallocN(cmd->xnew);
311         /* note that xnew coords are already in global space, */
312         /* determine the ortho BB */
313         for (i = 0; i < pccd_M->mvert_num; i++) {
314                 const float *v;
315
316                 /* evaluate limits */
317                 v = pccd_M->mvert[i].co;
318                 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
319                 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
320                 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
321
322                 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
323                 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
324                 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
325
326         }
327         /* alloc and copy faces*/
328         pccd_M->tri = MEM_dupallocN(cmd->tri);
329
330         /* OBBs for idea1 */
331         pccd_M->mima = MEM_mallocN(sizeof(ccdf_minmax) * pccd_M->tri_num, "ccd_Mesh_Faces_mima");
332
333
334         /* anyhoo we need to walk the list of faces and find OBB they live in */
335         for (i = 0, mima  = pccd_M->mima, vt = pccd_M->tri; i < pccd_M->tri_num; i++, mima++, vt++) {
336                 const float *v;
337
338                 mima->minx=mima->miny=mima->minz=1e30f;
339                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
340
341                 v = pccd_M->mvert[vt->tri[0]].co;
342                 mima->minx = min_ff(mima->minx, v[0] - hull);
343                 mima->miny = min_ff(mima->miny, v[1] - hull);
344                 mima->minz = min_ff(mima->minz, v[2] - hull);
345                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
346                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
347                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
348
349                 v = pccd_M->mvert[vt->tri[1]].co;
350                 mima->minx = min_ff(mima->minx, v[0] - hull);
351                 mima->miny = min_ff(mima->miny, v[1] - hull);
352                 mima->minz = min_ff(mima->minz, v[2] - hull);
353                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
354                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
355                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
356
357                 v = pccd_M->mvert[vt->tri[2]].co;
358                 mima->minx = min_ff(mima->minx, v[0] - hull);
359                 mima->miny = min_ff(mima->miny, v[1] - hull);
360                 mima->minz = min_ff(mima->minz, v[2] - hull);
361                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
362                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
363                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
364         }
365
366         return pccd_M;
367 }
368 static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M)
369 {
370         CollisionModifierData *cmd;
371         ccdf_minmax *mima;
372         const MVertTri *vt;
373         float hull;
374         int i;
375
376         cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
377
378         /* first some paranoia checks */
379         if (!cmd) return;
380         if (!cmd->mvert_num || !cmd->tri_num) return;
381
382         if ((pccd_M->mvert_num != cmd->mvert_num) ||
383             (pccd_M->tri_num != cmd->tri_num))
384         {
385                 return;
386         }
387
388         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
389         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
390
391
392         /* blow it up with forcefield ranges */
393         hull = max_ff(ob->pd->pdef_sbift, ob->pd->pdef_sboft);
394
395         /* rotate current to previous */
396         if (pccd_M->mprevvert) MEM_freeN((void *)pccd_M->mprevvert);
397         pccd_M->mprevvert = pccd_M->mvert;
398         /* alloc and copy verts*/
399         pccd_M->mvert = MEM_dupallocN(cmd->xnew);
400         /* note that xnew coords are already in global space, */
401         /* determine the ortho BB */
402         for (i=0; i < pccd_M->mvert_num; i++) {
403                 const float *v;
404
405                 /* evaluate limits */
406                 v = pccd_M->mvert[i].co;
407                 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
408                 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
409                 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
410
411                 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
412                 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
413                 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
414
415                 /* evaluate limits */
416                 v = pccd_M->mprevvert[i].co;
417                 pccd_M->bbmin[0] = min_ff(pccd_M->bbmin[0], v[0] - hull);
418                 pccd_M->bbmin[1] = min_ff(pccd_M->bbmin[1], v[1] - hull);
419                 pccd_M->bbmin[2] = min_ff(pccd_M->bbmin[2], v[2] - hull);
420
421                 pccd_M->bbmax[0] = max_ff(pccd_M->bbmax[0], v[0] + hull);
422                 pccd_M->bbmax[1] = max_ff(pccd_M->bbmax[1], v[1] + hull);
423                 pccd_M->bbmax[2] = max_ff(pccd_M->bbmax[2], v[2] + hull);
424
425         }
426
427         /* anyhoo we need to walk the list of faces and find OBB they live in */
428         for (i = 0, mima  = pccd_M->mima, vt = pccd_M->tri; i < pccd_M->tri_num; i++, mima++, vt++) {
429                 const float *v;
430
431                 mima->minx=mima->miny=mima->minz=1e30f;
432                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
433
434                 /* mvert */
435                 v = pccd_M->mvert[vt->tri[0]].co;
436                 mima->minx = min_ff(mima->minx, v[0] - hull);
437                 mima->miny = min_ff(mima->miny, v[1] - hull);
438                 mima->minz = min_ff(mima->minz, v[2] - hull);
439                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
440                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
441                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
442
443                 v = pccd_M->mvert[vt->tri[1]].co;
444                 mima->minx = min_ff(mima->minx, v[0] - hull);
445                 mima->miny = min_ff(mima->miny, v[1] - hull);
446                 mima->minz = min_ff(mima->minz, v[2] - hull);
447                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
448                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
449                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
450
451                 v = pccd_M->mvert[vt->tri[2]].co;
452                 mima->minx = min_ff(mima->minx, v[0] - hull);
453                 mima->miny = min_ff(mima->miny, v[1] - hull);
454                 mima->minz = min_ff(mima->minz, v[2] - hull);
455                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
456                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
457                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
458
459
460                 /* mprevvert */
461                 v = pccd_M->mprevvert[vt->tri[0]].co;
462                 mima->minx = min_ff(mima->minx, v[0] - hull);
463                 mima->miny = min_ff(mima->miny, v[1] - hull);
464                 mima->minz = min_ff(mima->minz, v[2] - hull);
465                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
466                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
467                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
468
469                 v = pccd_M->mprevvert[vt->tri[1]].co;
470                 mima->minx = min_ff(mima->minx, v[0] - hull);
471                 mima->miny = min_ff(mima->miny, v[1] - hull);
472                 mima->minz = min_ff(mima->minz, v[2] - hull);
473                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
474                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
475                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
476
477                 v = pccd_M->mprevvert[vt->tri[2]].co;
478                 mima->minx = min_ff(mima->minx, v[0] - hull);
479                 mima->miny = min_ff(mima->miny, v[1] - hull);
480                 mima->minz = min_ff(mima->minz, v[2] - hull);
481                 mima->maxx = max_ff(mima->maxx, v[0] + hull);
482                 mima->maxy = max_ff(mima->maxy, v[1] + hull);
483                 mima->maxz = max_ff(mima->maxz, v[2] + hull);
484         }
485         return;
486 }
487
488 static void ccd_mesh_free(ccd_Mesh *ccdm)
489 {
490         if (ccdm && (ccdm->savety == CCD_SAVETY )) { /*make sure we're not nuking objects we don't know*/
491                 MEM_freeN((void *)ccdm->mvert);
492                 MEM_freeN((void *)ccdm->tri);
493                 if (ccdm->mprevvert) MEM_freeN((void *)ccdm->mprevvert);
494                 MEM_freeN(ccdm->mima);
495                 MEM_freeN(ccdm);
496                 ccdm = NULL;
497         }
498 }
499
500 static void ccd_build_deflector_hash_single(GHash *hash, Object *ob)
501 {
502         /* only with deflecting set */
503         if (ob->pd && ob->pd->deflect) {
504                 void **val_p;
505                 if (!BLI_ghash_ensure_p(hash, ob, &val_p)) {
506                         ccd_Mesh *ccdmesh = ccd_mesh_make(ob);
507                         *val_p = ccdmesh;
508                 }
509         }
510 }
511
512 /**
513  * \note collection overrides scene when not NULL.
514  */
515 static void ccd_build_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash)
516 {
517         if (!hash) return;
518
519         unsigned int numobjects;
520         Object **objects = BKE_collision_objects_create(depsgraph, vertexowner, collection, &numobjects, eModifierType_Collision);
521
522         for (int i = 0; i < numobjects; i++) {
523                 Object *ob = objects[i];
524
525                 if (ob->type == OB_MESH) {
526                         ccd_build_deflector_hash_single(hash, ob);
527                 }
528         }
529
530         BKE_collision_objects_free(objects);
531 }
532
533 static void ccd_update_deflector_hash_single(GHash *hash, Object *ob)
534 {
535         if (ob->pd && ob->pd->deflect) {
536                 ccd_Mesh *ccdmesh = BLI_ghash_lookup(hash, ob);
537                 if (ccdmesh) {
538                         ccd_mesh_update(ob, ccdmesh);
539                 }
540         }
541 }
542
543 /**
544  * \note collection overrides scene when not NULL.
545  */
546 static void ccd_update_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash)
547 {
548         if ((!hash) || (!vertexowner)) return;
549
550         unsigned int numobjects;
551         Object **objects = BKE_collision_objects_create(depsgraph, vertexowner, collection, &numobjects, eModifierType_Collision);
552
553         for (int i = 0; i < numobjects; i++) {
554                 Object *ob = objects[i];
555
556                 if (ob->type == OB_MESH) {
557                         ccd_update_deflector_hash_single(hash, ob);
558                 }
559         }
560
561         BKE_collision_objects_free(objects);
562 }
563
564 /*--- collider caching and dicing ---*/
565
566
567 static int count_mesh_quads(Mesh *me)
568 {
569         int a, result = 0;
570         const MPoly *mp = me->mpoly;
571
572         if (mp) {
573                 for (a = me->totpoly; a > 0; a--, mp++) {
574                         if (mp->totloop == 4) {
575                                 result++;
576                         }
577                 }
578         }
579         return result;
580 }
581
582 static void add_mesh_quad_diag_springs(Object *ob)
583 {
584         Mesh *me= ob->data;
585         /*BodyPoint *bp;*/ /*UNUSED*/
586         int a;
587
588         if (ob->soft) {
589                 int nofquads;
590                 //float s_shear = ob->soft->shearstiff*ob->soft->shearstiff;
591
592                 nofquads = count_mesh_quads(me);
593                 if (nofquads) {
594                         const MLoop *mloop = me->mloop;
595                         const MPoly *mp = me->mpoly;
596                         BodySpring *bs;
597
598                         /* resize spring-array to hold additional quad springs */
599                         ob->soft->bspring = MEM_recallocN(ob->soft->bspring, sizeof(BodySpring) * (ob->soft->totspring + nofquads * 2));
600
601                         /* fill the tail */
602                         a = 0;
603                         bs = &ob->soft->bspring[ob->soft->totspring];
604                         /*bp= ob->soft->bpoint; */ /*UNUSED*/
605                         for (a = me->totpoly; a > 0; a--, mp++) {
606                                 if (mp->totloop == 4) {
607                                         bs->v1 = mloop[mp->loopstart + 0].v;
608                                         bs->v2 = mloop[mp->loopstart + 2].v;
609                                         bs->springtype   = SB_STIFFQUAD;
610                                         bs++;
611                                         bs->v1 = mloop[mp->loopstart + 1].v;
612                                         bs->v2 = mloop[mp->loopstart + 3].v;
613                                         bs->springtype   = SB_STIFFQUAD;
614                                         bs++;
615                                 }
616                         }
617
618                         /* now we can announce new springs */
619                         ob->soft->totspring += nofquads * 2;
620                 }
621         }
622 }
623
624 static void add_2nd_order_roller(Object *ob, float UNUSED(stiffness), int *counter, int addsprings)
625 {
626         /*assume we have a softbody*/
627         SoftBody *sb= ob->soft; /* is supposed to be there */
628         BodyPoint *bp, *bpo;
629         BodySpring *bs, *bs2, *bs3= NULL;
630         int a, b, c, notthis= 0, v0;
631         if (!sb->bspring) {return;} /* we are 2nd order here so 1rst should have been build :) */
632         /* first run counting  second run adding */
633         *counter = 0;
634         if (addsprings) bs3 = ob->soft->bspring+ob->soft->totspring;
635         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
636                 /*scan for neighborhood*/
637                 bpo = NULL;
638                 v0  = (sb->totpoint-a);
639                 for (b=bp->nofsprings;b>0;b--) {
640                         bs = sb->bspring + bp->springs[b-1];
641                         /*nasty thing here that springs have two ends
642                         so here we have to make sure we examine the other */
643                         if (v0 == bs->v1) {
644                                 bpo = sb->bpoint+bs->v2;
645                                 notthis = bs->v2;
646                         }
647                         else {
648                                 if (v0 == bs->v2) {
649                                         bpo = sb->bpoint+bs->v1;
650                                         notthis = bs->v1;
651                                 }
652                                 else {
653                                         CLOG_ERROR(&LOG, "oops we should not get here");
654                                 }
655                         }
656                         if (bpo) {/* so now we have a 2nd order humpdidump */
657                                 for (c=bpo->nofsprings;c>0;c--) {
658                                         bs2 = sb->bspring + bpo->springs[c-1];
659                                         if ((bs2->v1 != notthis) && (bs2->v1 > v0)) {
660                                                 (*counter)++;/*hit */
661                                                 if (addsprings) {
662                                                         bs3->v1= v0;
663                                                         bs3->v2= bs2->v1;
664                                                         bs3->springtype   = SB_BEND;
665                                                         bs3++;
666                                                 }
667                                         }
668                                         if ((bs2->v2 !=notthis)&&(bs2->v2 > v0)) {
669                                                 (*counter)++;  /* hit */
670                                                 if (addsprings) {
671                                                         bs3->v1= v0;
672                                                         bs3->v2= bs2->v2;
673                                                         bs3->springtype   = SB_BEND;
674                                                         bs3++;
675                                                 }
676
677                                         }
678                                 }
679
680                         }
681
682                 }
683                 /*scan for neighborhood done*/
684         }
685 }
686
687
688 static void add_2nd_order_springs(Object *ob, float stiffness)
689 {
690         int counter = 0;
691         BodySpring *bs_new;
692         stiffness *=stiffness;
693
694         add_2nd_order_roller(ob, stiffness, &counter, 0); /* counting */
695         if (counter) {
696                 /* resize spring-array to hold additional springs */
697                 bs_new= MEM_callocN((ob->soft->totspring + counter )*sizeof(BodySpring), "bodyspring");
698                 memcpy(bs_new, ob->soft->bspring, (ob->soft->totspring )*sizeof(BodySpring));
699
700                 if (ob->soft->bspring)
701                         MEM_freeN(ob->soft->bspring);
702                 ob->soft->bspring = bs_new;
703
704                 add_2nd_order_roller(ob, stiffness, &counter, 1); /* adding */
705                 ob->soft->totspring += counter;
706         }
707 }
708
709 static void add_bp_springlist(BodyPoint *bp, int springID)
710 {
711         int *newlist;
712
713         if (bp->springs == NULL) {
714                 bp->springs = MEM_callocN(sizeof(int), "bpsprings");
715                 bp->springs[0] = springID;
716                 bp->nofsprings = 1;
717         }
718         else {
719                 bp->nofsprings++;
720                 newlist = MEM_callocN(bp->nofsprings * sizeof(int), "bpsprings");
721                 memcpy(newlist, bp->springs, (bp->nofsprings-1)* sizeof(int));
722                 MEM_freeN(bp->springs);
723                 bp->springs = newlist;
724                 bp->springs[bp->nofsprings-1] = springID;
725         }
726 }
727
728 /* do this once when sb is build
729  * it is O(N^2) so scanning for springs every iteration is too expensive
730  */
731 static void build_bps_springlist(Object *ob)
732 {
733         SoftBody *sb= ob->soft; /* is supposed to be there */
734         BodyPoint *bp;
735         BodySpring *bs;
736         int a, b;
737
738         if (sb==NULL) return; /* paranoya check */
739
740         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
741                 /* throw away old list */
742                 if (bp->springs) {
743                         MEM_freeN(bp->springs);
744                         bp->springs=NULL;
745                 }
746                 /* scan for attached inner springs */
747                 for (b=sb->totspring, bs= sb->bspring; b>0; b--, bs++) {
748                         if (( (sb->totpoint-a) == bs->v1) ) {
749                                 add_bp_springlist(bp, sb->totspring -b);
750                         }
751                         if (( (sb->totpoint-a) == bs->v2) ) {
752                                 add_bp_springlist(bp, sb->totspring -b);
753                         }
754                 }/*for springs*/
755         }/*for bp*/
756 }
757
758 static void calculate_collision_balls(Object *ob)
759 {
760         SoftBody *sb= ob->soft; /* is supposed to be there */
761         BodyPoint *bp;
762         BodySpring *bs;
763         int a, b, akku_count;
764         float min, max, akku;
765
766         if (sb==NULL) return; /* paranoya check */
767
768         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
769                 bp->colball=0;
770                 akku =0.0f;
771                 akku_count=0;
772                 min = 1e22f;
773                 max = -1e22f;
774                 /* first estimation based on attached */
775                 for (b=bp->nofsprings;b>0;b--) {
776                         bs = sb->bspring + bp->springs[b-1];
777                         if (bs->springtype == SB_EDGE) {
778                                 akku += bs->len;
779                                 akku_count++;
780                                 min = min_ff(bs->len, min);
781                                 max = max_ff(bs->len, max);
782                         }
783                 }
784
785                 if (akku_count > 0) {
786                         if (sb->sbc_mode == SBC_MODE_MANUAL) {
787                                 bp->colball=sb->colball;
788                         }
789                         if (sb->sbc_mode == SBC_MODE_AVG) {
790                                 bp->colball = akku/(float)akku_count*sb->colball;
791                         }
792                         if (sb->sbc_mode == SBC_MODE_MIN) {
793                                 bp->colball=min*sb->colball;
794                         }
795                         if (sb->sbc_mode == SBC_MODE_MAX) {
796                                 bp->colball=max*sb->colball;
797                         }
798                         if (sb->sbc_mode == SBC_MODE_AVGMINMAX) {
799                                 bp->colball = (min + max)/2.0f*sb->colball;
800                         }
801                 }
802                 else bp->colball=0;
803         }/*for bp*/
804 }
805
806
807 /* creates new softbody if didn't exist yet, makes new points and springs arrays */
808 static void renew_softbody(Scene *scene, Object *ob, int totpoint, int totspring)
809 {
810         SoftBody *sb;
811         int i;
812         short softflag;
813         if (ob->soft==NULL) ob->soft= sbNew(scene);
814         else free_softbody_intern(ob->soft);
815         sb= ob->soft;
816         softflag=ob->softflag;
817
818         if (totpoint) {
819                 sb->totpoint= totpoint;
820                 sb->totspring= totspring;
821
822                 sb->bpoint= MEM_mallocN(totpoint*sizeof(BodyPoint), "bodypoint");
823                 if (totspring)
824                         sb->bspring= MEM_mallocN(totspring*sizeof(BodySpring), "bodyspring");
825
826                         /* initialize BodyPoint array */
827                 for (i=0; i<totpoint; i++) {
828                         BodyPoint *bp = &sb->bpoint[i];
829
830
831                         /* hum as far as i see this is overridden by _final_goal() now jow_go_for2_5 */
832                         /* sadly breaks compatibility with older versions */
833                         /* but makes goals behave the same for meshes, lattices and curves */
834                         if (softflag & OB_SB_GOAL) {
835                                 bp->goal= sb->defgoal;
836                         }
837                         else {
838                                 bp->goal= 0.0f;
839                                 /* so this will definily be below SOFTGOALSNAP */
840                         }
841
842                         bp->nofsprings= 0;
843                         bp->springs= NULL;
844                         bp->choke = 0.0f;
845                         bp->choke2 = 0.0f;
846                         bp->frozen = 1.0f;
847                         bp->colball = 0.0f;
848                         bp->loc_flag = 0;
849                         bp->springweight = 1.0f;
850                         bp->mass = 1.0f;
851                 }
852         }
853 }
854
855 static void free_softbody_baked(SoftBody *sb)
856 {
857         SBVertex *key;
858         int k;
859
860         for (k=0; k<sb->totkey; k++) {
861                 key= *(sb->keys + k);
862                 if (key) MEM_freeN(key);
863         }
864         if (sb->keys) MEM_freeN(sb->keys);
865
866         sb->keys= NULL;
867         sb->totkey= 0;
868 }
869 static void free_scratch(SoftBody *sb)
870 {
871         if (sb->scratch) {
872                 /* todo make sure everything is cleaned up nicly */
873                 if (sb->scratch->colliderhash) {
874                         BLI_ghash_free(
875                                 sb->scratch->colliderhash, NULL,
876                                 (GHashValFreeFP) ccd_mesh_free); /*this hoepfully will free all caches*/
877                         sb->scratch->colliderhash = NULL;
878                 }
879                 if (sb->scratch->bodyface) {
880                         MEM_freeN(sb->scratch->bodyface);
881                 }
882                 if (sb->scratch->Ref.ivert) {
883                         MEM_freeN(sb->scratch->Ref.ivert);
884                 }
885                 MEM_freeN(sb->scratch);
886                 sb->scratch = NULL;
887         }
888
889 }
890
891 /* only frees internal data */
892 static void free_softbody_intern(SoftBody *sb)
893 {
894         if (sb) {
895                 int a;
896                 BodyPoint *bp;
897
898                 if (sb->bpoint) {
899                         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
900                                 /* free spring list */
901                                 if (bp->springs != NULL) {
902                                         MEM_freeN(bp->springs);
903                                 }
904                         }
905                         MEM_freeN(sb->bpoint);
906                 }
907
908                 if (sb->bspring) MEM_freeN(sb->bspring);
909
910                 sb->totpoint= sb->totspring= 0;
911                 sb->bpoint= NULL;
912                 sb->bspring= NULL;
913
914                 free_scratch(sb);
915                 free_softbody_baked(sb);
916         }
917 }
918
919
920 /* ************ dynamics ********** */
921
922 /* the most general (micro physics correct) way to do collision
923  * (only needs the current particle position)
924  *
925  * it actually checks if the particle intrudes a short range force field generated
926  * by the faces of the target object and returns a force to drive the particel out
927  * the strength of the field grows exponetially if the particle is on the 'wrong' side of the face
928  * 'wrong' side : projection to the face normal is negative (all referred to a vertex in the face)
929  *
930  * flaw of this: 'fast' particles as well as 'fast' colliding faces
931  * give a 'tunnel' effect such that the particle passes through the force field
932  * without ever 'seeing' it
933  * this is fully compliant to heisenberg: h >= fuzzy(location) * fuzzy(time)
934  * besides our h is way larger than in QM because forces propagate way slower here
935  * we have to deal with fuzzy(time) in the range of 1/25 seconds (typical frame rate)
936  * yup collision targets are not known here any better
937  * and 1/25 second is looong compared to real collision events
938  * Q: why not use 'simple' collision here like bouncing back a particle
939  *   --> reverting is velocity on the face normal
940  * A: because our particles are not alone here
941  *    and need to tell their neighbors exactly what happens via spring forces
942  * unless sbObjectStep( .. ) is called on sub frame timing level
943  * BTW that also questions the use of a 'implicit' solvers on softbodies
944  * since that would only valid for 'slow' moving collision targets and dito particles
945  */
946
947 /* +++ dependency information functions*/
948
949 /**
950  * \note collection overrides scene when not NULL.
951  */
952 static int query_external_colliders(Depsgraph *depsgraph, Collection *collection)
953 {
954         unsigned int numobjects;
955         Object **objects = BKE_collision_objects_create(depsgraph, NULL, collection, &numobjects, eModifierType_Collision);
956         BKE_collision_objects_free(objects);
957
958         return (numobjects != 0);
959 }
960 /* --- dependency information functions*/
961
962
963 /* +++ the aabb "force" section*/
964 static int sb_detect_aabb_collisionCached(float UNUSED(force[3]), struct Object *vertexowner, float UNUSED(time))
965 {
966         Object *ob;
967         SoftBody *sb=vertexowner->soft;
968         GHash *hash;
969         GHashIterator *ihash;
970         float  aabbmin[3], aabbmax[3];
971         int deflected=0;
972 #if 0
973         int a;
974 #endif
975
976         if ((sb == NULL) || (sb->scratch ==NULL)) return 0;
977         copy_v3_v3(aabbmin, sb->scratch->aabbmin);
978         copy_v3_v3(aabbmax, sb->scratch->aabbmax);
979
980         hash  = vertexowner->soft->scratch->colliderhash;
981         ihash = BLI_ghashIterator_new(hash);
982         while (!BLI_ghashIterator_done(ihash)) {
983
984                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
985                 ob             = BLI_ghashIterator_getKey       (ihash);
986                 {
987                         /* only with deflecting set */
988                         if (ob->pd && ob->pd->deflect) {
989                                 if (ccdm) {
990                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
991                                             (aabbmax[1] < ccdm->bbmin[1]) ||
992                                             (aabbmax[2] < ccdm->bbmin[2]) ||
993                                             (aabbmin[0] > ccdm->bbmax[0]) ||
994                                             (aabbmin[1] > ccdm->bbmax[1]) ||
995                                             (aabbmin[2] > ccdm->bbmax[2]) )
996                                         {
997                                                 /* boxes don't intersect */
998                                                 BLI_ghashIterator_step(ihash);
999                                                 continue;
1000                                         }
1001
1002                                         /* so now we have the 2 boxes overlapping */
1003                                         /* forces actually not used */
1004                                         deflected = 2;
1005
1006                                 }
1007                                 else {
1008                                         /*aye that should be cached*/
1009                                         CLOG_ERROR(&LOG, "missing cache error");
1010                                         BLI_ghashIterator_step(ihash);
1011                                         continue;
1012                                 }
1013                         } /* if (ob->pd && ob->pd->deflect) */
1014                         BLI_ghashIterator_step(ihash);
1015                 }
1016         } /* while () */
1017         BLI_ghashIterator_free(ihash);
1018         return deflected;
1019 }
1020 /* --- the aabb section*/
1021
1022
1023 /* +++ the face external section*/
1024 static int sb_detect_face_pointCached(float face_v1[3], float face_v2[3], float face_v3[3], float *damp,
1025                                       float force[3], struct Object *vertexowner, float time)
1026 {
1027         Object *ob;
1028         GHash *hash;
1029         GHashIterator *ihash;
1030         float nv1[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1031         float facedist, outerfacethickness, tune = 10.f;
1032         int a, deflected=0;
1033
1034         aabbmin[0] = min_fff(face_v1[0], face_v2[0], face_v3[0]);
1035         aabbmin[1] = min_fff(face_v1[1], face_v2[1], face_v3[1]);
1036         aabbmin[2] = min_fff(face_v1[2], face_v2[2], face_v3[2]);
1037         aabbmax[0] = max_fff(face_v1[0], face_v2[0], face_v3[0]);
1038         aabbmax[1] = max_fff(face_v1[1], face_v2[1], face_v3[1]);
1039         aabbmax[2] = max_fff(face_v1[2], face_v2[2], face_v3[2]);
1040
1041         /* calculate face normal once again SIGH */
1042         sub_v3_v3v3(edge1, face_v1, face_v2);
1043         sub_v3_v3v3(edge2, face_v3, face_v2);
1044         cross_v3_v3v3(d_nvect, edge2, edge1);
1045         normalize_v3(d_nvect);
1046
1047
1048         hash  = vertexowner->soft->scratch->colliderhash;
1049         ihash = BLI_ghashIterator_new(hash);
1050         while (!BLI_ghashIterator_done(ihash)) {
1051
1052                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1053                 ob             = BLI_ghashIterator_getKey       (ihash);
1054                 {
1055                         /* only with deflecting set */
1056                         if (ob->pd && ob->pd->deflect) {
1057                                 const MVert *mvert= NULL;
1058                                 const MVert *mprevvert= NULL;
1059                                 if (ccdm) {
1060                                         mvert = ccdm->mvert;
1061                                         a     = ccdm->mvert_num;
1062                                         mprevvert= ccdm->mprevvert;
1063                                         outerfacethickness = ob->pd->pdef_sboft;
1064                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1065                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1066                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1067                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1068                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1069                                             (aabbmin[2] > ccdm->bbmax[2]) )
1070                                         {
1071                                                 /* boxes don't intersect */
1072                                                 BLI_ghashIterator_step(ihash);
1073                                                 continue;
1074                                         }
1075
1076                                 }
1077                                 else {
1078                                         /*aye that should be cached*/
1079                                         CLOG_ERROR(&LOG, "missing cache error");
1080                                         BLI_ghashIterator_step(ihash);
1081                                         continue;
1082                                 }
1083
1084
1085                                 /* use mesh*/
1086                                 if (mvert) {
1087                                         while (a) {
1088                                                 copy_v3_v3(nv1, mvert[a-1].co);
1089                                                 if (mprevvert) {
1090                                                         mul_v3_fl(nv1, time);
1091                                                         madd_v3_v3fl(nv1, mprevvert[a - 1].co, 1.0f - time);
1092                                                 }
1093                                                 /* origin to face_v2*/
1094                                                 sub_v3_v3(nv1, face_v2);
1095                                                 facedist = dot_v3v3(nv1, d_nvect);
1096                                                 if (ABS(facedist)<outerfacethickness) {
1097                                                         if (isect_point_tri_prism_v3(nv1, face_v1, face_v2, face_v3) ) {
1098                                                                 float df;
1099                                                                 if (facedist > 0) {
1100                                                                         df = (outerfacethickness-facedist)/outerfacethickness;
1101                                                                 }
1102                                                                 else {
1103                                                                         df = (outerfacethickness+facedist)/outerfacethickness;
1104                                                                 }
1105
1106                                                                 *damp=df*tune*ob->pd->pdef_sbdamp;
1107
1108                                                                 df = 0.01f * expf(-100.0f * df);
1109                                                                 madd_v3_v3fl(force, d_nvect, -df);
1110                                                                 deflected = 3;
1111                                                         }
1112                                                 }
1113                                                 a--;
1114                                         }/* while (a)*/
1115                                 } /* if (mvert) */
1116                         } /* if (ob->pd && ob->pd->deflect) */
1117                         BLI_ghashIterator_step(ihash);
1118                 }
1119         } /* while () */
1120         BLI_ghashIterator_free(ihash);
1121         return deflected;
1122 }
1123
1124
1125 static int sb_detect_face_collisionCached(float face_v1[3], float face_v2[3], float face_v3[3], float *damp,
1126                                           float force[3], struct Object *vertexowner, float time)
1127 {
1128         Object *ob;
1129         GHash *hash;
1130         GHashIterator *ihash;
1131         float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1132         float t, tune = 10.0f;
1133         int a, deflected=0;
1134
1135         aabbmin[0] = min_fff(face_v1[0], face_v2[0], face_v3[0]);
1136         aabbmin[1] = min_fff(face_v1[1], face_v2[1], face_v3[1]);
1137         aabbmin[2] = min_fff(face_v1[2], face_v2[2], face_v3[2]);
1138         aabbmax[0] = max_fff(face_v1[0], face_v2[0], face_v3[0]);
1139         aabbmax[1] = max_fff(face_v1[1], face_v2[1], face_v3[1]);
1140         aabbmax[2] = max_fff(face_v1[2], face_v2[2], face_v3[2]);
1141
1142         hash  = vertexowner->soft->scratch->colliderhash;
1143         ihash = BLI_ghashIterator_new(hash);
1144         while (!BLI_ghashIterator_done(ihash)) {
1145
1146                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1147                 ob             = BLI_ghashIterator_getKey       (ihash);
1148                 {
1149                         /* only with deflecting set */
1150                         if (ob->pd && ob->pd->deflect) {
1151                                 const MVert *mvert = NULL;
1152                                 const MVert *mprevvert = NULL;
1153                                 const MVertTri *vt = NULL;
1154                                 const ccdf_minmax *mima = NULL;
1155
1156                                 if (ccdm) {
1157                                         mvert = ccdm->mvert;
1158                                         vt = ccdm->tri;
1159                                         mprevvert = ccdm->mprevvert;
1160                                         mima = ccdm->mima;
1161                                         a = ccdm->tri_num;
1162
1163                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1164                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1165                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1166                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1167                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1168                                             (aabbmin[2] > ccdm->bbmax[2]) )
1169                                         {
1170                                                 /* boxes don't intersect */
1171                                                 BLI_ghashIterator_step(ihash);
1172                                                 continue;
1173                                         }
1174
1175                                 }
1176                                 else {
1177                                         /*aye that should be cached*/
1178                                         CLOG_ERROR(&LOG, "missing cache error");
1179                                         BLI_ghashIterator_step(ihash);
1180                                         continue;
1181                                 }
1182
1183
1184                                 /* use mesh*/
1185                                 while (a--) {
1186                                         if ((aabbmax[0] < mima->minx) ||
1187                                             (aabbmin[0] > mima->maxx) ||
1188                                             (aabbmax[1] < mima->miny) ||
1189                                             (aabbmin[1] > mima->maxy) ||
1190                                             (aabbmax[2] < mima->minz) ||
1191                                             (aabbmin[2] > mima->maxz))
1192                                         {
1193                                                 mima++;
1194                                                 vt++;
1195                                                 continue;
1196                                         }
1197
1198
1199                                         if (mvert) {
1200
1201                                                 copy_v3_v3(nv1, mvert[vt->tri[0]].co);
1202                                                 copy_v3_v3(nv2, mvert[vt->tri[1]].co);
1203                                                 copy_v3_v3(nv3, mvert[vt->tri[2]].co);
1204
1205                                                 if (mprevvert) {
1206                                                         mul_v3_fl(nv1, time);
1207                                                         madd_v3_v3fl(nv1, mprevvert[vt->tri[0]].co, 1.0f - time);
1208
1209                                                         mul_v3_fl(nv2, time);
1210                                                         madd_v3_v3fl(nv2, mprevvert[vt->tri[1]].co, 1.0f - time);
1211
1212                                                         mul_v3_fl(nv3, time);
1213                                                         madd_v3_v3fl(nv3, mprevvert[vt->tri[2]].co, 1.0f - time);
1214                                                 }
1215                                         }
1216
1217                                         /* switch origin to be nv2*/
1218                                         sub_v3_v3v3(edge1, nv1, nv2);
1219                                         sub_v3_v3v3(edge2, nv3, nv2);
1220                                         cross_v3_v3v3(d_nvect, edge2, edge1);
1221                                         normalize_v3(d_nvect);
1222                                         if (isect_line_segment_tri_v3(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
1223                                             isect_line_segment_tri_v3(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1224                                             isect_line_segment_tri_v3(nv3, nv1, face_v1, face_v2, face_v3, &t, NULL) )
1225                                         {
1226                                                 madd_v3_v3fl(force, d_nvect, -0.5f);
1227                                                 *damp=tune*ob->pd->pdef_sbdamp;
1228                                                 deflected = 2;
1229                                         }
1230                                         mima++;
1231                                         vt++;
1232                                 }/* while a */
1233                         } /* if (ob->pd && ob->pd->deflect) */
1234                         BLI_ghashIterator_step(ihash);
1235                 }
1236         } /* while () */
1237         BLI_ghashIterator_free(ihash);
1238         return deflected;
1239 }
1240
1241
1242
1243 static void scan_for_ext_face_forces(Object *ob, float timenow)
1244 {
1245         SoftBody *sb = ob->soft;
1246         BodyFace *bf;
1247         int a;
1248         float damp=0.0f, choke=1.0f;
1249         float tune = -10.0f;
1250         float feedback[3];
1251
1252         if (sb && sb->scratch->totface) {
1253
1254
1255                 bf = sb->scratch->bodyface;
1256                 for (a=0; a<sb->scratch->totface; a++, bf++) {
1257                         bf->ext_force[0]=bf->ext_force[1]=bf->ext_force[2]=0.0f;
1258 /*+++edges intruding*/
1259                         bf->flag &= ~BFF_INTERSECT;
1260                         zero_v3(feedback);
1261                         if (sb_detect_face_collisionCached(
1262                                 sb->bpoint[bf->v1].pos, sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
1263                                 &damp, feedback, ob, timenow))
1264                         {
1265                                 madd_v3_v3fl(sb->bpoint[bf->v1].force, feedback, tune);
1266                                 madd_v3_v3fl(sb->bpoint[bf->v2].force, feedback, tune);
1267                                 madd_v3_v3fl(sb->bpoint[bf->v3].force, feedback, tune);
1268 //                              madd_v3_v3fl(bf->ext_force, feedback, tune);
1269                                 bf->flag |= BFF_INTERSECT;
1270                                 choke = min_ff(max_ff(damp, choke), 1.0f);
1271                         }
1272 /*---edges intruding*/
1273
1274 /*+++ close vertices*/
1275                         if (( bf->flag & BFF_INTERSECT)==0) {
1276                                 bf->flag &= ~BFF_CLOSEVERT;
1277                                 tune = -1.0f;
1278                                 zero_v3(feedback);
1279                                 if (sb_detect_face_pointCached(
1280                                         sb->bpoint[bf->v1].pos, sb->bpoint[bf->v2].pos, sb->bpoint[bf->v3].pos,
1281                                         &damp,  feedback, ob, timenow))
1282                                 {
1283                                         madd_v3_v3fl(sb->bpoint[bf->v1].force, feedback, tune);
1284                                         madd_v3_v3fl(sb->bpoint[bf->v2].force, feedback, tune);
1285                                         madd_v3_v3fl(sb->bpoint[bf->v3].force, feedback, tune);
1286 //                                      madd_v3_v3fl(bf->ext_force, feedback, tune);
1287                                         bf->flag |= BFF_CLOSEVERT;
1288                                         choke = min_ff(max_ff(damp, choke), 1.0f);
1289                                 }
1290                         }
1291 /*--- close vertices*/
1292                 }
1293                 bf = sb->scratch->bodyface;
1294                 for (a=0; a<sb->scratch->totface; a++, bf++) {
1295                         if (( bf->flag & BFF_INTERSECT) || ( bf->flag & BFF_CLOSEVERT)) {
1296                                 sb->bpoint[bf->v1].choke2 = max_ff(sb->bpoint[bf->v1].choke2, choke);
1297                                 sb->bpoint[bf->v2].choke2 = max_ff(sb->bpoint[bf->v2].choke2, choke);
1298                                 sb->bpoint[bf->v3].choke2 = max_ff(sb->bpoint[bf->v3].choke2, choke);
1299                         }
1300                 }
1301         }
1302 }
1303
1304 /*  --- the face external section*/
1305
1306
1307 /* +++ the spring external section*/
1308
1309 static int sb_detect_edge_collisionCached(float edge_v1[3], float edge_v2[3], float *damp,
1310                                                                    float force[3], struct Object *vertexowner, float time)
1311 {
1312         Object *ob;
1313         GHash *hash;
1314         GHashIterator *ihash;
1315         float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], aabbmin[3], aabbmax[3];
1316         float t, el;
1317         int a, deflected=0;
1318
1319         minmax_v3v3_v3(aabbmin, aabbmax, edge_v1);
1320         minmax_v3v3_v3(aabbmin, aabbmax, edge_v2);
1321
1322         el = len_v3v3(edge_v1, edge_v2);
1323
1324         hash  = vertexowner->soft->scratch->colliderhash;
1325         ihash = BLI_ghashIterator_new(hash);
1326         while (!BLI_ghashIterator_done(ihash)) {
1327
1328                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1329                 ob             = BLI_ghashIterator_getKey       (ihash);
1330                 {
1331                         /* only with deflecting set */
1332                         if (ob->pd && ob->pd->deflect) {
1333                                 const MVert *mvert = NULL;
1334                                 const MVert *mprevvert = NULL;
1335                                 const MVertTri *vt = NULL;
1336                                 const ccdf_minmax *mima = NULL;
1337
1338                                 if (ccdm) {
1339                                         mvert = ccdm->mvert;
1340                                         mprevvert = ccdm->mprevvert;
1341                                         vt = ccdm->tri;
1342                                         mima = ccdm->mima;
1343                                         a = ccdm->tri_num;
1344
1345                                         if ((aabbmax[0] < ccdm->bbmin[0]) ||
1346                                             (aabbmax[1] < ccdm->bbmin[1]) ||
1347                                             (aabbmax[2] < ccdm->bbmin[2]) ||
1348                                             (aabbmin[0] > ccdm->bbmax[0]) ||
1349                                             (aabbmin[1] > ccdm->bbmax[1]) ||
1350                                             (aabbmin[2] > ccdm->bbmax[2]) )
1351                                         {
1352                                                 /* boxes don't intersect */
1353                                                 BLI_ghashIterator_step(ihash);
1354                                                 continue;
1355                                         }
1356
1357                                 }
1358                                 else {
1359                                         /*aye that should be cached*/
1360                                         CLOG_ERROR(&LOG, "missing cache error");
1361                                         BLI_ghashIterator_step(ihash);
1362                                         continue;
1363                                 }
1364
1365
1366                                 /* use mesh*/
1367                                 while (a--) {
1368                                         if ((aabbmax[0] < mima->minx) ||
1369                                             (aabbmin[0] > mima->maxx) ||
1370                                             (aabbmax[1] < mima->miny) ||
1371                                             (aabbmin[1] > mima->maxy) ||
1372                                             (aabbmax[2] < mima->minz) ||
1373                                             (aabbmin[2] > mima->maxz))
1374                                         {
1375                                                 mima++;
1376                                                 vt++;
1377                                                 continue;
1378                                         }
1379
1380
1381                                         if (mvert) {
1382
1383                                                 copy_v3_v3(nv1, mvert[vt->tri[0]].co);
1384                                                 copy_v3_v3(nv2, mvert[vt->tri[1]].co);
1385                                                 copy_v3_v3(nv3, mvert[vt->tri[2]].co);
1386
1387                                                 if (mprevvert) {
1388                                                         mul_v3_fl(nv1, time);
1389                                                         madd_v3_v3fl(nv1, mprevvert[vt->tri[0]].co, 1.0f - time);
1390
1391                                                         mul_v3_fl(nv2, time);
1392                                                         madd_v3_v3fl(nv2, mprevvert[vt->tri[1]].co, 1.0f - time);
1393
1394                                                         mul_v3_fl(nv3, time);
1395                                                         madd_v3_v3fl(nv3, mprevvert[vt->tri[2]].co, 1.0f - time);
1396                                                 }
1397                                         }
1398
1399                                         /* switch origin to be nv2*/
1400                                         sub_v3_v3v3(edge1, nv1, nv2);
1401                                         sub_v3_v3v3(edge2, nv3, nv2);
1402
1403                                         cross_v3_v3v3(d_nvect, edge2, edge1);
1404                                         normalize_v3(d_nvect);
1405                                         if (isect_line_segment_tri_v3(edge_v1, edge_v2, nv1, nv2, nv3, &t, NULL)) {
1406                                                 float v1[3], v2[3];
1407                                                 float intrusiondepth, i1, i2;
1408                                                 sub_v3_v3v3(v1, edge_v1, nv2);
1409                                                 sub_v3_v3v3(v2, edge_v2, nv2);
1410                                                 i1 = dot_v3v3(v1, d_nvect);
1411                                                 i2 = dot_v3v3(v2, d_nvect);
1412                                                 intrusiondepth = -min_ff(i1, i2) / el;
1413                                                 madd_v3_v3fl(force, d_nvect, intrusiondepth);
1414                                                 *damp=ob->pd->pdef_sbdamp;
1415                                                 deflected = 2;
1416                                         }
1417
1418                                         mima++;
1419                                         vt++;
1420                                 }/* while a */
1421                         } /* if (ob->pd && ob->pd->deflect) */
1422                         BLI_ghashIterator_step(ihash);
1423                 }
1424         } /* while () */
1425         BLI_ghashIterator_free(ihash);
1426         return deflected;
1427 }
1428
1429 static void _scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow, int ifirst, int ilast, struct ListBase *effectors)
1430 {
1431         SoftBody *sb = ob->soft;
1432         int a;
1433         float damp;
1434         float feedback[3];
1435
1436         if (sb && sb->totspring) {
1437                 for (a=ifirst; a<ilast; a++) {
1438                         BodySpring *bs = &sb->bspring[a];
1439                         bs->ext_force[0]=bs->ext_force[1]=bs->ext_force[2]=0.0f;
1440                         feedback[0]=feedback[1]=feedback[2]=0.0f;
1441                         bs->flag &= ~BSF_INTERSECT;
1442
1443                         if (bs->springtype == SB_EDGE) {
1444                                 /* +++ springs colliding */
1445                                 if (ob->softflag & OB_SB_EDGECOLL) {
1446                                         if ( sb_detect_edge_collisionCached (sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos,
1447                                                 &damp, feedback, ob, timenow)) {
1448                                                         add_v3_v3(bs->ext_force, feedback);
1449                                                         bs->flag |= BSF_INTERSECT;
1450                                                         //bs->cf=damp;
1451                                                         bs->cf=sb->choke*0.01f;
1452
1453                                         }
1454                                 }
1455                                 /* ---- springs colliding */
1456
1457                                 /* +++ springs seeing wind ... n stuff depending on their orientation*/
1458                                 /* note we don't use sb->mediafrict but use sb->aeroedge for magnitude of effect*/
1459                                 if (sb->aeroedge) {
1460                                         float vel[3], sp[3], pr[3], force[3];
1461                                         float f, windfactor  = 0.25f;
1462                                         /*see if we have wind*/
1463                                         if (effectors) {
1464                                                 EffectedPoint epoint;
1465                                                 float speed[3] = {0.0f, 0.0f, 0.0f};
1466                                                 float pos[3];
1467                                                 mid_v3_v3v3(pos, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1468                                                 mid_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1469                                                 pd_point_from_soft(scene, pos, vel, -1, &epoint);
1470                                                 BKE_effectors_apply(effectors, NULL, sb->effector_weights, &epoint, force, speed);
1471
1472                                                 mul_v3_fl(speed, windfactor);
1473                                                 add_v3_v3(vel, speed);
1474                                         }
1475                                         /* media in rest */
1476                                         else {
1477                                                 add_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec);
1478                                         }
1479                                         f = normalize_v3(vel);
1480                                         f = -0.0001f*f*f*sb->aeroedge;
1481                                         /* (todo) add a nice angle dependent function done for now BUT */
1482                                         /* still there could be some nice drag/lift function, but who needs it */
1483
1484                                         sub_v3_v3v3(sp, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos);
1485                                         project_v3_v3v3(pr, vel, sp);
1486                                         sub_v3_v3(vel, pr);
1487                                         normalize_v3(vel);
1488                                         if (ob->softflag & OB_SB_AERO_ANGLE) {
1489                                                 normalize_v3(sp);
1490                                                 madd_v3_v3fl(bs->ext_force, vel, f * (1.0f - fabsf(dot_v3v3(vel, sp))));
1491                                         }
1492                                         else {
1493                                                 madd_v3_v3fl(bs->ext_force, vel, f); // to keep compatible with 2.45 release files
1494                                         }
1495                                 }
1496                                 /* --- springs seeing wind */
1497                         }
1498                 }
1499         }
1500 }
1501
1502 static void *exec_scan_for_ext_spring_forces(void *data)
1503 {
1504         SB_thread_context *pctx = (SB_thread_context*)data;
1505         _scan_for_ext_spring_forces(pctx->scene, pctx->ob, pctx->timenow, pctx->ifirst, pctx->ilast, pctx->effectors);
1506         return NULL;
1507 }
1508
1509 static void sb_sfesf_threads_run(struct Depsgraph *depsgraph, Scene *scene, struct Object *ob, float timenow, int totsprings, int *UNUSED(ptr_to_break_func(void)))
1510 {
1511         ListBase threads;
1512         SB_thread_context *sb_threads;
1513         int i, totthread, left, dec;
1514         int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
1515
1516         ListBase *effectors = BKE_effectors_create(depsgraph, ob, NULL, ob->soft->effector_weights);
1517
1518         /* figure the number of threads while preventing pretty pointless threading overhead */
1519         totthread= BKE_scene_num_threads(scene);
1520         /* what if we got zillions of CPUs running but less to spread*/
1521         while ((totsprings/totthread < lowsprings) && (totthread > 1)) {
1522                 totthread--;
1523         }
1524
1525         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBSpringsThread");
1526         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
1527         left = totsprings;
1528         dec = totsprings/totthread +1;
1529         for (i=0; i<totthread; i++) {
1530                 sb_threads[i].scene = scene;
1531                 sb_threads[i].ob = ob;
1532                 sb_threads[i].forcetime = 0.0; // not used here
1533                 sb_threads[i].timenow = timenow;
1534                 sb_threads[i].ilast   = left;
1535                 left = left - dec;
1536                 if (left >0) {
1537                         sb_threads[i].ifirst  = left;
1538                 }
1539                 else
1540                         sb_threads[i].ifirst  = 0;
1541                 sb_threads[i].effectors = effectors;
1542                 sb_threads[i].do_deflector = false;// not used here
1543                 sb_threads[i].fieldfactor = 0.0f;// not used here
1544                 sb_threads[i].windfactor  = 0.0f;// not used here
1545                 sb_threads[i].nr= i;
1546                 sb_threads[i].tot= totthread;
1547         }
1548         if (totthread > 1) {
1549                 BLI_threadpool_init(&threads, exec_scan_for_ext_spring_forces, totthread);
1550
1551                 for (i=0; i<totthread; i++)
1552                         BLI_threadpool_insert(&threads, &sb_threads[i]);
1553
1554                 BLI_threadpool_end(&threads);
1555         }
1556         else
1557                 exec_scan_for_ext_spring_forces(&sb_threads[0]);
1558         /* clean up */
1559         MEM_freeN(sb_threads);
1560
1561         BKE_effectors_free(effectors);
1562 }
1563
1564
1565 /* --- the spring external section*/
1566
1567 static int choose_winner(float*w, float* pos, float*a, float*b, float*c, float*ca, float*cb, float*cc)
1568 {
1569         float mindist, cp;
1570         int winner =1;
1571         mindist = fabsf(dot_v3v3(pos, a));
1572
1573         cp = fabsf(dot_v3v3(pos, b));
1574         if ( mindist < cp ) {
1575                 mindist = cp;
1576                 winner =2;
1577         }
1578
1579         cp = fabsf(dot_v3v3(pos, c));
1580         if (mindist < cp ) {
1581                 mindist = cp;
1582                 winner =3;
1583         }
1584         switch (winner) {
1585                 case 1: copy_v3_v3(w, ca); break;
1586                 case 2: copy_v3_v3(w, cb); break;
1587                 case 3: copy_v3_v3(w, cc);
1588         }
1589         return(winner);
1590 }
1591
1592
1593
1594 static int sb_detect_vertex_collisionCached(
1595         float opco[3], float facenormal[3], float *damp,
1596         float force[3], struct Object *vertexowner,
1597         float time, float vel[3], float *intrusion)
1598 {
1599         Object *ob= NULL;
1600         GHash *hash;
1601         GHashIterator *ihash;
1602         float nv1[3], nv2[3], nv3[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3], avel[3] = {0.0, 0.0, 0.0},
1603               vv1[3], vv2[3], vv3[3], coledge[3] = {0.0f, 0.0f, 0.0f}, mindistedge = 1000.0f,
1604               outerforceaccu[3], innerforceaccu[3],
1605               facedist, /* n_mag, */ /* UNUSED */ force_mag_norm, minx, miny, minz, maxx, maxy, maxz,
1606               innerfacethickness = -0.5f, outerfacethickness = 0.2f,
1607               ee = 5.0f, ff = 0.1f, fa=1;
1608         int a, deflected=0, cavel=0, ci=0;
1609 /* init */
1610         *intrusion = 0.0f;
1611         hash  = vertexowner->soft->scratch->colliderhash;
1612         ihash = BLI_ghashIterator_new(hash);
1613         outerforceaccu[0]=outerforceaccu[1]=outerforceaccu[2]=0.0f;
1614         innerforceaccu[0]=innerforceaccu[1]=innerforceaccu[2]=0.0f;
1615 /* go */
1616         while (!BLI_ghashIterator_done(ihash)) {
1617
1618                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1619                 ob             = BLI_ghashIterator_getKey       (ihash);
1620                 {
1621                         /* only with deflecting set */
1622                         if (ob->pd && ob->pd->deflect) {
1623                                 const MVert *mvert = NULL;
1624                                 const MVert *mprevvert = NULL;
1625                                 const MVertTri *vt = NULL;
1626                                 const ccdf_minmax *mima = NULL;
1627
1628                                 if (ccdm) {
1629                                         mvert = ccdm->mvert;
1630                                         mprevvert = ccdm->mprevvert;
1631                                         vt = ccdm->tri;
1632                                         mima = ccdm->mima;
1633                                         a = ccdm->tri_num;
1634
1635                                         minx = ccdm->bbmin[0];
1636                                         miny = ccdm->bbmin[1];
1637                                         minz = ccdm->bbmin[2];
1638
1639                                         maxx = ccdm->bbmax[0];
1640                                         maxy = ccdm->bbmax[1];
1641                                         maxz = ccdm->bbmax[2];
1642
1643                                         if ((opco[0] < minx) ||
1644                                             (opco[1] < miny) ||
1645                                             (opco[2] < minz) ||
1646                                             (opco[0] > maxx) ||
1647                                             (opco[1] > maxy) ||
1648                                             (opco[2] > maxz) )
1649                                         {
1650                                                 /* outside the padded boundbox --> collision object is too far away */
1651                                                 BLI_ghashIterator_step(ihash);
1652                                                 continue;
1653                                         }
1654                                 }
1655                                 else {
1656                                         /*aye that should be cached*/
1657                                         CLOG_ERROR(&LOG, "missing cache error");
1658                                         BLI_ghashIterator_step(ihash);
1659                                         continue;
1660                                 }
1661
1662                                 /* do object level stuff */
1663                                 /* need to have user control for that since it depends on model scale */
1664                                 innerfacethickness = -ob->pd->pdef_sbift;
1665                                 outerfacethickness =  ob->pd->pdef_sboft;
1666                                 fa = (ff*outerfacethickness-outerfacethickness);
1667                                 fa *= fa;
1668                                 fa = 1.0f/fa;
1669                                 avel[0]=avel[1]=avel[2]=0.0f;
1670                                 /* use mesh*/
1671                                 while (a--) {
1672                                         if ((opco[0] < mima->minx) ||
1673                                             (opco[0] > mima->maxx) ||
1674                                             (opco[1] < mima->miny) ||
1675                                             (opco[1] > mima->maxy) ||
1676                                             (opco[2] < mima->minz) ||
1677                                             (opco[2] > mima->maxz))
1678                                         {
1679                                                 mima++;
1680                                                 vt++;
1681                                                 continue;
1682                                         }
1683
1684                                         if (mvert) {
1685
1686                                                 copy_v3_v3(nv1, mvert[vt->tri[0]].co);
1687                                                 copy_v3_v3(nv2, mvert[vt->tri[1]].co);
1688                                                 copy_v3_v3(nv3, mvert[vt->tri[2]].co);
1689
1690                                                 if (mprevvert) {
1691                                                         /* grab the average speed of the collider vertices
1692                                                          * before we spoil nvX
1693                                                          * humm could be done once a SB steps but then we' need to store that too
1694                                                          * since the AABB reduced propabitlty to get here drasticallly
1695                                                          * it might be a nice tradeof CPU <--> memory
1696                                                          */
1697                                                         sub_v3_v3v3(vv1, nv1, mprevvert[vt->tri[0]].co);
1698                                                         sub_v3_v3v3(vv2, nv2, mprevvert[vt->tri[1]].co);
1699                                                         sub_v3_v3v3(vv3, nv3, mprevvert[vt->tri[2]].co);
1700
1701                                                         mul_v3_fl(nv1, time);
1702                                                         madd_v3_v3fl(nv1, mprevvert[vt->tri[0]].co, 1.0f - time);
1703
1704                                                         mul_v3_fl(nv2, time);
1705                                                         madd_v3_v3fl(nv2, mprevvert[vt->tri[1]].co, 1.0f - time);
1706
1707                                                         mul_v3_fl(nv3, time);
1708                                                         madd_v3_v3fl(nv3, mprevvert[vt->tri[2]].co, 1.0f - time);
1709                                                 }
1710                                         }
1711
1712                                         /* switch origin to be nv2*/
1713                                         sub_v3_v3v3(edge1, nv1, nv2);
1714                                         sub_v3_v3v3(edge2, nv3, nv2);
1715                                         sub_v3_v3v3(dv1, opco, nv2); /* abuse dv1 to have vertex in question at *origin* of triangle */
1716
1717                                         cross_v3_v3v3(d_nvect, edge2, edge1);
1718                                         /* n_mag = */ /* UNUSED */ normalize_v3(d_nvect);
1719                                         facedist = dot_v3v3(dv1, d_nvect);
1720                                         // so rules are
1721                                         //
1722
1723                                         if ((facedist > innerfacethickness) && (facedist < outerfacethickness)) {
1724                                                 if (isect_point_tri_prism_v3(opco, nv1, nv2, nv3) ) {
1725                                                         force_mag_norm =(float)exp(-ee*facedist);
1726                                                         if (facedist > outerfacethickness*ff)
1727                                                                 force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
1728                                                         *damp=ob->pd->pdef_sbdamp;
1729                                                         if (facedist > 0.0f) {
1730                                                                 *damp *= (1.0f - facedist/outerfacethickness);
1731                                                                 madd_v3_v3fl(outerforceaccu, d_nvect, force_mag_norm);
1732                                                                 deflected = 3;
1733
1734                                                         }
1735                                                         else {
1736                                                                 madd_v3_v3fl(innerforceaccu, d_nvect, force_mag_norm);
1737                                                                 if (deflected < 2) deflected = 2;
1738                                                         }
1739                                                         if ((mprevvert) && (*damp > 0.0f)) {
1740                                                                 choose_winner(ve, opco, nv1, nv2, nv3, vv1, vv2, vv3);
1741                                                                 add_v3_v3(avel, ve);
1742                                                                 cavel ++;
1743                                                         }
1744                                                         *intrusion += facedist;
1745                                                         ci++;
1746                                                 }
1747                                         }
1748
1749                                         mima++;
1750                                         vt++;
1751                                 }/* while a */
1752                         } /* if (ob->pd && ob->pd->deflect) */
1753                         BLI_ghashIterator_step(ihash);
1754                 }
1755         } /* while () */
1756
1757         if (deflected == 1) { // no face but 'outer' edge cylinder sees vert
1758                 force_mag_norm =(float)exp(-ee*mindistedge);
1759                 if (mindistedge > outerfacethickness*ff)
1760                         force_mag_norm =(float)force_mag_norm*fa*(mindistedge - outerfacethickness)*(mindistedge - outerfacethickness);
1761                 madd_v3_v3fl(force, coledge, force_mag_norm);
1762                 *damp=ob->pd->pdef_sbdamp;
1763                 if (mindistedge > 0.0f) {
1764                         *damp *= (1.0f - mindistedge/outerfacethickness);
1765                 }
1766
1767         }
1768         if (deflected == 2) { //  face inner detected
1769                 add_v3_v3(force, innerforceaccu);
1770         }
1771         if (deflected == 3) { //  face outer detected
1772                 add_v3_v3(force, outerforceaccu);
1773         }
1774
1775         BLI_ghashIterator_free(ihash);
1776         if (cavel) mul_v3_fl(avel, 1.0f/(float)cavel);
1777         copy_v3_v3(vel, avel);
1778         if (ci) *intrusion /= ci;
1779         if (deflected) {
1780                 normalize_v3_v3(facenormal, force);
1781         }
1782         return deflected;
1783 }
1784
1785
1786 /* sandbox to plug in various deflection algos */
1787 static int sb_deflect_face(Object *ob, float *actpos, float *facenormal, float *force, float *cf, float time, float *vel, float *intrusion)
1788 {
1789         float s_actpos[3];
1790         int deflected;
1791         copy_v3_v3(s_actpos, actpos);
1792         deflected= sb_detect_vertex_collisionCached(s_actpos, facenormal, cf, force, ob, time, vel, intrusion);
1793         //deflected= sb_detect_vertex_collisionCachedEx(s_actpos, facenormal, cf, force, ob, time, vel, intrusion);
1794         return(deflected);
1795 }
1796
1797 /* hiding this for now .. but the jacobian may pop up on other tasks .. so i'd like to keep it */
1798 #if 0
1799 static void dfdx_spring(int ia, int ic, int op, float dir[3], float L, float len, float factor)
1800 {
1801         float m, delta_ij;
1802         int i, j;
1803         if (L < len) {
1804                 for (i=0;i<3;i++) {
1805                         for (j=0;j<3;j++) {
1806                                 delta_ij = (i==j ? (1.0f): (0.0f));
1807                                 m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j]));
1808                                 EIG_linear_solver_matrix_add(ia+i, op+ic+j, m);
1809                         }
1810                 }
1811         }
1812         else {
1813                 for (i=0;i<3;i++) {
1814                         for (j=0;j<3;j++) {
1815                                 m=factor*dir[i]*dir[j];
1816                                 EIG_linear_solver_matrix_add(ia+i, op+ic+j, m);
1817                         }
1818                 }
1819         }
1820 }
1821
1822
1823 static void dfdx_goal(int ia, int ic, int op, float factor)
1824 {
1825         int i;
1826         for (i=0;i<3;i++) EIG_linear_solver_matrix_add(ia+i, op+ic+i, factor);
1827 }
1828
1829 static void dfdv_goal(int ia, int ic, float factor)
1830 {
1831         int i;
1832         for (i=0;i<3;i++) EIG_linear_solver_matrix_add(ia+i, ic+i, factor);
1833 }
1834 #endif  /* if 0 */
1835
1836 static void sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float UNUSED(forcetime))
1837 {
1838         SoftBody *sb= ob->soft; /* is supposed to be there */
1839         BodyPoint  *bp1, *bp2;
1840
1841         float dir[3], dvel[3];
1842         float distance, forcefactor, kd, absvel, projvel, kw;
1843 #if 0   /* UNUSED */
1844         int ia, ic;
1845 #endif
1846         /* prepare depending on which side of the spring we are on */
1847         if (bpi == bs->v1) {
1848                 bp1 = &sb->bpoint[bs->v1];
1849                 bp2 = &sb->bpoint[bs->v2];
1850 #if 0   /* UNUSED */
1851                 ia =3*bs->v1;
1852                 ic =3*bs->v2;
1853 #endif
1854         }
1855         else if (bpi == bs->v2) {
1856                 bp1 = &sb->bpoint[bs->v2];
1857                 bp2 = &sb->bpoint[bs->v1];
1858 #if 0   /* UNUSED */
1859                 ia =3*bs->v2;
1860                 ic =3*bs->v1;
1861 #endif
1862         }
1863         else {
1864                 /* TODO make this debug option */
1865                 /**/
1866                 CLOG_WARN(&LOG, "bodypoint <bpi> is not attached to spring  <*bs>");
1867                 return;
1868         }
1869
1870         /* do bp1 <--> bp2 elastic */
1871         sub_v3_v3v3(dir, bp1->pos, bp2->pos);
1872         distance = normalize_v3(dir);
1873         if (bs->len < distance)
1874                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
1875         else
1876                 iks  = 1.0f/(1.0f-sb->inpush)-1.0f ;/* inner spring constants function */
1877
1878         if (bs->len > 0.0f) /* check for degenerated springs */
1879                 forcefactor = iks/bs->len;
1880         else
1881                 forcefactor = iks;
1882         kw = (bp1->springweight+bp2->springweight)/2.0f;
1883         kw = kw * kw;
1884         kw = kw * kw;
1885         switch (bs->springtype) {
1886                 case SB_EDGE:
1887                 case SB_HANDLE:
1888                         forcefactor *=  kw;
1889                         break;
1890                 case SB_BEND:
1891                         forcefactor *=sb->secondspring*kw;
1892                         break;
1893                 case SB_STIFFQUAD:
1894                         forcefactor *=sb->shearstiff*sb->shearstiff* kw;
1895                         break;
1896                 default:
1897                         break;
1898         }
1899
1900
1901         madd_v3_v3fl(bp1->force, dir, (bs->len - distance) * forcefactor);
1902
1903         /* do bp1 <--> bp2 viscous */
1904         sub_v3_v3v3(dvel, bp1->vec, bp2->vec);
1905         kd = sb->infrict * sb_fric_force_scale(ob);
1906         absvel  = normalize_v3(dvel);
1907         projvel = dot_v3v3(dir, dvel);
1908         kd     *= absvel * projvel;
1909         madd_v3_v3fl(bp1->force, dir, -kd);
1910 }
1911
1912
1913 /* since this is definitely the most CPU consuming task here .. try to spread it */
1914 /* core function _softbody_calc_forces_slice_in_a_thread */
1915 /* result is int to be able to flag user break */
1916 static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, float forcetime, float timenow, int ifirst, int ilast, int *UNUSED(ptr_to_break_func(void)), ListBase *effectors, int do_deflector, float fieldfactor, float windfactor)
1917 {
1918         float iks;
1919         int bb, do_selfcollision, do_springcollision, do_aero;
1920         int number_of_points_here = ilast - ifirst;
1921         SoftBody *sb = ob->soft;        /* is supposed to be there */
1922         BodyPoint  *bp;
1923
1924         /* initialize */
1925         if (sb) {
1926                 /* check conditions for various options */
1927                 /* +++ could be done on object level to squeeze out the last bits of it */
1928                 do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
1929                 do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
1930                 do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
1931                 /* --- could be done on object level to squeeze out the last bits of it */
1932         }
1933         else {
1934                 CLOG_ERROR(&LOG, "expected a SB here");
1935                 return (999);
1936         }
1937
1938 /* debugerin */
1939         if (sb->totpoint < ifirst) {
1940                 printf("Aye 998");
1941                 return (998);
1942         }
1943 /* debugerin */
1944
1945
1946         bp = &sb->bpoint[ifirst];
1947         for (bb=number_of_points_here; bb>0; bb--, bp++) {
1948                 /* clear forces  accumulator */
1949                 bp->force[0] = bp->force[1] = bp->force[2] = 0.0;
1950                 /* naive ball self collision */
1951                 /* needs to be done if goal snaps or not */
1952                 if (do_selfcollision) {
1953                         int attached;
1954                         BodyPoint   *obp;
1955                         BodySpring *bs;
1956                         int c, b;
1957                         float velcenter[3], dvel[3], def[3];
1958                         float distance;
1959                         float compare;
1960                         float bstune = sb->ballstiff;
1961
1962                         /* running in a slice we must not assume anything done with obp  neither alter the data of obp */
1963                         for (c=sb->totpoint, obp= sb->bpoint; c>0; c--, obp++) {
1964                                 compare = (obp->colball + bp->colball);
1965                                 sub_v3_v3v3(def, bp->pos, obp->pos);
1966                                 /* rather check the AABBoxes before ever calculating the real distance */
1967                                 /* mathematically it is completely nuts, but performance is pretty much (3) times faster */
1968                                 if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
1969                                 distance = normalize_v3(def);
1970                                 if (distance < compare ) {
1971                                         /* exclude body points attached with a spring */
1972                                         attached = 0;
1973                                         for (b=obp->nofsprings;b>0;b--) {
1974                                                 bs = sb->bspring + obp->springs[b-1];
1975                                                 if (( ilast-bb == bs->v2) || ( ilast-bb == bs->v1)) {
1976                                                         attached=1;
1977                                                         continue;
1978                                                 }
1979                                         }
1980                                         if (!attached) {
1981                                                 float f = bstune / (distance) + bstune / (compare * compare) * distance - 2.0f * bstune / compare;
1982
1983                                                 mid_v3_v3v3(velcenter, bp->vec, obp->vec);
1984                                                 sub_v3_v3v3(dvel, velcenter, bp->vec);
1985                                                 mul_v3_fl(dvel, _final_mass(ob, bp));
1986
1987                                                 madd_v3_v3fl(bp->force, def, f * (1.0f - sb->balldamp));
1988                                                 madd_v3_v3fl(bp->force, dvel, sb->balldamp);
1989                                         }
1990                                 }
1991                         }
1992                 }
1993                 /* naive ball self collision done */
1994
1995                 if (_final_goal(ob, bp) < SOFTGOALSNAP) {  /* omit this bp when it snaps */
1996                         float auxvect[3];
1997                         float velgoal[3];
1998
1999                         /* do goal stuff */
2000                         if (ob->softflag & OB_SB_GOAL) {
2001                                 /* true elastic goal */
2002                                 float ks, kd;
2003                                 sub_v3_v3v3(auxvect, bp->pos, bp->origT);
2004                                 ks  = 1.0f / (1.0f - _final_goal(ob, bp) * sb->goalspring) - 1.0f;
2005                                 bp->force[0]+= -ks*(auxvect[0]);
2006                                 bp->force[1]+= -ks*(auxvect[1]);
2007                                 bp->force[2]+= -ks*(auxvect[2]);
2008
2009                                 /* calculate damping forces generated by goals*/
2010                                 sub_v3_v3v3(velgoal, bp->origS, bp->origE);
2011                                 kd =  sb->goalfrict * sb_fric_force_scale(ob);
2012                                 add_v3_v3v3(auxvect, velgoal, bp->vec);
2013
2014                                 if (forcetime > 0.0f) { /* make sure friction does not become rocket motor on time reversal */
2015                                         bp->force[0]-= kd * (auxvect[0]);
2016                                         bp->force[1]-= kd * (auxvect[1]);
2017                                         bp->force[2]-= kd * (auxvect[2]);
2018                                 }
2019                                 else {
2020                                         bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2021                                         bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2022                                         bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2023                                 }
2024                         }
2025                         /* done goal stuff */
2026
2027                         /* gravitation */
2028                         if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
2029                                 float gravity[3];
2030                                 copy_v3_v3(gravity, scene->physics_settings.gravity);
2031                                 mul_v3_fl(gravity, sb_grav_force_scale(ob)*_final_mass(ob, bp)*sb->effector_weights->global_gravity); /* individual mass of node here */
2032                                 add_v3_v3(bp->force, gravity);
2033                         }
2034
2035                         /* particle field & vortex */
2036                         if (effectors) {
2037                                 EffectedPoint epoint;
2038                                 float kd;
2039                                 float force[3] = {0.0f, 0.0f, 0.0f};
2040                                 float speed[3] = {0.0f, 0.0f, 0.0f};
2041                                 float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2042                                 pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint);
2043                                 BKE_effectors_apply(effectors, NULL, sb->effector_weights, &epoint, force, speed);
2044
2045                                 /* apply forcefield*/
2046                                 mul_v3_fl(force, fieldfactor* eval_sb_fric_force_scale);
2047                                 add_v3_v3(bp->force, force);
2048
2049                                 /* BP friction in moving media */
2050                                 kd= sb->mediafrict* eval_sb_fric_force_scale;
2051                                 bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2052                                 bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2053                                 bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2054                                 /* now we'll have nice centrifugal effect for vortex */
2055
2056                         }
2057                         else {
2058                                 /* BP friction in media (not) moving*/
2059                                 float kd = sb->mediafrict* sb_fric_force_scale(ob);
2060                                 /* assume it to be proportional to actual velocity */
2061                                 bp->force[0]-= bp->vec[0]*kd;
2062                                 bp->force[1]-= bp->vec[1]*kd;
2063                                 bp->force[2]-= bp->vec[2]*kd;
2064                                 /* friction in media done */
2065                         }
2066                         /* +++cached collision targets */
2067                         bp->choke = 0.0f;
2068                         bp->choke2 = 0.0f;
2069                         bp->loc_flag &= ~SBF_DOFUZZY;
2070                         if (do_deflector && !(bp->loc_flag & SBF_OUTOFCOLLISION) ) {
2071                                 float cfforce[3], defforce[3] ={0.0f, 0.0f, 0.0f}, vel[3] = {0.0f, 0.0f, 0.0f}, facenormal[3], cf = 1.0f, intrusion;
2072                                 float kd = 1.0f;
2073
2074                                 if (sb_deflect_face(ob, bp->pos, facenormal, defforce, &cf, timenow, vel, &intrusion)) {
2075                                         if (intrusion < 0.0f) {
2076                                                 sb->scratch->flag |= SBF_DOFUZZY;
2077                                                 bp->loc_flag |= SBF_DOFUZZY;
2078                                                 bp->choke = sb->choke*0.01f;
2079                                         }
2080
2081                                         sub_v3_v3v3(cfforce, bp->vec, vel);
2082                                         madd_v3_v3fl(bp->force, cfforce, -cf * 50.0f);
2083
2084                                         madd_v3_v3fl(bp->force, defforce, kd);
2085                                 }
2086
2087                         }
2088                         /* ---cached collision targets */
2089
2090                         /* +++springs */
2091                         iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2092                         if (ob->softflag & OB_SB_EDGES) {
2093                                 if (sb->bspring) { /* spring list exists at all ? */
2094                                         int b;
2095                                         BodySpring *bs;
2096                                         for (b=bp->nofsprings;b>0;b--) {
2097                                                 bs = sb->bspring + bp->springs[b-1];
2098                                                 if (do_springcollision || do_aero) {
2099                                                         add_v3_v3(bp->force, bs->ext_force);
2100                                                         if (bs->flag & BSF_INTERSECT)
2101                                                                 bp->choke = bs->cf;
2102
2103                                                 }
2104                                                 // sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float forcetime)
2105                                                 sb_spring_force(ob, ilast-bb, bs, iks, forcetime);
2106                                         }/* loop springs */
2107                                 }/* existing spring list */
2108                         }/*any edges*/
2109                         /* ---springs */
2110                 }/*omit on snap */
2111         }/*loop all bp's*/
2112         return 0; /*done fine*/
2113 }
2114
2115 static void *exec_softbody_calc_forces(void *data)
2116 {
2117         SB_thread_context *pctx = (SB_thread_context*)data;
2118         _softbody_calc_forces_slice_in_a_thread(pctx->scene, pctx->ob, pctx->forcetime, pctx->timenow, pctx->ifirst, pctx->ilast, NULL, pctx->effectors, pctx->do_deflector, pctx->fieldfactor, pctx->windfactor);
2119         return NULL;
2120 }
2121
2122 static void sb_cf_threads_run(Scene *scene, Object *ob, float forcetime, float timenow, int totpoint, int *UNUSED(ptr_to_break_func(void)), struct ListBase *effectors, int do_deflector, float fieldfactor, float windfactor)
2123 {
2124         ListBase threads;
2125         SB_thread_context *sb_threads;
2126         int i, totthread, left, dec;
2127         int lowpoints =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
2128
2129         /* figure the number of threads while preventing pretty pointless threading overhead */
2130         totthread= BKE_scene_num_threads(scene);
2131         /* what if we got zillions of CPUs running but less to spread*/
2132         while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
2133                 totthread--;
2134         }
2135
2136         /* printf("sb_cf_threads_run spawning %d threads\n", totthread); */
2137
2138         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
2139         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
2140         left = totpoint;
2141         dec = totpoint/totthread +1;
2142         for (i=0; i<totthread; i++) {
2143                 sb_threads[i].scene = scene;
2144                 sb_threads[i].ob = ob;
2145                 sb_threads[i].forcetime = forcetime;
2146                 sb_threads[i].timenow = timenow;
2147                 sb_threads[i].ilast   = left;
2148                 left = left - dec;
2149                 if (left >0) {
2150                         sb_threads[i].ifirst  = left;
2151                 }
2152                 else
2153                         sb_threads[i].ifirst  = 0;
2154                 sb_threads[i].effectors = effectors;
2155                 sb_threads[i].do_deflector = do_deflector;
2156                 sb_threads[i].fieldfactor = fieldfactor;
2157                 sb_threads[i].windfactor  = windfactor;
2158                 sb_threads[i].nr= i;
2159                 sb_threads[i].tot= totthread;
2160         }
2161
2162
2163         if (totthread > 1) {
2164                 BLI_threadpool_init(&threads, exec_softbody_calc_forces, totthread);
2165
2166                 for (i=0; i<totthread; i++)
2167                         BLI_threadpool_insert(&threads, &sb_threads[i]);
2168
2169                 BLI_threadpool_end(&threads);
2170         }
2171         else
2172                 exec_softbody_calc_forces(&sb_threads[0]);
2173         /* clean up */
2174         MEM_freeN(sb_threads);
2175 }
2176
2177 static void softbody_calc_forces(struct Depsgraph *depsgraph, Scene *scene, Object *ob, float forcetime, float timenow)
2178 {
2179         /* rule we never alter free variables :bp->vec bp->pos in here !
2180          * this will ruin adaptive stepsize AKA heun! (BM)
2181          */
2182         SoftBody *sb= ob->soft; /* is supposed to be there */
2183         /*BodyPoint *bproot;*/ /* UNUSED */
2184         /* float gravity; */ /* UNUSED */
2185         /* float iks; */
2186         float fieldfactor = -1.0f, windfactor  = 0.25;
2187         int   do_deflector /*, do_selfcollision*/, do_springcollision, do_aero;
2188
2189         /* gravity = sb->grav * sb_grav_force_scale(ob); */ /* UNUSED */
2190
2191         /* check conditions for various options */
2192         do_deflector= query_external_colliders(depsgraph, sb->collision_group);
2193         /* do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); */ /* UNUSED */
2194         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2195         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2196
2197         /* iks  = 1.0f/(1.0f-sb->inspring)-1.0f; */ /* inner spring constants function */ /* UNUSED */
2198         /* bproot= sb->bpoint; */ /* need this for proper spring addressing */ /* UNUSED */
2199
2200         if (do_springcollision || do_aero)
2201                 sb_sfesf_threads_run(depsgraph, scene, ob, timenow, sb->totspring, NULL);
2202
2203         /* after spring scan because it uses Effoctors too */
2204         ListBase *effectors = BKE_effectors_create(depsgraph, ob, NULL, sb->effector_weights);
2205
2206         if (do_deflector) {
2207                 float defforce[3];
2208                 do_deflector = sb_detect_aabb_collisionCached(defforce, ob, timenow);
2209         }
2210
2211         sb_cf_threads_run(scene, ob, forcetime, timenow, sb->totpoint, NULL, effectors, do_deflector, fieldfactor, windfactor);
2212
2213         /* finally add forces caused by face collision */
2214         if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob, timenow);
2215
2216         /* finish matrix and solve */
2217         BKE_effectors_free(effectors);
2218 }
2219
2220 static void softbody_apply_forces(Object *ob, float forcetime, int mode, float *err, int mid_flags)
2221 {
2222         /* time evolution */
2223         /* actually does an explicit euler step mode == 0 */
2224         /* or heun ~ 2nd order runge-kutta steps, mode 1, 2 */
2225         SoftBody *sb= ob->soft; /* is supposed to be there */
2226         BodyPoint *bp;
2227         float dx[3] = {0}, dv[3], aabbmin[3], aabbmax[3], cm[3] = {0.0f, 0.0f, 0.0f};
2228         float timeovermass/*, freezeloc=0.00001f, freezeforce=0.00000000001f*/;
2229         float maxerrpos= 0.0f, maxerrvel = 0.0f;
2230         int a, fuzzy=0;
2231
2232         forcetime *= sb_time_scale(ob);
2233
2234         aabbmin[0]=aabbmin[1]=aabbmin[2] = 1e20f;
2235         aabbmax[0]=aabbmax[1]=aabbmax[2] = -1e20f;
2236
2237         /* old one with homogeneous masses  */
2238         /* claim a minimum mass for vertex */
2239 #if 0
2240         if (sb->nodemass > 0.009999f) timeovermass = forcetime / sb->nodemass;
2241         else timeovermass = forcetime / 0.009999f;
2242 #endif
2243
2244         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2245 /* now we have individual masses   */
2246 /* claim a minimum mass for vertex */
2247                 if (_final_mass(ob, bp) > 0.009999f) timeovermass = forcetime/_final_mass(ob, bp);
2248                 else timeovermass = forcetime/0.009999f;
2249
2250
2251                 if (_final_goal(ob, bp) < SOFTGOALSNAP) {
2252                         /* this makes t~ = t */
2253                         if (mid_flags & MID_PRESERVE) copy_v3_v3(dx, bp->vec);
2254
2255                         /* so here is (v)' = a(cceleration) = sum(F_springs)/m + gravitation + some friction forces  + more forces*/
2256                         /* the ( ... )' operator denotes derivate respective time */
2257                         /* the euler step for velocity then becomes */
2258                         /* v(t + dt) = v(t) + a(t) * dt */
2259                         mul_v3_fl(bp->force, timeovermass);/* individual mass of node here */
2260                         /* some nasty if's to have heun in here too */
2261                         copy_v3_v3(dv, bp->force);
2262
2263                         if (mode == 1) {
2264                                 copy_v3_v3(bp->prevvec, bp->vec);
2265                                 copy_v3_v3(bp->prevdv, dv);
2266                         }
2267
2268                         if (mode ==2) {
2269                                 /* be optimistic and execute step */
2270                                 bp->vec[0] = bp->prevvec[0] + 0.5f * (dv[0] + bp->prevdv[0]);
2271                                 bp->vec[1] = bp->prevvec[1] + 0.5f * (dv[1] + bp->prevdv[1]);
2272                                 bp->vec[2] = bp->prevvec[2] + 0.5f * (dv[2] + bp->prevdv[2]);
2273                                 /* compare euler to heun to estimate error for step sizing */
2274                                 maxerrvel = max_ff(maxerrvel, fabsf(dv[0] - bp->prevdv[0]));
2275                                 maxerrvel = max_ff(maxerrvel, fabsf(dv[1] - bp->prevdv[1]));
2276                                 maxerrvel = max_ff(maxerrvel, fabsf(dv[2] - bp->prevdv[2]));
2277                         }
2278                         else { add_v3_v3(bp->vec, bp->force); }
2279
2280                         /* this makes t~ = t+dt */
2281                         if (!(mid_flags & MID_PRESERVE)) copy_v3_v3(dx, bp->vec);
2282
2283                         /* so here is (x)'= v(elocity) */
2284                         /* the euler step for location then becomes */
2285                         /* x(t + dt) = x(t) + v(t~) * dt */
2286                         mul_v3_fl(dx, forcetime);
2287
2288                         /* the freezer coming sooner or later */
2289 #if 0
2290                         if ((dot_v3v3(dx, dx)<freezeloc )&&(dot_v3v3(bp->force, bp->force)<freezeforce )) {
2291                                 bp->frozen /=2;
2292                         }
2293                         else {
2294                                 bp->frozen = min_ff(bp->frozen*1.05f, 1.0f);
2295                         }
2296                         mul_v3_fl(dx, bp->frozen);
2297 #endif
2298                         /* again some nasty if's to have heun in here too */
2299                         if (mode ==1) {
2300                                 copy_v3_v3(bp->prevpos, bp->pos);
2301                                 copy_v3_v3(bp->prevdx, dx);
2302                         }
2303
2304                         if (mode ==2) {
2305                                 bp->pos[0] = bp->prevpos[0] + 0.5f * ( dx[0] + bp->prevdx[0]);
2306                                 bp->pos[1] = bp->prevpos[1] + 0.5f * ( dx[1] + bp->prevdx[1]);
2307                                 bp->pos[2] = bp->prevpos[2] + 0.5f * ( dx[2] + bp->prevdx[2]);
2308                                 maxerrpos = max_ff(maxerrpos, fabsf(dx[0] - bp->prevdx[0]));
2309                                 maxerrpos = max_ff(maxerrpos, fabsf(dx[1] - bp->prevdx[1]));
2310                                 maxerrpos = max_ff(maxerrpos, fabsf(dx[2] - bp->prevdx[2]));
2311
2312                                 /* bp->choke is set when we need to pull a vertex or edge out of the collider.
2313                                  * the collider object signals to get out by pushing hard. on the other hand
2314                                  * we don't want to end up in deep space so we add some <viscosity>
2315                                  * to balance that out */
2316                                 if (bp->choke2 > 0.0f) {
2317                                         mul_v3_fl(bp->vec, (1.0f - bp->choke2));
2318                                 }
2319                                 if (bp->choke > 0.0f) {
2320                                         mul_v3_fl(bp->vec, (1.0f - bp->choke));
2321                                 }
2322
2323                         }
2324                         else {
2325                                 add_v3_v3(bp->pos, dx);
2326                         }
2327                 }/*snap*/
2328                 /* so while we are looping BPs anyway do statistics on the fly */
2329                 minmax_v3v3_v3(aabbmin, aabbmax, bp->pos);
2330                 if (bp->loc_flag & SBF_DOFUZZY) fuzzy =1;
2331         } /*for*/
2332
2333         if (sb->totpoint) mul_v3_fl(cm, 1.0f/sb->totpoint);
2334         if (sb->scratch) {
2335                 copy_v3_v3(sb->scratch->aabbmin, aabbmin);
2336                 copy_v3_v3(sb->scratch->aabbmax, aabbmax);
2337         }
2338
2339         if (err) { /* so step size will be controlled by biggest difference in slope */
2340                 if (sb->solverflags & SBSO_OLDERR)
2341                         *err = max_ff(maxerrpos, maxerrvel);
2342                 else
2343                         *err = maxerrpos;
2344                 //printf("EP %f EV %f\n", maxerrpos, maxerrvel);
2345                 if (fuzzy) {
2346                         *err /= sb->fuzzyness;
2347                 }
2348         }
2349 }
2350
2351 /* used by heun when it overshoots */
2352 static void softbody_restore_prev_step(Object *ob)
2353 {
2354         SoftBody *sb= ob->soft; /* is supposed to be there*/
2355         BodyPoint *bp;
2356         int a;
2357
2358         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2359                 copy_v3_v3(bp->vec, bp->prevvec);
2360                 copy_v3_v3(bp->pos, bp->prevpos);
2361         }
2362 }
2363
2364 #if 0
2365 static void softbody_store_step(Object *ob)
2366 {
2367         SoftBody *sb= ob->soft; /* is supposed to be there*/
2368         BodyPoint *bp;
2369         int a;
2370
2371         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2372                 copy_v3_v3(bp->prevvec, bp->vec);
2373                 copy_v3_v3(bp->prevpos, bp->pos);
2374         }
2375 }
2376
2377
2378 /* used by predictors and correctors */
2379 static void softbody_store_state(Object *ob, float *ppos, float *pvel)
2380 {
2381         SoftBody *sb= ob->soft; /* is supposed to be there*/
2382         BodyPoint *bp;
2383         int a;
2384         float *pp=ppos, *pv=pvel;
2385
2386         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2387
2388                 copy_v3_v3(pv, bp->vec);
2389                 pv+=3;
2390
2391                 copy_v3_v3(pp, bp->pos);
2392                 pp+=3;
2393         }
2394 }
2395
2396 /* used by predictors and correctors */
2397 static void softbody_retrieve_state(Object *ob, float *ppos, float *pvel)
2398 {
2399         SoftBody *sb= ob->soft; /* is supposed to be there*/
2400         BodyPoint *bp;
2401         int a;
2402         float *pp=ppos, *pv=pvel;
2403
2404         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2405
2406                 copy_v3_v3(bp->vec, pv);
2407                 pv+=3;
2408
2409                 copy_v3_v3(bp->pos, pp);
2410                 pp+=3;
2411         }
2412 }
2413
2414 /* used by predictors and correctors */
2415 static void softbody_swap_state(Object *ob, float *ppos, float *pvel)
2416 {
2417         SoftBody *sb= ob->soft; /* is supposed to be there*/
2418         BodyPoint *bp;
2419         int a;
2420         float *pp=ppos, *pv=pvel;
2421         float temp[3];
2422
2423         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2424
2425                 copy_v3_v3(temp, bp->vec);
2426                 copy_v3_v3(bp->vec, pv);
2427                 copy_v3_v3(pv, temp);
2428                 pv+=3;
2429
2430                 copy_v3_v3(temp, bp->pos);
2431                 copy_v3_v3(bp->pos, pp);
2432                 copy_v3_v3(pp, temp);
2433                 pp+=3;
2434         }
2435 }
2436 #endif
2437
2438
2439 /* care for bodypoints taken out of the 'ordinary' solver step
2440  * because they are screwed to goal by bolts
2441  * they just need to move along with the goal in time
2442  * we need to adjust them on sub frame timing in solver
2443  * so now when frame is done .. put 'em to the position at the end of frame
2444  */
2445 static void softbody_apply_goalsnap(Object *ob)
2446 {
2447         SoftBody *sb= ob->soft; /* is supposed to be there */
2448         BodyPoint *bp;
2449         int a;
2450
2451         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2452                 if (_final_goal(ob, bp) >= SOFTGOALSNAP) {
2453                         copy_v3_v3(bp->prevpos, bp->pos);
2454                         copy_v3_v3(bp->pos, bp->origT);
2455                 }
2456         }
2457 }
2458
2459
2460 static void apply_spring_memory(Object *ob)
2461 {
2462         SoftBody *sb = ob->soft;
2463         BodySpring *bs;
2464         BodyPoint *bp1, *bp2;
2465         int a;
2466         float b, l, r;
2467
2468         if (sb && sb->totspring) {
2469                 b = sb->plastic;
2470                 for (a=0; a<sb->totspring; a++) {
2471                         bs  = &sb->bspring[a];
2472                         bp1 =&sb->bpoint[bs->v1];
2473                         bp2 =&sb->bpoint[bs->v2];
2474                         l = len_v3v3(bp1->pos, bp2->pos);
2475                         r = bs->len/l;
2476                         if (( r > 1.05f) || (r < 0.95f)) {
2477                                 bs->len = ((100.0f - b) * bs->len  + b*l)/100.0f;
2478                         }
2479                 }
2480         }
2481 }
2482
2483 /* expects full initialized softbody */
2484 static void interpolate_exciter(Object *ob, int timescale, int time)
2485 {
2486         SoftBody *sb= ob->soft;
2487         BodyPoint *bp;
2488         float f;
2489         int a;
2490
2491         f = (float)time/(float)timescale;
2492
2493         for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2494                 bp->origT[0] = bp->origS[0] + f*(bp->origE[0] - bp->origS[0]);
2495                 bp->origT[1] = bp->origS[1] + f*(bp->origE[1] - bp->origS[1]);
2496                 bp->origT[2] = bp->origS[2] + f*(bp->origE[2] - bp->origS[2]);
2497                 if (_final_goal(ob, bp) >= SOFTGOALSNAP) {
2498                         bp->vec[0] = bp->origE[0] - bp->origS[0];
2499                         bp->vec[1] = bp->origE[1] - bp->origS[1];
2500                         bp->vec[2] = bp->origE[2] - bp->origS[2];
2501                 }
2502         }
2503
2504 }
2505
2506
2507 /* ************ convertors ********** */
2508
2509 /* for each object type we need;
2510  * - xxxx_to_softbody(Object *ob)      : a full (new) copy, creates SB geometry
2511  */
2512
2513 /* Resetting a Mesh SB object's springs */
2514 /* Spring length are caculted from'raw' mesh vertices that are NOT altered by modifier stack. */
2515 static void springs_from_mesh(Object *ob)
2516 {
2517         SoftBody *sb;
2518         Mesh *me= ob->data;
2519         BodyPoint *bp;
2520         int a;
2521         float scale =1.0f;
2522
2523         sb= ob->soft;
2524         if (me && sb) {
2525                 /* using bp->origS as a container for spring calculations here
2526                  * will be overwritten sbObjectStep() to receive
2527                  * actual modifier stack positions
2528                  */
2529                 if (me->totvert) {
2530                         bp= ob->soft->bpoint;
2531                         for (a=0; a<me->totvert; a++, bp++) {
2532                                 copy_v3_v3(bp->origS, me->mvert[a].co);
2533                                 mul_m4_v3(ob->obmat, bp->origS);
2534                         }
2535
2536                 }
2537                 /* recalculate spring length for meshes here */
2538                 /* public version shrink to fit */
2539                 if (sb->springpreload != 0 ) {
2540                         scale = sb->springpreload / 100.0f;
2541                 }
2542                 for (a=0; a<sb->totspring; a++) {
2543                         BodySpring *bs = &sb->bspring[a];
2544                         bs->len= scale*len_v3v3(sb->bpoint[bs->v1].origS, sb->bpoint[bs->v2].origS);
2545                 }
2546         }
2547 }
2548
2549
2550
2551
2552 /* makes totally fresh start situation */
2553 static void mesh_to_softbody(Scene *scene, Object *ob)
2554 {
2555         SoftBody *sb;
2556         Mesh *me= ob->data;
2557         MEdge *medge= me->medge;
2558         BodyPoint *bp;
2559         BodySpring *bs;
2560         int a, totedge;
2561         int defgroup_index, defgroup_index_mass, defgroup_index_spring;
2562
2563         if (ob->softflag & OB_SB_EDGES) totedge= me->totedge;
2564         else totedge= 0;
2565
2566         /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2567         renew_softbody(scene, ob, me->totvert, totedge);
2568
2569         /* we always make body points */
2570         sb = ob->soft;
2571         bp= sb->bpoint;
2572
2573         defgroup_index        = me->dvert ? (sb->vertgroup - 1) : -1;
2574         defgroup_index_mass   = me->dvert ? defgroup_name_index(ob, sb->namedVG_Mass) : -1;
2575         defgroup_index_spring = me->dvert ? defgroup_name_index(ob, sb->namedVG_Spring_K) : -1;
2576
2577         for (a=0; a<me->totvert; a++, bp++) {
2578                 /* get scalar values needed  *per vertex* from vertex group functions,
2579                  * so we can *paint* them nicly ..
2580                  * they are normalized [0.0..1.0] so may be we need amplitude for scale
2581                  * which can be done by caller but still .. i'd like it to go this way
2582                  */
2583
2584                 if (ob->softflag & OB_SB_GOAL) {
2585                         BLI_assert(bp->goal == sb->defgoal);
2586                 }
2587                 if ((ob->softflag & OB_SB_GOAL) && (defgroup_index != -1)) {
2588                         bp->goal *= defvert_find_weight(&me->dvert[a], defgroup_index);
2589                 }
2590
2591                 /* to proof the concept
2592                  * this enables per vertex *mass painting*
2593                  */
2594
2595                 if (defgroup_index_mass != -1) {
2596                         bp->mass *= defvert_find_weight(&me->dvert[a], defgroup_index_mass);
2597                 }
2598
2599                 if (defgroup_index_spring != -1) {
2600                         bp->springweight *= defvert_find_weight(&me->dvert[a], defgroup_index_spring);
2601                 }
2602         }
2603
2604         /* but we only optionally add body edge springs */
2605         if (ob->softflag & OB_SB_EDGES) {
2606                 if (medge) {
2607                         bs= sb->bspring;
2608                         for (a=me->totedge; a>0; a--, medge++, bs++) {
2609                                 bs->v1= medge->v1;
2610                                 bs->v2= medge->v2;
2611                                 bs->springtype=SB_EDGE;
2612                         }
2613
2614
2615                         /* insert *diagonal* springs in quads if desired */
2616                         if (ob->softflag & OB_SB_QUADS) {
2617                                 add_mesh_quad_diag_springs(ob);
2618                         }
2619
2620                         build_bps_springlist(ob); /* scan for springs attached to bodypoints ONCE */
2621                         /* insert *other second order* springs if desired */
2622                         if (sb->secondspring > 0.0000001f) {
2623                                 add_2nd_order_springs(ob, sb->secondspring); /* exploits the first run of build_bps_springlist(ob);*/
2624                                 build_bps_springlist(ob); /* yes we need to do it again*/
2625                         }
2626                         springs_from_mesh(ob); /* write the 'rest'-length of the springs */
2627                         if (ob->softflag & OB_SB_SELF) { calculate_collision_balls(ob); }
2628
2629                 }
2630
2631         }
2632
2633 }
2634
2635 static void mesh_faces_to_scratch(Object *ob)
2636 {
2637         SoftBody *sb= ob->soft;
2638         const Mesh *me = ob->data;
2639         MLoopTri *looptri, *lt;
2640         BodyFace *bodyface;
2641         int a;
2642         /* alloc and copy faces*/
2643
2644         sb->scratch->totface = poly_to_tri_count(me->totpoly, me->totloop);
2645         looptri = lt = MEM_mallocN(sizeof(*looptri) * sb->scratch->totface, __func__);
2646         BKE_mesh_recalc_looptri(
2647                 me->mloop, me->mpoly,
2648                 me->mvert,
2649                 me->totloop, me->totpoly,
2650                 looptri);
2651
2652         bodyface = sb->scratch->bodyface = MEM_mallocN(sizeof(BodyFace) * sb->scratch->totface, "SB_body_Faces");
2653
2654         for (a = 0; a < sb->scratch->totface; a++, lt++, bodyface++) {
2655                 bodyface->v1 = me->mloop[lt->tri[0]].v;
2656                 bodyface->v2 = me->mloop[lt->tri[1]].v;
2657                 bodyface->v3 = me->mloop[lt->tri[2]].v;
2658                 zero_v3(bodyface->ext_force);
2659                 bodyface->ext_force[0] = bodyface->ext_force[1] = bodyface->ext_force[2] = 0.0f;
2660                 bodyface->flag = 0;
2661         }
2662
2663         MEM_freeN(looptri);
2664 }
2665 static void reference_to_scratch(Object *ob)
2666 {
2667         SoftBody *sb= ob->soft;
2668         ReferenceVert *rp;
2669         BodyPoint     *bp;
2670         float accu_pos[3] ={0.f, 0.f, 0.f};
2671         float accu_mass = 0.f;
2672         int a;
2673
2674         sb->scratch->Ref.ivert = MEM_mallocN(sizeof(ReferenceVert)*sb->totpoint, "SB_Reference");
2675         bp= ob->soft->bpoint;
2676         rp= sb->scratch->Ref.ivert;
2677         for (a=0; a<sb->totpoint; a++, rp++, bp++) {
2678                 copy_v3_v3(rp->pos, bp->pos);
2679                 add_v3_v3(accu_pos, bp->pos);
2680                 accu_mass += _final_mass(ob, bp);
2681         }
2682         mul_v3_fl(accu_pos, 1.0f/accu_mass);
2683         copy_v3_v3(sb->scratch->Ref.com, accu_pos);
2684         /* printf("reference_to_scratch\n"); */
2685 }
2686
2687 /*
2688  * helper function to get proper spring length
2689  * when object is rescaled
2690  */
2691 static float globallen(float *v1, float *v2, Object *ob)
2692 {
2693         float p1[3], p2[3];
2694         copy_v3_v3(p1, v1);
2695         mul_m4_v3(ob->obmat, p1);
2696         copy_v3_v3(p2, v2);
2697         mul_m4_v3(ob->obmat, p2);
2698         return len_v3v3(p1, p2);
2699 }
2700
2701 static void makelatticesprings(Lattice *lt,     BodySpring *bs, int dostiff, Object *ob)
2702 {
2703         BPoint *bp=lt->def, *bpu;
2704         int u, v, w, dv, dw, bpc=0, bpuc;
2705
2706         dv= lt->pntsu;
2707         dw= dv*lt->pntsv;
2708
2709         for (w=0; w<lt->pntsw; w++) {
2710
2711                 for (v=0; v<lt->pntsv; v++) {
2712
2713                         for (u=0, bpuc=0, bpu=NULL; u<lt->pntsu; u++, bp++, bpc++) {
2714
2715                                 if (w) {
2716                                         bs->v1 = bpc;
2717                                         bs->v2 = bpc-dw;
2718                                         bs->springtype=SB_EDGE;
2719                                         bs->len= globallen((bp-dw)->vec, bp->vec, ob);
2720                                         bs++;
2721                                 }
2722                                 if (v) {
2723                                         bs->v1 = bpc;
2724                                         bs->v2 = bpc-dv;
2725                                         bs->springtype=SB_EDGE;
2726                                         bs->len= globallen((bp-dv)->vec, bp->vec, ob);
2727                                         bs++;
2728                                 }
2729                                 if (u) {
2730                                         bs->v1 = bpuc;
2731                                         bs->v2 = bpc;
2732                                         bs->springtype=SB_EDGE;
2733                                         bs->len= globallen((bpu)->vec, bp->vec, ob);
2734                                         bs++;
2735                                 }
2736
2737                                 if (dostiff) {
2738
2739                                         if (w) {
2740                                                 if ( v && u ) {
2741                                                         bs->v1 = bpc;
2742                                                         bs->v2 = bpc-dw-dv-1;
2743                                                         bs->springtype=SB_BEND;
2744                                                         bs->len= globallen((bp-dw-dv-1)->vec, bp->vec, ob);
2745                                                         bs++;
2746                                                 }
2747                                                 if ( (v < lt->pntsv-1) && (u != 0) ) {
2748                                                         bs->v1 = bpc;
2749                                                         bs->v2 = bpc-dw+dv-1;
2750                                                         bs->springtype=SB_BEND;
2751                                                         bs->len= globallen((bp-dw+dv-1)->vec, bp->vec, ob);
2752                                                         bs++;
2753                                                 }
2754                                         }
2755
2756                                         if (w < lt->pntsw -1) {
2757                                                 if ( v && u ) {
2758                                                         bs->v1 = bpc;
2759                                                         bs->v2 = bpc+dw-dv-1;
2760                                                         bs->springtype=SB_BEND;
2761                                                         bs->len= globallen((bp+dw-dv-1)->vec, bp->vec, ob);
2762                                                         bs++;
2763                                                 }
2764                                                 if ( (v < lt->pntsv-1) && (u != 0) ) {
2765                                                         bs->v1 = bpc;
2766                                                         bs->v2 = bpc+dw+dv-1;
2767                                                         bs->springtype=SB_BEND;
2768                                                         bs->len= globallen((bp+dw+dv-1)->vec, bp->vec, ob);
2769                                                         bs++;
2770                                                 }
2771                                         }
2772                                 }
2773                                 bpu = bp;
2774                                 bpuc = bpc;
2775                         }
2776                 }
2777         }
2778 }
2779
2780
2781 /* makes totally fresh start situation */
2782 static void lattice_to_softbody(Scene *scene, Object *ob)
2783 {
2784         Lattice *lt= ob->data;
2785         SoftBody *sb;
2786         int totvert, totspring = 0, a;
2787         BodyPoint *bp;
2788         BPoint *bpnt = lt->def;
2789         int defgroup_index, defgroup_index_mass, defgroup_index_spring;
2790
2791         totvert= lt->pntsu*lt->pntsv*lt->pntsw;
2792
2793         if (ob->softflag & OB_SB_EDGES) {
2794                 totspring = ((lt->pntsu - 1) * lt->pntsv +
2795                              (lt->pntsv - 1) * lt->pntsu) * lt->pntsw +
2796                             lt->pntsu*lt->pntsv * (lt->pntsw - 1);
2797                 if (ob->softflag & OB_SB_QUADS) {
2798                         totspring += 4 * (lt->pntsu - 1) *  (lt->pntsv -1)  * (lt->pntsw - 1);
2799                 }
2800         }
2801
2802
2803         /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2804         renew_softbody(scene, ob, totvert, totspring);
2805         sb= ob->soft;   /* can be created in renew_softbody() */
2806         bp = sb->bpoint;
2807
2808         defgroup_index        = lt->dvert ? (sb->vertgroup - 1) : -1;
2809         defgroup_index_mass   = lt->dvert ? defgroup_name_index(ob, sb->namedVG_Mass) : -1;
2810         defgroup_index_spring = lt->dvert ? defgroup_name_index(ob, sb->namedVG_Spring_K) : -1;
2811
2812         /* same code used as for mesh vertices */
2813         for (a = 0; a < totvert; a++, bp++, bpnt++) {
2814
2815                 if (ob->softflag & OB_SB_GOAL) {
2816                         BLI_assert(bp->goal == sb->defgoal);
2817                 }
2818
2819                 if ((ob->softflag & OB_SB_GOAL) && (defgroup_index != -1)) {
2820                         bp->goal *= defvert_find_weight(&lt->dvert[a], defgroup_index);
2821                 }
2822                 else {
2823                         bp->goal *= bpnt->weight;
2824                 }
2825
2826                 if (defgroup_index_mass != -1) {
2827                         bp->mass *= defvert_find_weight(&lt->dvert[a], defgroup_index_mass);
2828                 }
2829
2830                 if (defgroup_index_spring != -1) {
2831                         bp->springweight *= defvert_find_weight(&lt->dvert[a], defgroup_index_spring);
2832                 }
2833         }
2834
2835
2836         /* create some helper edges to enable SB lattice to be useful at all */
2837         if (ob->softflag & OB_SB_EDGES) {
2838                 makelatticesprings(lt, ob->soft->bspring, ob->softflag & OB_SB_QUADS, ob);
2839                 build_bps_springlist(ob); /* link bps to springs */
2840         }
2841 }
2842
2843 /* makes totally fresh start situation */
2844 static void curve_surf_to_softbody(Scene *scene, Object *ob)
2845 {
2846         Curve *cu= ob->data;
2847         SoftBody *sb;
2848         BodyPoint *bp;
2849         BodySpring *bs;
2850         Nurb *nu;
2851         BezTriple *bezt;
2852         BPoint *bpnt;
2853         int a, curindex=0;
2854         int totvert, totspring = 0, setgoal=0;
2855
2856         totvert= BKE_nurbList_verts_count(&cu->nurb);
2857
2858         if (ob->softflag & OB_SB_EDGES) {
2859                 if (ob->type==OB_CURVE) {
2860                         totspring = totvert - BLI_listbase_count(&cu->nurb);
2861                 }
2862         }
2863
2864         /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */
2865         renew_softbody(scene, ob, totvert, totspring);
2866         sb= ob->soft;   /* can be created in renew_softbody() */
2867
2868         /* set vars now */
2869         bp= sb->bpoint;
2870         bs= sb->bspring;
2871
2872         /* weights from bpoints, same code used as for mesh vertices */
2873         /* if ((ob->softflag & OB_SB_GOAL) && sb->vertgroup) 2.4x hack*/
2874         /* new! take the weights from curve vertex anyhow */
2875         if (ob->softflag & OB_SB_GOAL)
2876                 setgoal= 1;
2877
2878         for (nu= cu->nurb.first; nu; nu= nu->next) {
2879                 if (nu->bezt) {
2880                         /* bezier case ; this is nicly said naive; who ever wrote this part, it was not me (JOW) :) */
2881                         /* a: never ever make tangent handles (sub) and or (ob)ject to collision */
2882                         /* b: rather calculate them using some C2 (C2= continuous in second derivate -> no jump in bending ) condition */
2883                         /* not too hard to do, but needs some more code to care for;  some one may want look at it  JOW 2010/06/12*/
2884                         for (bezt=nu->bezt, a=0; a<nu->pntsu; a++, bezt++, bp+=3, curindex+=3) {
2885                                 if (setgoal) {
2886                                         bp->goal *= bezt->weight;
2887
2888                                         /* all three triples */
2889                                         (bp+1)->goal= bp->goal;
2890                                         (bp+2)->goal= bp->goal;
2891                                         /*do not collide handles */
2892                                         (bp+1)->loc_flag |= SBF_OUTOFCOLLISION;
2893                                         (bp+2)->loc_flag |= SBF_OUTOFCOLLISION;
2894                                 }
2895
2896                                 if (totspring) {
2897                                         if (a>0) {
2898                                                 bs->v1= curindex-3;
2899                                                 bs->v2= curindex;
2900                                                 bs->springtype=SB_HANDLE;
2901                                                 bs->len = globallen((bezt-1)->vec[0], bezt->vec[0], ob);
2902                                                 bs++;
2903                                         }