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