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