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