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