merge with 2.5 (not trunk, last merge message said that on accident) at r22252
[blender.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_particle_types.h"
62 #include "DNA_key_types.h"
63 #include "DNA_mesh_types.h"
64 #include "DNA_meshdata_types.h"
65 #include "DNA_modifier_types.h"
66 #include "DNA_lattice_types.h"
67 #include "DNA_scene_types.h"
68
69 #include "BLI_blenlib.h"
70 #include "BLI_arithb.h"
71 #include "BLI_ghash.h"
72 #include "BLI_threads.h"
73
74 #include "BKE_curve.h"
75 #include "BKE_effect.h"
76 #include "BKE_global.h"
77 #include "BKE_key.h"
78 #include "BKE_object.h"
79 #include "BKE_particle.h"
80 #include "BKE_softbody.h"
81 #include "BKE_utildefines.h"
82 #include "BKE_DerivedMesh.h"
83 #include "BKE_pointcache.h"
84 #include "BKE_modifier.h"
85 #include "BKE_deform.h"
86 //XXX #include  "BIF_editdeform.h"
87 //XXX #include  "BIF_graphics.h"
88 #include  "PIL_time.h"
89 // #include  "ONL_opennl.h" remove linking to ONL for now
90
91 /* callbacks for errors and interrupts and some goo */
92 static int (*SB_localInterruptCallBack)(void) = NULL;
93
94
95 /* ********** soft body engine ******* */
96
97
98 typedef struct BodySpring {
99         int v1, v2;
100         float len, strength, cf,load;
101         float ext_force[3]; /* edges colliding and sailing */
102         short order;
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
113 /*private scratch pad for caching and other data only needed when alive*/
114 typedef struct SBScratch {
115         GHash *colliderhash;
116         short needstobuildcollider;
117         short flag;
118         BodyFace *bodyface;
119         int totface;
120         float aabbmin[3],aabbmax[3];
121 }SBScratch;
122
123 typedef struct  SB_thread_context {
124                 Scene *scene;
125         Object *ob;
126                 float forcetime;
127                 float timenow;
128                 int ifirst;
129                 int ilast;
130                 ListBase *do_effector;
131                 int do_deflector;
132                 float fieldfactor;
133                 float windfactor;
134                 int nr;
135                 int tot;
136 }SB_thread_context;
137
138 #define NLF_BUILD  1 
139 #define NLF_SOLVE  2 
140
141 #define MID_PRESERVE 1
142
143 #define SOFTGOALSNAP  0.999f 
144 /* if bp-> goal is above make it a *forced follow original* and skip all ODE stuff for this bp
145    removes *unnecessary* stiffnes from ODE system
146 */
147 #define HEUNWARNLIMIT 1 /* 500 would be fine i think for detecting severe *stiff* stuff */
148
149
150 #define BSF_INTERSECT   1 /* edge intersects collider face */
151 #define SBF_DOFUZZY     1 /* edge intersects collider face */
152
153 #define BFF_INTERSECT   1 /* collider edge   intrudes face */
154 #define BFF_CLOSEVERT   2 /* collider vertex repulses face */
155
156
157 float SoftHeunTol = 1.0f; /* humm .. this should be calculated from sb parameters and sizes */
158
159 /* local prototypes */
160 static void free_softbody_intern(SoftBody *sb);
161 /* aye this belongs to arith.c */
162 static void Vec3PlusStVec(float *v, float s, float *v1);
163
164 /*+++ frame based timing +++*/
165
166 /*physical unit of force is [kg * m / sec^2]*/
167
168 static float sb_grav_force_scale(Object *ob)
169 /* since unit of g is [m/sec^2] and F = mass * g we rescale unit mass of node to 1 gramm
170   put it to a function here, so we can add user options later without touching simulation code
171 */
172 {
173         return (0.001f);
174 }
175
176 static float sb_fric_force_scale(Object *ob)
177 /* rescaling unit of drag [1 / sec] to somehow reasonable
178   put it to a function here, so we can add user options later without touching simulation code
179 */
180 {
181         return (0.01f);
182 }
183
184 static float sb_time_scale(Object *ob)
185 /* defining the frames to *real* time relation */
186 {
187         SoftBody *sb= ob->soft; /* is supposed to be there */
188         if (sb){
189                 return(sb->physics_speed); 
190                 /*hrms .. this could be IPO as well :) 
191                  estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)]
192                  1 approx = a unit 1 pendulum at g = 9.8 [earth conditions]  has period 65 frames
193          theory would give a 50 frames period .. so there must be something inaccurate .. looking for that (BM) 
194                  */
195         }
196         return (1.0f);
197         /* 
198         this would be frames/sec independant timing assuming 25 fps is default
199         but does not work very well with NLA
200                 return (25.0f/scene->r.frs_sec)
201         */
202 }
203 /*--- frame based timing ---*/
204
205 /*+++ collider caching and dicing +++*/
206
207 /********************
208 for each target object/face the axis aligned bounding box (AABB) is stored
209 faces paralell to global axes 
210 so only simple "value" in [min,max] ckecks are used
211 float operations still
212 */
213
214 /* just an ID here to reduce the prob for killing objects
215 ** ob->sumohandle points to we should not kill :)
216 */ 
217 const int CCD_SAVETY = 190561; 
218
219 typedef struct ccdf_minmax{
220 float minx,miny,minz,maxx,maxy,maxz;
221 }ccdf_minmax;
222
223
224
225 typedef struct ccd_Mesh {
226         int totvert, totface;
227         MVert *mvert;
228         MVert *mprevvert;
229         MFace *mface;
230         int savety;
231         ccdf_minmax *mima;
232         /* Axis Aligned Bounding Box AABB */
233         float bbmin[3];
234         float bbmax[3];
235 }ccd_Mesh;
236
237
238
239
240 static ccd_Mesh *ccd_mesh_make(Object *ob, DerivedMesh *dm)
241 {
242     ccd_Mesh *pccd_M = NULL;
243         ccdf_minmax *mima =NULL;
244         MFace *mface=NULL;
245         float v[3],hull;
246         int i;
247         
248         /* first some paranoia checks */
249         if (!dm) return NULL;
250         if (!dm->getNumVerts(dm) || !dm->getNumTessFaces(dm)) return NULL;
251         
252         pccd_M = MEM_mallocN(sizeof(ccd_Mesh),"ccd_Mesh");
253         pccd_M->totvert = dm->getNumVerts(dm);
254         pccd_M->totface = dm->getNumTessFaces(dm);
255         pccd_M->savety  = CCD_SAVETY;
256         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
257         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
258         pccd_M->mprevvert=NULL;
259         
260         
261     /* blow it up with forcefield ranges */
262         hull = MAX2(ob->pd->pdef_sbift,ob->pd->pdef_sboft);
263         
264         /* alloc and copy verts*/
265         pccd_M->mvert = dm->dupVertArray(dm);
266     /* ah yeah, put the verices to global coords once */        
267         /* and determine the ortho BB on the fly */ 
268         for(i=0; i < pccd_M->totvert; i++){
269                 Mat4MulVecfl(ob->obmat, pccd_M->mvert[i].co);
270                 
271         /* evaluate limits */
272                 VECCOPY(v,pccd_M->mvert[i].co);
273                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
274                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
275                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
276                 
277                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
278                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
279                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
280                 
281         }
282         /* alloc and copy faces*/
283     pccd_M->mface = dm->dupTessFaceArray(dm);
284         
285         /* OBBs for idea1 */
286     pccd_M->mima = MEM_mallocN(sizeof(ccdf_minmax)*pccd_M->totface,"ccd_Mesh_Faces_mima");
287         mima  = pccd_M->mima;
288         mface = pccd_M->mface;
289
290
291         /* anyhoo we need to walk the list of faces and find OBB they live in */
292         for(i=0; i < pccd_M->totface; i++){
293                 mima->minx=mima->miny=mima->minz=1e30f;
294                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
295                 
296         VECCOPY(v,pccd_M->mvert[mface->v1].co);
297                 mima->minx = MIN2(mima->minx,v[0]-hull);
298                 mima->miny = MIN2(mima->miny,v[1]-hull);
299                 mima->minz = MIN2(mima->minz,v[2]-hull);
300                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
301                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
302                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
303                 
304         VECCOPY(v,pccd_M->mvert[mface->v2].co);
305                 mima->minx = MIN2(mima->minx,v[0]-hull);
306                 mima->miny = MIN2(mima->miny,v[1]-hull);
307                 mima->minz = MIN2(mima->minz,v[2]-hull);
308                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
309                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
310                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
311                 
312                 VECCOPY(v,pccd_M->mvert[mface->v3].co);
313                 mima->minx = MIN2(mima->minx,v[0]-hull);
314                 mima->miny = MIN2(mima->miny,v[1]-hull);
315                 mima->minz = MIN2(mima->minz,v[2]-hull);
316                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
317                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
318                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
319         
320                 if(mface->v4){
321                         VECCOPY(v,pccd_M->mvert[mface->v4].co);
322                 mima->minx = MIN2(mima->minx,v[0]-hull);
323                 mima->miny = MIN2(mima->miny,v[1]-hull);
324                 mima->minz = MIN2(mima->minz,v[2]-hull);
325                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
326                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
327                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
328                 }
329
330                 
331         mima++;
332         mface++;
333                 
334         }
335         return pccd_M;
336 }
337 static void ccd_mesh_update(Object *ob,ccd_Mesh *pccd_M, DerivedMesh *dm)
338 {
339         ccdf_minmax *mima =NULL;
340         MFace *mface=NULL;
341         float v[3],hull;
342         int i;
343         
344         /* first some paranoia checks */
345         if (!dm) return ;
346         if (!dm->getNumVerts(dm) || !dm->getNumTessFaces(dm)) return ;
347
348         if ((pccd_M->totvert != dm->getNumVerts(dm)) ||
349                 (pccd_M->totface != dm->getNumTessFaces(dm))) return;
350
351         pccd_M->bbmin[0]=pccd_M->bbmin[1]=pccd_M->bbmin[2]=1e30f;
352         pccd_M->bbmax[0]=pccd_M->bbmax[1]=pccd_M->bbmax[2]=-1e30f;
353         
354         
355     /* blow it up with forcefield ranges */
356         hull = MAX2(ob->pd->pdef_sbift,ob->pd->pdef_sboft);
357         
358         /* rotate current to previous */
359         if(pccd_M->mprevvert) MEM_freeN(pccd_M->mprevvert);
360     pccd_M->mprevvert = pccd_M->mvert;
361         /* alloc and copy verts*/
362     pccd_M->mvert = dm->dupVertArray(dm);
363     /* ah yeah, put the verices to global coords once */        
364         /* and determine the ortho BB on the fly */ 
365         for(i=0; i < pccd_M->totvert; i++){
366                 Mat4MulVecfl(ob->obmat, pccd_M->mvert[i].co);
367                 
368         /* evaluate limits */
369                 VECCOPY(v,pccd_M->mvert[i].co);
370                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
371                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
372                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
373                 
374                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
375                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
376                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
377
378         /* evaluate limits */
379                 VECCOPY(v,pccd_M->mprevvert[i].co);
380                 pccd_M->bbmin[0] = MIN2(pccd_M->bbmin[0],v[0]-hull);
381                 pccd_M->bbmin[1] = MIN2(pccd_M->bbmin[1],v[1]-hull);
382                 pccd_M->bbmin[2] = MIN2(pccd_M->bbmin[2],v[2]-hull);
383                 
384                 pccd_M->bbmax[0] = MAX2(pccd_M->bbmax[0],v[0]+hull);
385                 pccd_M->bbmax[1] = MAX2(pccd_M->bbmax[1],v[1]+hull);
386                 pccd_M->bbmax[2] = MAX2(pccd_M->bbmax[2],v[2]+hull);
387                 
388         }
389         
390         mima  = pccd_M->mima;
391         mface = pccd_M->mface;
392
393
394         /* anyhoo we need to walk the list of faces and find OBB they live in */
395         for(i=0; i < pccd_M->totface; i++){
396                 mima->minx=mima->miny=mima->minz=1e30f;
397                 mima->maxx=mima->maxy=mima->maxz=-1e30f;
398                 
399         VECCOPY(v,pccd_M->mvert[mface->v1].co);
400                 mima->minx = MIN2(mima->minx,v[0]-hull);
401                 mima->miny = MIN2(mima->miny,v[1]-hull);
402                 mima->minz = MIN2(mima->minz,v[2]-hull);
403                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
404                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
405                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
406                 
407         VECCOPY(v,pccd_M->mvert[mface->v2].co);
408                 mima->minx = MIN2(mima->minx,v[0]-hull);
409                 mima->miny = MIN2(mima->miny,v[1]-hull);
410                 mima->minz = MIN2(mima->minz,v[2]-hull);
411                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
412                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
413                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
414                 
415                 VECCOPY(v,pccd_M->mvert[mface->v3].co);
416                 mima->minx = MIN2(mima->minx,v[0]-hull);
417                 mima->miny = MIN2(mima->miny,v[1]-hull);
418                 mima->minz = MIN2(mima->minz,v[2]-hull);
419                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
420                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
421                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
422         
423                 if(mface->v4){
424                         VECCOPY(v,pccd_M->mvert[mface->v4].co);
425                 mima->minx = MIN2(mima->minx,v[0]-hull);
426                 mima->miny = MIN2(mima->miny,v[1]-hull);
427                 mima->minz = MIN2(mima->minz,v[2]-hull);
428                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
429                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
430                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
431                 }
432
433
434         VECCOPY(v,pccd_M->mprevvert[mface->v1].co);
435                 mima->minx = MIN2(mima->minx,v[0]-hull);
436                 mima->miny = MIN2(mima->miny,v[1]-hull);
437                 mima->minz = MIN2(mima->minz,v[2]-hull);
438                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
439                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
440                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
441                 
442         VECCOPY(v,pccd_M->mprevvert[mface->v2].co);
443                 mima->minx = MIN2(mima->minx,v[0]-hull);
444                 mima->miny = MIN2(mima->miny,v[1]-hull);
445                 mima->minz = MIN2(mima->minz,v[2]-hull);
446                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
447                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
448                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
449                 
450                 VECCOPY(v,pccd_M->mprevvert[mface->v3].co);
451                 mima->minx = MIN2(mima->minx,v[0]-hull);
452                 mima->miny = MIN2(mima->miny,v[1]-hull);
453                 mima->minz = MIN2(mima->minz,v[2]-hull);
454                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
455                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
456                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
457         
458                 if(mface->v4){
459                         VECCOPY(v,pccd_M->mprevvert[mface->v4].co);
460                 mima->minx = MIN2(mima->minx,v[0]-hull);
461                 mima->miny = MIN2(mima->miny,v[1]-hull);
462                 mima->minz = MIN2(mima->minz,v[2]-hull);
463                 mima->maxx = MAX2(mima->maxx,v[0]+hull);
464                 mima->maxy = MAX2(mima->maxy,v[1]+hull);
465                 mima->maxz = MAX2(mima->maxz,v[2]+hull);
466                 }
467
468                 
469         mima++;
470         mface++;
471                 
472         }
473         return ;
474 }
475
476 static void ccd_mesh_free(ccd_Mesh *ccdm)
477 {
478         if(ccdm && (ccdm->savety == CCD_SAVETY )){ /*make sure we're not nuking objects we don't know*/
479                 MEM_freeN(ccdm->mface);
480                 MEM_freeN(ccdm->mvert);
481                 if (ccdm->mprevvert) MEM_freeN(ccdm->mprevvert);
482                 MEM_freeN(ccdm->mima);
483                 MEM_freeN(ccdm);
484                 ccdm = NULL;
485         }
486 }
487
488 static void ccd_build_deflector_hash(Scene *scene, Object *vertexowner, GHash *hash)
489 {
490         Base *base= scene->base.first;
491         Object *ob;
492
493         if (!hash) return;
494         while (base) {
495                 /*Only proceed for mesh object in same layer */
496                 if(base->object->type==OB_MESH && (base->lay & vertexowner->lay)) {
497                         int particles=0;
498                         ob= base->object;
499                         if((vertexowner) && (ob == vertexowner)) {
500                                 if(vertexowner->soft->particles){
501                                         particles=1;
502                                 }
503                                 else {
504                                         /* if vertexowner is given  we don't want to check collision with owner object */ 
505                                         base = base->next;
506                                         continue;                               
507                                 }
508                         }
509
510                         /*+++ only with deflecting set */
511                         if(ob->pd && ob->pd->deflect && BLI_ghash_lookup(hash, ob) == 0) {
512                                 DerivedMesh *dm= NULL;
513
514                                 if(particles) {
515                                         dm = psys_get_modifier(ob,psys_get_current(ob))->dm;
516                                 }
517                                 else {
518                                         if(ob->softflag & OB_SB_COLLFINAL) /* so maybe someone wants overkill to collide with subsurfed */
519                                                 dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
520                                         else
521                                                 dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
522                                 }
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->strength= s_shear;
630                                                 bs->order   =2;
631                                                 bs++;
632                                                 bs->v1= mface->v2;
633                                                 bs->v2= mface->v4;
634                                                 bs->strength= s_shear;
635                                                 bs->order   =2;
636                                                 bs++;
637                                                 
638                                         }
639                                 }       
640                         }
641                         
642             /* now we can announce new springs */
643                         ob->soft->totspring += nofquads *2;
644                 }
645         }
646 }
647
648 static void add_2nd_order_roller(Object *ob,float stiffness,int *counter, int addsprings)
649 {
650         /*assume we have a softbody*/
651         SoftBody *sb= ob->soft; /* is supposed to be there */
652         BodyPoint *bp,*bpo;     
653         BodySpring *bs,*bs2,*bs3= NULL;
654         int a,b,c,notthis= 0,v0;
655         if (!sb->bspring){return;} /* we are 2nd order here so 1rst should have been build :) */
656         /* first run counting  second run adding */
657         *counter = 0;
658         if (addsprings) bs3 = ob->soft->bspring+ob->soft->totspring;
659         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
660                 /*scan for neighborhood*/
661                 bpo = NULL;
662                 v0  = (sb->totpoint-a);
663                 for(b=bp->nofsprings;b>0;b--){
664                         bs = sb->bspring + bp->springs[b-1];
665                         /*nasty thing here that springs have two ends
666                         so here we have to make sure we examine the other */
667                         if (( v0 == bs->v1) ){ 
668                                 bpo =sb->bpoint+bs->v2;
669                                 notthis = bs->v2;
670                         }
671                         else {
672                         if (( v0 == bs->v2) ){
673                                 bpo =sb->bpoint+bs->v1;
674                                 notthis = bs->v1;
675                         } 
676                         else {printf("oops we should not get here -  add_2nd_order_springs");}
677                         }
678             if (bpo){/* so now we have a 2nd order humpdidump */
679                                 for(c=bpo->nofsprings;c>0;c--){
680                                         bs2 = sb->bspring + bpo->springs[c-1];
681                                         if ((bs2->v1 != notthis)  && (bs2->v1 > v0)){
682                                                 (*counter)++;/*hit */
683                                                 if (addsprings){
684                                                         bs3->v1= v0;
685                                                         bs3->v2= bs2->v1;
686                                                         bs3->strength= stiffness;
687                                                         bs3->order=2;
688                                                         bs3++;
689                                                 }
690                                         }
691                                         if ((bs2->v2 !=notthis)&&(bs2->v2 > v0)){
692                                         (*counter)++;/*hit */
693                                                 if (addsprings){
694                                                         bs3->v1= v0;
695                                                         bs3->v2= bs2->v2;
696                                                         bs3->strength= stiffness;
697                                                         bs3->order=2;
698                                                         bs3++;
699                                                 }
700
701                                         }
702                                 }
703                                 
704                         }
705                         
706                 }
707                 /*scan for neighborhood done*/
708         }
709 }
710
711
712 static void add_2nd_order_springs(Object *ob,float stiffness)
713 {
714         int counter = 0;
715         BodySpring *bs_new;
716         stiffness *=stiffness;
717         
718         add_2nd_order_roller(ob,stiffness,&counter,0); /* counting */
719         if (counter) {
720                 /* resize spring-array to hold additional springs */
721                 bs_new= MEM_callocN( (ob->soft->totspring + counter )*sizeof(BodySpring), "bodyspring");
722                 memcpy(bs_new,ob->soft->bspring,(ob->soft->totspring )*sizeof(BodySpring));
723                 
724                 if(ob->soft->bspring)
725                         MEM_freeN(ob->soft->bspring); 
726                 ob->soft->bspring = bs_new; 
727                 
728                 add_2nd_order_roller(ob,stiffness,&counter,1); /* adding */
729                 ob->soft->totspring +=counter ;
730         }
731 }
732
733 static void add_bp_springlist(BodyPoint *bp,int springID)
734 {
735         int *newlist;
736         
737         if (bp->springs == NULL) {
738                 bp->springs = MEM_callocN( sizeof(int), "bpsprings");
739                 bp->springs[0] = springID;
740                 bp->nofsprings = 1;
741         }
742         else {
743                 bp->nofsprings++;
744                 newlist = MEM_callocN(bp->nofsprings * sizeof(int), "bpsprings");
745                 memcpy(newlist,bp->springs,(bp->nofsprings-1)* sizeof(int));
746                 MEM_freeN(bp->springs);
747                 bp->springs = newlist;
748                 bp->springs[bp->nofsprings-1] = springID;
749         }
750 }
751
752 /* do this once when sb is build
753 it is O(N^2) so scanning for springs every iteration is too expensive
754 */
755 static void build_bps_springlist(Object *ob)
756 {
757         SoftBody *sb= ob->soft; /* is supposed to be there */
758         BodyPoint *bp;  
759         BodySpring *bs; 
760         int a,b;
761         
762         if (sb==NULL) return; /* paranoya check */
763         
764         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
765                 /* throw away old list */
766                 if (bp->springs) {
767                         MEM_freeN(bp->springs);
768                         bp->springs=NULL;
769                 }
770                 /* scan for attached inner springs */   
771                 for(b=sb->totspring, bs= sb->bspring; b>0; b--, bs++) {
772                         if (( (sb->totpoint-a) == bs->v1) ){ 
773                                 add_bp_springlist(bp,sb->totspring -b);
774                         }
775                         if (( (sb->totpoint-a) == bs->v2) ){ 
776                                 add_bp_springlist(bp,sb->totspring -b);
777                         }
778                 }/*for springs*/
779         }/*for bp*/             
780 }
781
782 static void calculate_collision_balls(Object *ob)
783 {
784         SoftBody *sb= ob->soft; /* is supposed to be there */
785         BodyPoint *bp;  
786         BodySpring *bs; 
787         int a,b,akku_count;
788         float min,max,akku;
789
790         if (sb==NULL) return; /* paranoya check */
791
792         for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
793                 bp->colball=0;
794                 akku =0.0f;
795                 akku_count=0;
796                 min = 1e22f;
797                 max = -1e22f;
798                 /* first estimation based on attached */
799                 for(b=bp->nofsprings;b>0;b--){
800                         bs = sb->bspring + bp->springs[b-1];
801                         if (bs->order == 1){
802                         akku += bs->len;
803                         akku_count++,
804                         min = MIN2(bs->len,min);
805                         max = MAX2(bs->len,max);
806                         }
807                 }
808
809                 if (akku_count > 0) {
810                         if (sb->sbc_mode == SBC_MODE_MANUAL){
811                                 bp->colball=sb->colball;
812                         }
813                         if (sb->sbc_mode == SBC_MODE_AVG){
814                                 bp->colball = akku/(float)akku_count*sb->colball;
815                         }
816                         if (sb->sbc_mode == SBC_MODE_MIN){
817                                 bp->colball=min*sb->colball;
818                         }
819                         if (sb->sbc_mode == SBC_MODE_MAX){
820                                 bp->colball=max*sb->colball;
821                         }
822                         if (sb->sbc_mode == SBC_MODE_AVGMINMAX){
823                                 bp->colball = (min + max)/2.0f*sb->colball;
824                         }
825                 }
826                 else bp->colball=0;
827         }/*for bp*/             
828 }
829
830
831 /* creates new softbody if didn't exist yet, makes new points and springs arrays */
832 static void renew_softbody(Scene *scene, Object *ob, int totpoint, int totspring)  
833 {
834         SoftBody *sb;
835         int i;
836         short softflag;
837         if(ob->soft==NULL) ob->soft= sbNew(scene);
838         else free_softbody_intern(ob->soft);
839         sb= ob->soft;
840         softflag=ob->softflag;
841            
842         if(totpoint) {
843                 sb->totpoint= totpoint;
844                 sb->totspring= totspring;
845                 
846                 sb->bpoint= MEM_mallocN( totpoint*sizeof(BodyPoint), "bodypoint");
847                 if(totspring) 
848                         sb->bspring= MEM_mallocN( totspring*sizeof(BodySpring), "bodyspring");
849
850                         /* initialise BodyPoint array */
851                 for (i=0; i<totpoint; i++) {
852                         BodyPoint *bp = &sb->bpoint[i];
853
854                         if(softflag & OB_SB_GOAL) {
855                                 bp->goal= sb->defgoal;
856                         }
857                         else { 
858                                 bp->goal= 0.0f; 
859                                 /* so this will definily be below SOFTGOALSNAP */
860                         }
861                         
862                         bp->nofsprings= 0;
863                         bp->springs= NULL;
864                         bp->choke = 0.0f;
865                         bp->choke2 = 0.0f;
866                         bp->frozen = 1.0f;
867                         bp->colball = 0.0f;
868                         bp->flag = 0;
869
870                 }
871         }
872 }
873
874 static void free_softbody_baked(SoftBody *sb)
875 {
876         SBVertex *key;
877         int k;
878
879         for(k=0; k<sb->totkey; k++) {
880                 key= *(sb->keys + k);
881                 if(key) MEM_freeN(key);
882         }
883         if(sb->keys) MEM_freeN(sb->keys);
884         
885         sb->keys= NULL;
886         sb->totkey= 0;
887 }
888 static void free_scratch(SoftBody *sb)
889 {
890         if(sb->scratch){
891                 /* todo make sure everything is cleaned up nicly */
892                 if (sb->scratch->colliderhash){
893                         BLI_ghash_free(sb->scratch->colliderhash, NULL,
894                                         (GHashValFreeFP) ccd_mesh_free); /*this hoepfully will free all caches*/
895                         sb->scratch->colliderhash = NULL;
896                 }
897                 if (sb->scratch->bodyface){
898                         MEM_freeN(sb->scratch->bodyface);
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         Crossf(d_nvect, edge2, edge1);
1078         Normalize(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                                                         VecMulf(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 = Inpf(nv1,d_nvect);
1127                                                 if (ABS(facedist)<outerfacethickness){
1128                                                         if (point_in_tri_prism(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                                                         VecMulf(nv1,time);
1237                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1238                                                         
1239                                                         VecMulf(nv2,time);
1240                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1241                                                         
1242                                                         VecMulf(nv3,time);
1243                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1244                                                         
1245                                                         if (mface->v4){
1246                                                                 VecMulf(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                                         Crossf(d_nvect, edge2, edge1);
1256                                         Normalize(d_nvect);
1257                                         if ( 
1258                                                 LineIntersectsTriangle(nv1, nv2, face_v1, face_v2, face_v3, &t, NULL) ||
1259                                                 LineIntersectsTriangle(nv2, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1260                                                 LineIntersectsTriangle(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                                                 Crossf(d_nvect, edge2, edge1);
1270                                                 Normalize(d_nvect);     
1271                                                 if ( 
1272                                                         /* LineIntersectsTriangle(nv1, nv3, face_v1, face_v2, face_v3, &t, NULL) ||
1273                                                          we did that edge allready */
1274                                                         LineIntersectsTriangle(nv3, nv4, face_v1, face_v2, face_v3, &t, NULL) ||
1275                                                         LineIntersectsTriangle(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 = VecLenf(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                                                         VecMulf(nv1,time);
1465                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1466                                                         
1467                                                         VecMulf(nv2,time);
1468                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1469                                                         
1470                                                         VecMulf(nv3,time);
1471                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1472                                                         
1473                                                         if (mface->v4){
1474                                                                 VecMulf(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                                         Crossf(d_nvect, edge2, edge1);
1485                                         Normalize(d_nvect);
1486                                         if ( LineIntersectsTriangle(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 = Inpf(v1,d_nvect);
1492                                                 i2 = Inpf(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                                                 Crossf(d_nvect, edge2, edge1);
1504                                                 Normalize(d_nvect);                                             
1505                                                 if (LineIntersectsTriangle( 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 = Inpf(v1,d_nvect);
1511                                                 i2 = Inpf(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->order ==1){
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                                                         VecAddf(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                                                 float speed[3]={0.0f,0.0f,0.0f};
1566                                                 float pos[3];
1567                                                 VecMidf(pos, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
1568                                                 VecMidf(vel, sb->bpoint[bs->v1].vec , sb->bpoint[bs->v2].vec);
1569                                                 pdDoEffectors(scene, do_effector, pos, force, speed, (float)scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
1570                                                 VecMulf(speed,windfactor); 
1571                                                 VecAddf(vel,vel,speed);
1572                                         }
1573                                         /* media in rest */
1574                                         else{
1575                                                 VECADD(vel, sb->bpoint[bs->v1].vec , sb->bpoint[bs->v2].vec);
1576                                         }
1577                                         f = Normalize(vel);
1578                                         f = -0.0001f*f*f*sb->aeroedge;
1579                                         /* (todo) add a nice angle dependant function done for now BUT */
1580                                         /* still there could be some nice drag/lift function, but who needs it */ 
1581
1582                                         VECSUB(sp, sb->bpoint[bs->v1].pos , sb->bpoint[bs->v2].pos);
1583                                         Projf(pr,vel,sp);
1584                                         VECSUB(vel,vel,pr);
1585                                         Normalize(vel);
1586                                         if (ob->softflag & OB_SB_AERO_ANGLE){
1587                                                 Normalize(sp);
1588                                                 Vec3PlusStVec(bs->ext_force,f*(1.0f-ABS(Inpf(vel,sp))),vel);
1589                                         }
1590                                         else{ 
1591                                                 Vec3PlusStVec(bs->ext_force,f,vel); // to keep compatible with 2.45 release files
1592                                         }
1593                                 }
1594                                 /* --- springs seeing wind */
1595                         }
1596                 }
1597         }
1598 }
1599
1600
1601 static void scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow)
1602 {
1603   SoftBody *sb = ob->soft;
1604   ListBase *do_effector= NULL; 
1605   
1606   do_effector= pdInitEffectors(scene, ob,NULL);
1607   if (sb){
1608           _scan_for_ext_spring_forces(scene, ob, timenow, 0, sb->totspring, do_effector);
1609   }
1610   if(do_effector)
1611           pdEndEffectors(do_effector);
1612 }
1613
1614 static void *exec_scan_for_ext_spring_forces(void *data)
1615 {
1616         SB_thread_context *pctx = (SB_thread_context*)data;
1617         _scan_for_ext_spring_forces(pctx->scene, pctx->ob, pctx->timenow, pctx->ifirst, pctx->ilast, pctx->do_effector);
1618         return 0;
1619
1620
1621 static void sb_sfesf_threads_run(Scene *scene, struct Object *ob, float timenow,int totsprings,int *ptr_to_break_func())
1622 {
1623         ListBase *do_effector = NULL; 
1624         ListBase threads;
1625         SB_thread_context *sb_threads;
1626         int i, totthread,left,dec;
1627         int lowsprings =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
1628
1629         do_effector= pdInitEffectors(scene, ob,NULL);
1630
1631         /* figure the number of threads while preventing pretty pointless threading overhead */
1632         if(scene->r.mode & R_FIXED_THREADS)
1633                 totthread= scene->r.threads;
1634         else
1635                 totthread= BLI_system_thread_count();
1636         /* what if we got zillions of CPUs running but less to spread*/
1637         while ((totsprings/totthread < lowsprings) && (totthread > 1)) {
1638                 totthread--;
1639         }
1640
1641         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBSpringsThread");
1642         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
1643         left = totsprings;
1644         dec = totsprings/totthread +1;
1645         for(i=0; i<totthread; i++) {
1646                 sb_threads[i].scene = scene;
1647                 sb_threads[i].ob = ob; 
1648                 sb_threads[i].forcetime = 0.0; // not used here 
1649                 sb_threads[i].timenow = timenow; 
1650                 sb_threads[i].ilast   = left; 
1651                 left = left - dec;
1652                 if (left >0){
1653                         sb_threads[i].ifirst  = left;
1654                 }
1655                 else
1656                         sb_threads[i].ifirst  = 0; 
1657         sb_threads[i].do_effector = do_effector;
1658         sb_threads[i].do_deflector = 0;// not used here
1659                 sb_threads[i].fieldfactor = 0.0f;// not used here
1660                 sb_threads[i].windfactor  = 0.0f;// not used here
1661                 sb_threads[i].nr= i;
1662                 sb_threads[i].tot= totthread;
1663         }
1664         if(totthread > 1) {
1665                 BLI_init_threads(&threads, exec_scan_for_ext_spring_forces, totthread);
1666
1667                 for(i=0; i<totthread; i++)
1668                         BLI_insert_thread(&threads, &sb_threads[i]);
1669
1670                 BLI_end_threads(&threads);
1671         }
1672         else
1673                 exec_scan_for_ext_spring_forces(&sb_threads[0]);
1674     /* clean up */
1675         MEM_freeN(sb_threads);
1676
1677           if(do_effector)
1678   pdEndEffectors(do_effector);
1679 }
1680
1681
1682 /* --- the spring external section*/
1683
1684 static int choose_winner(float*w, float* pos,float*a,float*b,float*c,float*ca,float*cb,float*cc)
1685 {
1686         float mindist,cp;
1687         int winner =1;
1688         mindist = ABS(Inpf(pos,a));
1689
1690     cp = ABS(Inpf(pos,b));
1691         if ( mindist < cp ){
1692                 mindist = cp;
1693                 winner =2;
1694         }
1695
1696         cp = ABS(Inpf(pos,c));
1697         if (mindist < cp ){
1698                 mindist = cp;
1699                 winner =3;
1700         }
1701         switch (winner){ 
1702                 case 1: VECCOPY(w,ca); break; 
1703                 case 2: VECCOPY(w,cb); break; 
1704                 case 3: VECCOPY(w,cc); 
1705         }
1706         return(winner);
1707 }
1708
1709
1710
1711 static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], float *damp,
1712                                                                          float force[3], unsigned int par_layer,struct Object *vertexowner,
1713                                                                          float time,float vel[3], float *intrusion)
1714 {
1715         Object *ob= NULL;
1716         GHash *hash;
1717         GHashIterator *ihash;
1718         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},
1719     vv1[3], vv2[3], vv3[3], vv4[3], coledge[3], mindistedge = 1000.0f, 
1720         outerforceaccu[3],innerforceaccu[3],
1721                 facedist,n_mag,force_mag_norm,minx,miny,minz,maxx,maxy,maxz,
1722                 innerfacethickness = -0.5f, outerfacethickness = 0.2f,
1723                 ee = 5.0f, ff = 0.1f, fa=1;
1724         int a, deflected=0, cavel=0,ci=0;
1725 /* init */
1726         *intrusion = 0.0f;
1727         hash  = vertexowner->soft->scratch->colliderhash;
1728         ihash = BLI_ghashIterator_new(hash);
1729         outerforceaccu[0]=outerforceaccu[1]=outerforceaccu[2]=0.0f;
1730         innerforceaccu[0]=innerforceaccu[1]=innerforceaccu[2]=0.0f;
1731 /* go */
1732     while (!BLI_ghashIterator_isDone(ihash) ) {
1733
1734                 ccd_Mesh *ccdm = BLI_ghashIterator_getValue     (ihash);
1735                 ob             = BLI_ghashIterator_getKey       (ihash);
1736                         /* only with deflecting set */
1737                         if(ob->pd && ob->pd->deflect) {
1738                                 MFace *mface= NULL;
1739                                 MVert *mvert= NULL;
1740                                 MVert *mprevvert= NULL;
1741                                 ccdf_minmax *mima= NULL;
1742
1743                                 if(ccdm){
1744                                         mface= ccdm->mface;
1745                                         mvert= ccdm->mvert;
1746                                         mprevvert= ccdm->mprevvert;
1747                                         mima= ccdm->mima;
1748                                         a = ccdm->totface;
1749
1750                                         minx =ccdm->bbmin[0]; 
1751                                         miny =ccdm->bbmin[1]; 
1752                                         minz =ccdm->bbmin[2];
1753
1754                                         maxx =ccdm->bbmax[0]; 
1755                                         maxy =ccdm->bbmax[1]; 
1756                                         maxz =ccdm->bbmax[2]; 
1757
1758                                         if ((opco[0] < minx) || 
1759                                                 (opco[1] < miny) ||
1760                                                 (opco[2] < minz) ||
1761                                                 (opco[0] > maxx) || 
1762                                                 (opco[1] > maxy) || 
1763                                                 (opco[2] > maxz) ) {
1764                                                         /* outside the padded boundbox --> collision object is too far away */ 
1765                                                                                                 BLI_ghashIterator_step(ihash);
1766                                                         continue;                               
1767                                         }                                       
1768                                 }
1769                                 else{
1770                                         /*aye that should be cached*/
1771                                         printf("missing cache error \n");
1772                                                 BLI_ghashIterator_step(ihash);
1773                                         continue;                               
1774                                 }
1775
1776                                 /* do object level stuff */
1777                                 /* need to have user control for that since it depends on model scale */
1778                                 innerfacethickness =-ob->pd->pdef_sbift;
1779                                 outerfacethickness =ob->pd->pdef_sboft;
1780                                 fa = (ff*outerfacethickness-outerfacethickness);
1781                                 fa *= fa;
1782                                 fa = 1.0f/fa;
1783                 avel[0]=avel[1]=avel[2]=0.0f;
1784                                 /* use mesh*/
1785                                 while (a--) {
1786                                         if (
1787                                                 (opco[0] < mima->minx) || 
1788                                                 (opco[0] > mima->maxx) || 
1789                                                 (opco[1] < mima->miny) ||
1790                                                 (opco[1] > mima->maxy) || 
1791                                                 (opco[2] < mima->minz) ||
1792                                                 (opco[2] > mima->maxz) 
1793                                                 ) {
1794                                                         mface++;
1795                                                         mima++;
1796                                                         continue;
1797                                         }
1798
1799                                         if (mvert){
1800
1801                                                 VECCOPY(nv1,mvert[mface->v1].co);                                               
1802                                                 VECCOPY(nv2,mvert[mface->v2].co);
1803                                                 VECCOPY(nv3,mvert[mface->v3].co);
1804                                                 if (mface->v4){
1805                                                         VECCOPY(nv4,mvert[mface->v4].co);
1806                                                 }
1807
1808                                                 if (mprevvert){
1809                                                         /* grab the average speed of the collider vertices
1810                                                         before we spoil nvX 
1811                                                         humm could be done once a SB steps but then we' need to store that too
1812                                                         since the AABB reduced propabitlty to get here drasticallly
1813                                                         it might be a nice tradeof CPU <--> memory
1814                                                         */
1815                                                         VECSUB(vv1,nv1,mprevvert[mface->v1].co);
1816                                                         VECSUB(vv2,nv2,mprevvert[mface->v2].co);
1817                                                         VECSUB(vv3,nv3,mprevvert[mface->v3].co);
1818                                                         if (mface->v4){
1819                                                                 VECSUB(vv4,nv4,mprevvert[mface->v4].co);
1820                                                         }
1821
1822                                                         VecMulf(nv1,time);
1823                                                         Vec3PlusStVec(nv1,(1.0f-time),mprevvert[mface->v1].co);
1824
1825                                                         VecMulf(nv2,time);
1826                                                         Vec3PlusStVec(nv2,(1.0f-time),mprevvert[mface->v2].co);
1827
1828                                                         VecMulf(nv3,time);
1829                                                         Vec3PlusStVec(nv3,(1.0f-time),mprevvert[mface->v3].co);
1830
1831                                                         if (mface->v4){
1832                                                                 VecMulf(nv4,time);
1833                                                                 Vec3PlusStVec(nv4,(1.0f-time),mprevvert[mface->v4].co);
1834                                                         }
1835                                                 }       
1836                                         }
1837                                         
1838                                         /* switch origin to be nv2*/
1839                                         VECSUB(edge1, nv1, nv2);
1840                                         VECSUB(edge2, nv3, nv2);
1841                                         VECSUB(dv1,opco,nv2); /* abuse dv1 to have vertex in question at *origin* of triangle */
1842
1843                                         Crossf(d_nvect, edge2, edge1);
1844                                         n_mag = Normalize(d_nvect);
1845                                         facedist = Inpf(dv1,d_nvect);
1846                                         // so rules are
1847                                         //
1848
1849                                         if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){                
1850                                                 if (point_in_tri_prism(opco, nv1, nv2, nv3) ){
1851                                                         force_mag_norm =(float)exp(-ee*facedist);
1852                                                         if (facedist > outerfacethickness*ff)
1853                                                                 force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
1854                                                         *damp=ob->pd->pdef_sbdamp;
1855                                                         if (facedist > 0.0f){
1856                                                                 *damp *= (1.0f - facedist/outerfacethickness);
1857                                                                 Vec3PlusStVec(outerforceaccu,force_mag_norm,d_nvect);
1858                                                                 deflected = 3;
1859
1860                                                         }
1861                                                         else {
1862                                                                 Vec3PlusStVec(innerforceaccu,force_mag_norm,d_nvect);
1863                                                                 if (deflected < 2) deflected = 2;
1864                                                         }
1865                                                         if ((mprevvert) && (*damp > 0.0f)){
1866                                                                 choose_winner(ve,opco,nv1,nv2,nv3,vv1,vv2,vv3);
1867                                                                 VECADD(avel,avel,ve);
1868                                                                 cavel ++;
1869                                                         }
1870                                                         *intrusion += facedist;
1871                                                         ci++;
1872                                                 }
1873                                         }               
1874                                         if (mface->v4){ /* quad */
1875                                                 /* switch origin to be nv4 */
1876                                                 VECSUB(edge1, nv3, nv4);
1877                                                 VECSUB(edge2, nv1, nv4);
1878                                                 VECSUB(dv1,opco,nv4); /* abuse dv1 to have vertex in question at *origin* of triangle */
1879
1880                                                 Crossf(d_nvect, edge2, edge1);
1881                                                 n_mag = Normalize(d_nvect);
1882                                                 facedist = Inpf(dv1,d_nvect);
1883
1884                                                 if ((facedist > innerfacethickness) && (facedist < outerfacethickness)){
1885                                                         if (point_in_tri_prism(opco, nv1, nv3, nv4) ){
1886                                                                 force_mag_norm =(float)exp(-ee*facedist);
1887                                                                 if (facedist > outerfacethickness*ff)
1888                                                                         force_mag_norm =(float)force_mag_norm*fa*(facedist - outerfacethickness)*(facedist - outerfacethickness);
1889                                                                 *damp=ob->pd->pdef_sbdamp;
1890                                                         if (facedist > 0.0f){
1891                                                                 *damp *= (1.0f - facedist/outerfacethickness);
1892                                                                 Vec3PlusStVec(outerforceaccu,force_mag_norm,d_nvect);
1893                                                                 deflected = 3;
1894
1895                                                         }
1896                                                         else {
1897                                                                 Vec3PlusStVec(innerforceaccu,force_mag_norm,d_nvect);
1898                                                                 if (deflected < 2) deflected = 2;
1899                                                         }
1900
1901                                                                 if ((mprevvert) && (*damp > 0.0f)){
1902                                                                         choose_winner(ve,opco,nv1,nv3,nv4,vv1,vv3,vv4);
1903                                                                         VECADD(avel,avel,ve);
1904                                                                         cavel ++;
1905                                                                 }
1906                                                             *intrusion += facedist;
1907                                                                 ci++;
1908                                                         }
1909
1910                                                 }
1911                                                 if ((deflected < 2)&& (G.rt != 444)) // we did not hit a face until now
1912                                                 { // see if 'outer' hits an edge
1913                                                         float dist;
1914
1915                                                         PclosestVL3Dfl(ve, opco, nv1, nv2);
1916                                             VECSUB(ve,opco,ve); 
1917                                                         dist = Normalize(ve);
1918                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1919                                                                 VECCOPY(coledge,ve);
1920                                                                 mindistedge = dist,
1921                                                                 deflected=1;
1922                                                         }
1923
1924                                                         PclosestVL3Dfl(ve, opco, nv2, nv3);
1925                                             VECSUB(ve,opco,ve); 
1926                                                         dist = Normalize(ve);
1927                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1928                                                                 VECCOPY(coledge,ve);
1929                                                                 mindistedge = dist,
1930                                                                 deflected=1;
1931                                                         }
1932
1933                                                         PclosestVL3Dfl(ve, opco, nv3, nv1);
1934                                             VECSUB(ve,opco,ve); 
1935                                                         dist = Normalize(ve);
1936                                                         if ((dist < outerfacethickness)&&(dist < mindistedge )){
1937                                                                 VECCOPY(coledge,ve);
1938                                                                 mindistedge = dist,
1939                                                                 deflected=1;
1940                                                         }
1941                                                         if (mface->v4){ /* quad */
1942                                                                 PclosestVL3Dfl(ve, opco, nv3, nv4);
1943                                                                 VECSUB(ve,opco,ve); 
1944                                                                 dist = Normalize(ve);
1945                                                                 if ((dist < outerfacethickness)&&(dist < mindistedge )){
1946                                                                         VECCOPY(coledge,ve);
1947                                                                         mindistedge = dist,
1948                                                                                 deflected=1;
1949                                                                 }
1950
1951                                                                 PclosestVL3Dfl(ve, opco, nv1, nv4);
1952                                                                 VECSUB(ve,opco,ve); 
1953                                                                 dist = Normalize(ve);
1954                                                                 if ((dist < outerfacethickness)&&(dist < mindistedge )){
1955                                                                         VECCOPY(coledge,ve);
1956                                                                         mindistedge = dist,
1957                                                                                 deflected=1;
1958                                                                 }
1959                                                         
1960                                                         }
1961
1962
1963                                                 }
1964                                         }
1965                                         mface++;
1966                                         mima++;                                 
1967                                 }/* while a */          
1968                         } /* if(ob->pd && ob->pd->deflect) */
1969                         BLI_ghashIterator_step(ihash);
1970         } /* while () */
1971
1972         if (deflected == 1){ // no face but 'outer' edge cylinder sees vert
1973                 force_mag_norm =(float)exp(-ee*mindistedge);
1974                 if (mindistedge > outerfacethickness*ff)
1975                         force_mag_norm =(float)force_mag_norm*fa*(mindistedge - outerfacethickness)*(mindistedge - outerfacethickness);
1976                 Vec3PlusStVec(force,force_mag_norm,coledge);
1977                 *damp=ob->pd->pdef_sbdamp;
1978                 if (mindistedge > 0.0f){
1979                         *damp *= (1.0f - mindistedge/outerfacethickness);
1980                 }
1981
1982         }
1983         if (deflected == 2){ //  face inner detected
1984                 VECADD(force,force,innerforceaccu);
1985         }
1986         if (deflected == 3){ //  face outer detected
1987                 VECADD(force,force,outerforceaccu);
1988         }
1989
1990         BLI_ghashIterator_free(ihash);
1991         if (cavel) VecMulf(avel,1.0f/(float)cavel);
1992         VECCOPY(vel,avel);
1993         if (ci) *intrusion /= ci;
1994         if (deflected){ 
1995                 VECCOPY(facenormal,force);
1996                 Normalize(facenormal);
1997         }
1998         return deflected;       
1999 }
2000
2001
2002 /* sandbox to plug in various deflection algos */
2003 static int sb_deflect_face(Object *ob,float *actpos,float *facenormal,float *force,float *cf,float time,float *vel,float *intrusion)
2004 {
2005         float s_actpos[3];
2006         int deflected;  
2007         VECCOPY(s_actpos,actpos);
2008         deflected= sb_detect_vertex_collisionCached(s_actpos, facenormal, cf, force , ob->lay, ob,time,vel,intrusion);
2009         //deflected= sb_detect_vertex_collisionCachedEx(s_actpos, facenormal, cf, force , ob->lay, ob,time,vel,intrusion);
2010         return(deflected);
2011 }
2012
2013 /* hiding this for now .. but the jacobian may pop up on other tasks .. so i'd like to keep it
2014 static void dfdx_spring(int ia, int ic, int op, float dir[3],float L,float len,float factor)
2015
2016         float m,delta_ij;
2017         int i ,j;
2018         if (L < len){
2019                 for(i=0;i<3;i++)
2020                         for(j=0;j<3;j++){
2021                                 delta_ij = (i==j ? (1.0f): (0.0f));
2022                                 m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j]));
2023                                 nlMatrixAdd(ia+i,op+ic+j,m);
2024                         }
2025         }
2026         else{
2027                 for(i=0;i<3;i++)
2028                         for(j=0;j<3;j++){
2029                                 m=factor*dir[i]*dir[j];
2030                                 nlMatrixAdd(ia+i,op+ic+j,m);
2031                         }
2032         }
2033 }
2034
2035
2036 static void dfdx_goal(int ia, int ic, int op, float factor)
2037
2038         int i;
2039         for(i=0;i<3;i++) nlMatrixAdd(ia+i,op+ic+i,factor);
2040 }
2041
2042 static void dfdv_goal(int ia, int ic,float factor)
2043
2044         int i;
2045         for(i=0;i<3;i++) nlMatrixAdd(ia+i,ic+i,factor);
2046 }
2047 */
2048 static void sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
2049 {
2050         SoftBody *sb= ob->soft; /* is supposed to be there */
2051         BodyPoint  *bp1,*bp2;
2052
2053         float dir[3],dvel[3];
2054         float distance,forcefactor,kd,absvel,projvel,kw;
2055         int ia,ic;
2056         /* prepare depending on which side of the spring we are on */
2057         if (bpi == bs->v1){
2058                 bp1 = &sb->bpoint[bs->v1];
2059                 bp2 = &sb->bpoint[bs->v2];
2060                 ia =3*bs->v1;
2061                 ic =3*bs->v2;
2062         }
2063         else if (bpi == bs->v2){
2064                 bp1 = &sb->bpoint[bs->v2];
2065                 bp2 = &sb->bpoint[bs->v1];
2066                 ia =3*bs->v2;
2067                 ic =3*bs->v1;
2068         }
2069         else{
2070                 /* TODO make this debug option */
2071                 /**/
2072                 printf("bodypoint <bpi> is not attached to spring  <*bs> --> sb_spring_force()\n");
2073                 return;
2074         }
2075
2076         /* do bp1 <--> bp2 elastic */
2077         VecSubf(dir,bp1->pos,bp2->pos);
2078         distance = Normalize(dir);
2079         if (bs->len < distance)
2080                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2081         else
2082                 iks  = 1.0f/(1.0f-sb->inpush)-1.0f ;/* inner spring constants function */
2083
2084         if(bs->len > 0.0f) /* check for degenerated springs */
2085                 forcefactor = iks/bs->len;
2086         else
2087                 forcefactor = iks;
2088             kw = (bp1->springweight+bp2->springweight)/2.0f;
2089                 kw = kw * kw;
2090                 kw = kw * kw;
2091         forcefactor *= bs->strength * kw; 
2092         Vec3PlusStVec(bp1->force,(bs->len - distance)*forcefactor,dir);
2093
2094         /* do bp1 <--> bp2 viscous */
2095         VecSubf(dvel,bp1->vec,bp2->vec);
2096         kd = sb->infrict * sb_fric_force_scale(ob);
2097         absvel  = Normalize(dvel);
2098         projvel = Inpf(dir,dvel);
2099         kd     *= absvel * projvel;
2100         Vec3PlusStVec(bp1->force,-kd,dir);
2101
2102         /* do jacobian stuff if needed */
2103         if(nl_flags & NLF_BUILD){
2104                 //int op =3*sb->totpoint;
2105                 //float mvel = -forcetime*kd;
2106                 //float mpos = -forcetime*forcefactor;
2107                 /* depending on my pos */ 
2108                 // dfdx_spring(ia,ia,op,dir,bs->len,distance,-mpos);
2109                 /* depending on my vel */
2110                 // dfdv_goal(ia,ia,mvel); // well that ignores geometie
2111                 if(bp2->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2112                         /* depending on other pos */ 
2113                         // dfdx_spring(ia,ic,op,dir,bs->len,distance,mpos);
2114                         /* depending on other vel */
2115                         // dfdv_goal(ia,ia,-mvel); // well that ignores geometie
2116                 }
2117         }
2118 }
2119
2120
2121 /* since this is definitely the most CPU consuming task here .. try to spread it */
2122 /* core function _softbody_calc_forces_slice_in_a_thread */
2123 /* result is int to be able to flag user break */
2124 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)
2125 {
2126         float iks;
2127         int bb,do_selfcollision,do_springcollision,do_aero;
2128         int number_of_points_here = ilast - ifirst;
2129         SoftBody *sb= ob->soft; /* is supposed to be there */
2130         BodyPoint  *bp;
2131         
2132         /* intitialize */
2133         if (sb) {
2134         /* check conditions for various options */
2135     /* +++ could be done on object level to squeeze out the last bits of it */
2136         do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2137         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2138         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2139     /* --- could be done on object level to squeeze out the last bits of it */
2140         }
2141         else {
2142                 printf("Error expected a SB here \n");
2143                 return (999);
2144         }
2145
2146 /* debugerin */
2147         if  (sb->totpoint < ifirst) {
2148                 printf("Aye 998");
2149                 return (998);
2150         }
2151 /* debugerin */
2152
2153
2154         bp = &sb->bpoint[ifirst]; 
2155         for(bb=number_of_points_here; bb>0; bb--, bp++) {
2156                 /* clear forces  accumulator */
2157                 bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
2158                 /* naive ball self collision */
2159                 /* needs to be done if goal snaps or not */
2160                 if(do_selfcollision){
2161                                 int attached;
2162                                 BodyPoint   *obp;
2163                                 BodySpring *bs; 
2164                                 int c,b;
2165                                 float velcenter[3],dvel[3],def[3];
2166                                 float distance;
2167                                 float compare;
2168                 float bstune = sb->ballstiff;
2169
2170                                 for(c=sb->totpoint, obp= sb->bpoint; c>=ifirst+bb; c--, obp++) {
2171                                         compare = (obp->colball + bp->colball);         
2172                                         VecSubf(def, bp->pos, obp->pos);
2173                                         /* rather check the AABBoxes before ever calulating the real distance */
2174                                         /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
2175                                         if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
2176                     distance = Normalize(def);
2177                                         if (distance < compare ){
2178                                                 /* exclude body points attached with a spring */
2179                                                 attached = 0;
2180                                                 for(b=obp->nofsprings;b>0;b--){
2181                                                         bs = sb->bspring + obp->springs[b-1];
2182                                                         if (( ilast-bb == bs->v2)  || ( ilast-bb == bs->v1)){
2183                                                                 attached=1;
2184                                                                 continue;}
2185                                                 }
2186                                                 if (!attached){
2187                                                         float f = bstune/(distance) + bstune/(compare*compare)*distance - 2.0f*bstune/compare ;
2188
2189                                                         VecMidf(velcenter, bp->vec, obp->vec);
2190                                                         VecSubf(dvel,velcenter,bp->vec);
2191                                                         VecMulf(dvel,bp->mass);
2192
2193                                                         Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
2194                                                         Vec3PlusStVec(bp->force,sb->balldamp,dvel);
2195
2196                                                         /* exploit force(a,b) == -force(b,a) part2/2 */
2197                                                         VecSubf(dvel,velcenter,obp->vec);
2198                                                         VecMulf(dvel,bp->mass);
2199
2200                                                         Vec3PlusStVec(obp->force,sb->balldamp,dvel);
2201                                                         Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
2202                                                 }
2203                                         }
2204                                 }
2205                 }
2206                 /* naive ball self collision done */
2207
2208                 if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2209                         float auxvect[3];  
2210                         float velgoal[3];
2211
2212                         /* do goal stuff */
2213                         if(ob->softflag & OB_SB_GOAL) {
2214                                 /* true elastic goal */
2215                                 float ks,kd;
2216                                 VecSubf(auxvect,bp->pos,bp->origT);
2217                                 ks  = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
2218                                 bp->force[0]+= -ks*(auxvect[0]);
2219                                 bp->force[1]+= -ks*(auxvect[1]);
2220                                 bp->force[2]+= -ks*(auxvect[2]);
2221
2222                                 /* calulate damping forces generated by goals*/
2223                                 VecSubf(velgoal,bp->origS, bp->origE);
2224                                 kd =  sb->goalfrict * sb_fric_force_scale(ob) ;
2225                                 VecAddf(auxvect,velgoal,bp->vec);
2226                                 
2227                                 if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
2228                                         bp->force[0]-= kd * (auxvect[0]);
2229                                         bp->force[1]-= kd * (auxvect[1]);
2230                                         bp->force[2]-= kd * (auxvect[2]);
2231                                 }
2232                                 else {
2233                                         bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2234                                         bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2235                                         bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2236                                 }
2237                         }
2238                         /* done goal stuff */
2239                         
2240                         /* gravitation */
2241                         if (sb){ 
2242                         float gravity = sb->grav * sb_grav_force_scale(ob);     
2243                         bp->force[2]-= gravity*bp->mass; /* individual mass of node here */
2244                         }
2245                         
2246                         /* particle field & vortex */
2247                         if(do_effector) {
2248                                 float kd;
2249                                 float force[3]= {0.0f, 0.0f, 0.0f};
2250                                 float speed[3]= {0.0f, 0.0f, 0.0f};
2251                                 float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2252                                 
2253                                 pdDoEffectors(scene, do_effector, bp->pos, force, speed, (float)scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
2254                                 
2255                                 /* apply forcefield*/
2256                                 VecMulf(force,fieldfactor* eval_sb_fric_force_scale); 
2257                                 VECADD(bp->force, bp->force, force);
2258                                 
2259                                 /* BP friction in moving media */       
2260                                 kd= sb->mediafrict* eval_sb_fric_force_scale;  
2261                                 bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2262                                 bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2263                                 bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2264                                 /* now we'll have nice centrifugal effect for vortex */
2265                                 
2266                         }
2267                         else {
2268                                 /* BP friction in media (not) moving*/
2269                                 float kd = sb->mediafrict* sb_fric_force_scale(ob);  
2270                                 /* assume it to be proportional to actual velocity */
2271                                 bp->force[0]-= bp->vec[0]*kd;
2272                                 bp->force[1]-= bp->vec[1]*kd;
2273                                 bp->force[2]-= bp->vec[2]*kd;
2274                                 /* friction in media done */
2275                         }
2276                         /* +++cached collision targets */
2277                         bp->choke = 0.0f;
2278                         bp->choke2 = 0.0f;
2279                         bp->flag &= ~SBF_DOFUZZY;
2280                         if(do_deflector) {
2281                                 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;
2282                                 float kd = 1.0f;
2283
2284                                 if (sb_deflect_face(ob,bp->pos,facenormal,defforce,&cf,timenow,vel,&intrusion)){
2285                                                 if (intrusion < 0.0f){
2286                                                         sb->scratch->flag |= SBF_DOFUZZY;
2287                                                         bp->flag |= SBF_DOFUZZY;
2288                                                         bp->choke = sb->choke*0.01f;
2289                                                 }
2290
2291                                                         VECSUB(cfforce,bp->vec,vel);
2292                                                         Vec3PlusStVec(bp->force,-cf*50.0f,cfforce);
2293                                         
2294                                         Vec3PlusStVec(bp->force,kd,defforce);  
2295                                 }
2296
2297                         }
2298                         /* ---cached collision targets */
2299
2300                         /* +++springs */
2301                         iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2302                         if(ob->softflag & OB_SB_EDGES) {
2303                                 if (sb->bspring){ /* spring list exists at all ? */
2304                                         int b;
2305                                         BodySpring *bs; 
2306                                         for(b=bp->nofsprings;b>0;b--){
2307                                                 bs = sb->bspring + bp->springs[b-1];
2308                                                 if (do_springcollision || do_aero){
2309                                                         VecAddf(bp->force,bp->force,bs->ext_force);
2310                                                         if (bs->flag & BSF_INTERSECT)
2311                                                                 bp->choke = bs->cf; 
2312
2313                                                 }
2314                         // sb_spring_force(Object *ob,int bpi,BodySpring *bs,float iks,float forcetime,int nl_flags)
2315                                                 sb_spring_force(ob,ilast-bb,bs,iks,forcetime,0);
2316                                         }/* loop springs */
2317                                 }/* existing spring list */ 
2318                         }/*any edges*/
2319                         /* ---springs */
2320                 }/*omit on snap */
2321         }/*loop all bp's*/
2322 return 0; /*done fine*/
2323 }
2324
2325 static void *exec_softbody_calc_forces(void *data)
2326 {
2327         SB_thread_context *pctx = (SB_thread_context*)data;
2328     _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);
2329         return 0;
2330
2331
2332 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)
2333 {
2334         ListBase threads;
2335         SB_thread_context *sb_threads;
2336         int i, totthread,left,dec;
2337         int lowpoints =100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */
2338
2339         /* figure the number of threads while preventing pretty pointless threading overhead */
2340         if(scene->r.mode & R_FIXED_THREADS)
2341                 totthread= scene->r.threads;
2342         else
2343                 totthread= BLI_system_thread_count();
2344         /* what if we got zillions of CPUs running but less to spread*/
2345         while ((totpoint/totthread < lowpoints) && (totthread > 1)) {
2346                 totthread--;
2347         }
2348
2349     /* printf("sb_cf_threads_run spawning %d threads \n",totthread); */
2350
2351         sb_threads= MEM_callocN(sizeof(SB_thread_context)*totthread, "SBThread");
2352         memset(sb_threads, 0, sizeof(SB_thread_context)*totthread);
2353         left = totpoint;
2354         dec = totpoint/totthread +1;
2355         for(i=0; i<totthread; i++) {
2356                 sb_threads[i].ob = ob; 
2357                 sb_threads[i].forcetime = forcetime; 
2358                 sb_threads[i].timenow = timenow; 
2359                 sb_threads[i].ilast   = left; 
2360                 left = left - dec;
2361                 if (left >0){
2362                         sb_threads[i].ifirst  = left;
2363                 }
2364                 else
2365                         sb_threads[i].ifirst  = 0; 
2366         sb_threads[i].do_effector = do_effector;
2367         sb_threads[i].do_deflector = do_deflector;
2368                 sb_threads[i].fieldfactor = fieldfactor;
2369                 sb_threads[i].windfactor  = windfactor;
2370                 sb_threads[i].nr= i;
2371                 sb_threads[i].tot= totthread;
2372         }
2373
2374
2375         if(totthread > 1) {
2376                 BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
2377
2378                 for(i=0; i<totthread; i++)
2379                         BLI_insert_thread(&threads, &sb_threads[i]);
2380
2381                 BLI_end_threads(&threads);
2382         }
2383         else
2384                 exec_softbody_calc_forces(&sb_threads[0]);
2385     /* clean up */
2386         MEM_freeN(sb_threads);
2387 }
2388
2389 static void softbody_calc_forcesEx(Scene *scene, Object *ob, float forcetime, float timenow, int nl_flags)
2390 {
2391 /* rule we never alter free variables :bp->vec bp->pos in here ! 
2392  * this will ruin adaptive stepsize AKA heun! (BM) 
2393  */
2394         SoftBody *sb= ob->soft; /* is supposed to be there */
2395         BodyPoint *bproot;
2396         ListBase *do_effector;
2397         float iks, gravity;
2398         float fieldfactor = -1.0f, windfactor  = 0.25;   
2399         int   do_deflector,do_selfcollision,do_springcollision,do_aero;
2400         
2401         gravity = sb->grav * sb_grav_force_scale(ob);   
2402         
2403         /* check conditions for various options */
2404         do_deflector= query_external_colliders(scene, ob);
2405         do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2406         do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2407         do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2408         
2409         iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2410         bproot= sb->bpoint; /* need this for proper spring addressing */
2411         
2412         if (do_springcollision || do_aero)  
2413         sb_sfesf_threads_run(scene, ob, timenow,sb->totspring,NULL);    
2414         
2415         /* after spring scan because it uses Effoctors too */
2416         do_effector= pdInitEffectors(scene, ob,NULL);
2417
2418         if (do_deflector) {
2419                 float defforce[3];
2420                 do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
2421         }
2422
2423         sb_cf_threads_run(scene, ob, forcetime, timenow, sb->totpoint, NULL, do_effector, do_deflector, fieldfactor, windfactor);
2424
2425         /* finally add forces caused by face collision */
2426         if (ob->softflag & OB_SB_FACECOLL) scan_for_ext_face_forces(ob,timenow);
2427         
2428         /* finish matrix and solve */
2429         if(do_effector) pdEndEffectors(do_effector);
2430 }
2431
2432
2433
2434
2435 static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, float timenow, int nl_flags)
2436 {
2437         /* redirection to the new threaded Version */
2438         if (!(G.rt & 0x10)){ // 16
2439                 softbody_calc_forcesEx(scene, ob, forcetime, timenow, nl_flags);
2440                 return;
2441         }
2442         else{
2443                 /* so the following will die  */
2444                 /* |||||||||||||||||||||||||| */
2445                 /* VVVVVVVVVVVVVVVVVVVVVVVVVV */
2446                 /*backward compatibility note:
2447                 fixing bug [17428] which forces adaptive step size to tiny steps 
2448                 in some situations 
2449                 .. keeping G.rt==17 0x11 option for old files 'needing' the bug*/
2450
2451                 /* rule we never alter free variables :bp->vec bp->pos in here ! 
2452                 * this will ruin adaptive stepsize AKA heun! (BM) 
2453                 */
2454                 SoftBody *sb= ob->soft; /* is supposed to be there */
2455                 BodyPoint  *bp;
2456                 BodyPoint *bproot;
2457                 BodySpring *bs; 
2458                 ListBase *do_effector;
2459                 float iks, ks, kd, gravity;
2460                 float fieldfactor = -1.0f, windfactor  = 0.25f;   
2461                 float tune = sb->ballstiff;
2462                 int a, b,  do_deflector,do_selfcollision,do_springcollision,do_aero;
2463
2464
2465                 /* jacobian
2466                 NLboolean success;
2467
2468                 if(nl_flags){
2469                 nlBegin(NL_SYSTEM);
2470                 nlBegin(NL_MATRIX);
2471                 }
2472                 */
2473
2474
2475                 gravity = sb->grav * sb_grav_force_scale(ob);   
2476
2477                 /* check conditions for various options */
2478                 do_deflector= query_external_colliders(scene, ob);
2479                 do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF));
2480                 do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL);
2481                 do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES));
2482
2483                 iks  = 1.0f/(1.0f-sb->inspring)-1.0f ;/* inner spring constants function */
2484                 bproot= sb->bpoint; /* need this for proper spring addressing */
2485
2486                 if (do_springcollision || do_aero)  scan_for_ext_spring_forces(scene, ob, timenow);
2487                 /* after spring scan because it uses Effoctors too */
2488                 do_effector= pdInitEffectors(scene, ob,NULL);
2489
2490                 if (do_deflector) {
2491                         float defforce[3];
2492                         do_deflector = sb_detect_aabb_collisionCached(defforce,ob->lay,ob,timenow);
2493                 }
2494
2495                 for(a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) {
2496                         /* clear forces  accumulator */
2497                         bp->force[0]= bp->force[1]= bp->force[2]= 0.0;
2498                         if(nl_flags & NLF_BUILD){
2499                                 //int ia =3*(sb->totpoint-a);
2500                                 //int op =3*sb->totpoint;
2501                                 /* dF/dV = v */ 
2502                                 /* jacobioan
2503                                 nlMatrixAdd(op+ia,ia,-forcetime);
2504                                 nlMatrixAdd(op+ia+1,ia+1,-forcetime);
2505                                 nlMatrixAdd(op+ia+2,ia+2,-forcetime);
2506
2507                                 nlMatrixAdd(ia,ia,1);
2508                                 nlMatrixAdd(ia+1,ia+1,1);
2509                                 nlMatrixAdd(ia+2,ia+2,1);
2510
2511                                 nlMatrixAdd(op+ia,op+ia,1);
2512                                 nlMatrixAdd(op+ia+1,op+ia+1,1);
2513                                 nlMatrixAdd(op+ia+2,op+ia+2,1);
2514                                 */
2515
2516
2517                         }
2518
2519                         /* naive ball self collision */
2520                         /* needs to be done if goal snaps or not */
2521                         if(do_selfcollision){
2522                                 int attached;
2523                                 BodyPoint   *obp;
2524                                 int c,b;
2525                                 float velcenter[3],dvel[3],def[3];
2526                                 float distance;
2527                                 float compare;
2528
2529                                 for(c=sb->totpoint, obp= sb->bpoint; c>=a; c--, obp++) {
2530
2531                                         //if ((bp->octantflag & obp->octantflag) == 0) continue;
2532
2533                                         compare = (obp->colball + bp->colball);         
2534                                         VecSubf(def, bp->pos, obp->pos);
2535
2536                                         /* rather check the AABBoxes before ever calulating the real distance */
2537                                         /* mathematically it is completly nuts, but performace is pretty much (3) times faster */
2538                                         if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) continue;
2539
2540                                         distance = Normalize(def);
2541                                         if (distance < compare ){
2542                                                 /* exclude body points attached with a spring */
2543                                                 attached = 0;
2544                                                 for(b=obp->nofsprings;b>0;b--){
2545                                                         bs = sb->bspring + obp->springs[b-1];
2546                                                         if (( sb->totpoint-a == bs->v2)  || ( sb->totpoint-a == bs->v1)){
2547                                                                 attached=1;
2548                                                                 continue;}
2549                                                 }
2550                                                 if (!attached){
2551                                                         float f = tune/(distance) + tune/(compare*compare)*distance - 2.0f*tune/compare ;
2552
2553                                                         VecMidf(velcenter, bp->vec, obp->vec);
2554                                                         VecSubf(dvel,velcenter,bp->vec);
2555                                                         VecMulf(dvel,bp->mass);
2556
2557                                                         Vec3PlusStVec(bp->force,f*(1.0f-sb->balldamp),def);
2558                                                         Vec3PlusStVec(bp->force,sb->balldamp,dvel);
2559
2560                                                         if(nl_flags & NLF_BUILD){
2561                                                                 //int ia =3*(sb->totpoint-a);
2562                                                                 //int ic =3*(sb->totpoint-c);
2563                                                                 //int op =3*sb->totpoint;
2564                                                                 //float mvel = forcetime*sb->nodemass*sb->balldamp;
2565                                                                 //float mpos = forcetime*tune*(1.0f-sb->balldamp);
2566                                                                 /*some quick and dirty entries to the jacobian*/
2567                                                                 //dfdx_goal(ia,ia,op,mpos);
2568                                                                 //dfdv_goal(ia,ia,mvel);
2569                                                                 /* exploit force(a,b) == -force(b,a) part1/2 */
2570                                                                 //dfdx_goal(ic,ic,op,mpos);
2571                                                                 //dfdv_goal(ic,ic,mvel);
2572
2573
2574                                                                 /*TODO sit down an X-out the true jacobian entries*/
2575                                                                 /*well does not make to much sense because the eigenvalues
2576                                                                 of the jacobian go negative; and negative eigenvalues
2577                                                                 on a complex iterative system z(n+1)=A * z(n) 
2578                                                                 give imaginary roots in the charcateristic polynom
2579                                                                 --> solutions that to z(t)=u(t)* exp ( i omega t) --> oscilations we don't want here 
2580                                                                 where u(t) is a unknown amplitude function (worst case rising fast)
2581                                                                 */ 
2582                                                         }
2583
2584                                                         /* exploit force(a,b) == -force(b,a) part2/2 */
2585                                                         VecSubf(dvel,velcenter,obp->vec);
2586                                                         VecMulf(dvel,(bp->mass+obp->mass)/2.0f);
2587
2588                                                         Vec3PlusStVec(obp->force,sb->balldamp,dvel);
2589                                                         Vec3PlusStVec(obp->force,-f*(1.0f-sb->balldamp),def);
2590
2591
2592                                                 }
2593                                         }
2594                                 }
2595                         }
2596                         /* naive ball self collision done */
2597
2598                         if(bp->goal < SOFTGOALSNAP){ /* ommit this bp when it snaps */
2599                                 float auxvect[3];  
2600                                 float velgoal[3];
2601
2602                                 /* do goal stuff */
2603                                 if(ob->softflag & OB_SB_GOAL) {
2604                                         /* true elastic goal */
2605                                         VecSubf(auxvect,bp->pos,bp->origT);
2606                                         ks  = 1.0f/(1.0f- bp->goal*sb->goalspring)-1.0f ;
2607                                         bp->force[0]+= -ks*(auxvect[0]);
2608                                         bp->force[1]+= -ks*(auxvect[1]);
2609                                         bp->force[2]+= -ks*(auxvect[2]);
2610
2611                                         if(nl_flags & NLF_BUILD){
2612                                                 //int ia =3*(sb->totpoint-a);
2613                                                 //int op =3*(sb->totpoint);
2614                                                 /* depending on my pos */ 
2615                                                 //dfdx_goal(ia,ia,op,ks*forcetime);
2616                                         }
2617
2618
2619                                         /* calulate damping forces generated by goals*/
2620                                         VecSubf(velgoal,bp->origS, bp->origE);
2621                                         kd =  sb->goalfrict * sb_fric_force_scale(ob) ;
2622                                         VecAddf(auxvect,velgoal,bp->vec);
2623
2624                                         if (forcetime > 0.0 ) { /* make sure friction does not become rocket motor on time reversal */
2625                                                 bp->force[0]-= kd * (auxvect[0]);
2626                                                 bp->force[1]-= kd * (auxvect[1]);
2627                                                 bp->force[2]-= kd * (auxvect[2]);
2628                                                 if(nl_flags & NLF_BUILD){
2629                                                         //int ia =3*(sb->totpoint-a);
2630                                                         Normalize(auxvect);
2631                                                         /* depending on my vel */ 
2632                                                         //dfdv_goal(ia,ia,kd*forcetime);
2633                                                 }
2634
2635                                         }
2636                                         else {
2637                                                 bp->force[0]-= kd * (velgoal[0] - bp->vec[0]);
2638                                                 bp->force[1]-= kd * (velgoal[1] - bp->vec[1]);
2639                                                 bp->force[2]-= kd * (velgoal[2] - bp->vec[2]);
2640                                         }
2641                                 }
2642                                 /* done goal stuff */
2643
2644
2645                                 /* gravitation */
2646                                 bp->force[2]-= gravity*bp->mass; /* individual mass of node here */
2647
2648
2649                                 /* particle field & vortex */
2650                                 if(do_effector) {
2651                                         float force[3]= {0.0f, 0.0f, 0.0f};
2652                                         float speed[3]= {0.0f, 0.0f, 0.0f};
2653                                         float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */
2654
2655                                         pdDoEffectors(scene, do_effector, bp->pos, force, speed, (float)scene->r.cfra, 0.0f, PE_WIND_AS_SPEED);
2656
2657                                         /* apply forcefield*/
2658                                         VecMulf(force,fieldfactor* eval_sb_fric_force_scale); 
2659                                         VECADD(bp->force, bp->force, force);
2660
2661                                         /* BP friction in moving media */       
2662                                         kd= sb->mediafrict* eval_sb_fric_force_scale;  
2663                                         bp->force[0] -= kd * (bp->vec[0] + windfactor*speed[0]/eval_sb_fric_force_scale);
2664                                         bp->force[1] -= kd * (bp->vec[1] + windfactor*speed[1]/eval_sb_fric_force_scale);
2665                                         bp->force[2] -= kd * (bp->vec[2] + windfactor*speed[2]/eval_sb_fric_force_scale);
2666                                         /* now we'll have nice centrifugal effect for vortex */
2667
2668                                 }
2669                                 else {
2670                                         /* BP friction in media (not) moving*/
2671                                         kd= sb->mediafrict* sb_fric_force_scale(ob);  
2672                                         /* assume it to be proportional to actual velocity */
2673                                         bp->force[0]-= bp->vec[0]*kd;