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