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