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