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