Fix infinite recursion when using adjustment strip placed to channel 1
[blender.git] / source / blender / blenkernel / intern / collision.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/collision.c
29  *  \ingroup bke
30  */
31
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BKE_cloth.h"
36
37 #include "DNA_cloth_types.h"
38 #include "DNA_group_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_object_force.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BLI_utildefines.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_edgehash.h"
49 #include "BLI_utildefines.h"
50 #include "BLI_ghash.h"
51 #include "BLI_memarena.h"
52 #include "BLI_rand.h"
53
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_global.h"
56 #include "BKE_scene.h"
57 #include "BKE_mesh.h"
58 #include "BKE_object.h"
59 #include "BKE_modifier.h"
60
61 #include "BKE_DerivedMesh.h"
62 #ifdef USE_BULLET
63 #include "Bullet-C-Api.h"
64 #endif
65 #include "BLI_kdopbvh.h"
66 #include "BKE_collision.h"
67
68 #ifdef WITH_ELTOPO
69 #include "eltopo-capi.h"
70 #endif
71
72
73 /***********************************
74 Collision modifier code start
75 ***********************************/
76
77 /* step is limited from 0 (frame start position) to 1 (frame end position) */
78 void collision_move_object(CollisionModifierData *collmd, float step, float prevstep)
79 {
80         float tv[3] = {0, 0, 0};
81         unsigned int i = 0;
82
83         for ( i = 0; i < collmd->numverts; i++ ) {
84                 sub_v3_v3v3(tv, collmd->xnew[i].co, collmd->x[i].co);
85                 VECADDS(collmd->current_x[i].co, collmd->x[i].co, tv, prevstep);
86                 VECADDS(collmd->current_xnew[i].co, collmd->x[i].co, tv, step);
87                 sub_v3_v3v3(collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co);
88         }
89
90         bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
91 }
92
93 BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int UNUSED(numverts), float epsilon )
94 {
95         BVHTree *tree;
96         float co[12];
97         unsigned int i;
98         MFace *tface = mfaces;
99
100         tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
101
102         // fill tree
103         for ( i = 0; i < numfaces; i++, tface++ ) {
104                 copy_v3_v3 ( &co[0*3], x[tface->v1].co );
105                 copy_v3_v3 ( &co[1*3], x[tface->v2].co );
106                 copy_v3_v3 ( &co[2*3], x[tface->v3].co );
107                 if ( tface->v4 )
108                         copy_v3_v3 ( &co[3*3], x[tface->v4].co );
109
110                 BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
111         }
112
113         // balance tree
114         BLI_bvhtree_balance ( tree );
115
116         return tree;
117 }
118
119 void bvhtree_update_from_mvert(BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int UNUSED(numverts), int moving )
120 {
121         int i;
122         MFace *mfaces = faces;
123         float co[12], co_moving[12];
124         int ret = 0;
125
126         if ( !bvhtree )
127                 return;
128
129         if ( x ) {
130                 for ( i = 0; i < numfaces; i++, mfaces++ ) {
131                         copy_v3_v3 ( &co[0*3], x[mfaces->v1].co );
132                         copy_v3_v3 ( &co[1*3], x[mfaces->v2].co );
133                         copy_v3_v3 ( &co[2*3], x[mfaces->v3].co );
134                         if ( mfaces->v4 )
135                                 copy_v3_v3 ( &co[3*3], x[mfaces->v4].co );
136
137                         // copy new locations into array
138                         if ( moving && xnew ) {
139                                 // update moving positions
140                                 copy_v3_v3 ( &co_moving[0*3], xnew[mfaces->v1].co );
141                                 copy_v3_v3 ( &co_moving[1*3], xnew[mfaces->v2].co );
142                                 copy_v3_v3 ( &co_moving[2*3], xnew[mfaces->v3].co );
143                                 if ( mfaces->v4 )
144                                         copy_v3_v3 ( &co_moving[3*3], xnew[mfaces->v4].co );
145
146                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
147                         }
148                         else {
149                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
150                         }
151
152                         // check if tree is already full
153                         if ( !ret )
154                                 break;
155                 }
156
157                 BLI_bvhtree_update_tree ( bvhtree );
158         }
159 }
160
161 /***********************************
162 Collision modifier code end
163 ***********************************/
164 #define mySWAP(a, b) do { double tmp = b ; b = a ; a = tmp ; } while (0)
165
166
167 // w3 is not perfect
168 static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
169 {
170         double  tempV1[3], tempV2[3], tempV4[3];
171         double  a, b, c, d, e, f;
172
173         VECSUB ( tempV1, p1, p3 );
174         VECSUB ( tempV2, p2, p3 );
175         VECSUB ( tempV4, pv, p3 );
176
177         a = INPR ( tempV1, tempV1 );
178         b = INPR ( tempV1, tempV2 );
179         c = INPR ( tempV2, tempV2 );
180         e = INPR ( tempV1, tempV4 );
181         f = INPR ( tempV2, tempV4 );
182
183         d = ( a * c - b * b );
184
185         if ( ABS ( d ) < (double)ALMOST_ZERO ) {
186                 *w1 = *w2 = *w3 = 1.0 / 3.0;
187                 return;
188         }
189
190         w1[0] = ( float ) ( ( e * c - b * f ) / d );
191
192         if ( w1[0] < 0 )
193                 w1[0] = 0;
194
195         w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
196
197         if ( w2[0] < 0 )
198                 w2[0] = 0;
199
200         w3[0] = 1.0f - w1[0] - w2[0];
201 }
202
203 DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
204 {
205         zero_v3(to);
206         VECADDMUL(to, v1, w1);
207         VECADDMUL(to, v2, w2);
208         VECADDMUL(to, v3, w3);
209 }
210
211 static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
212 {
213         int result = 0;
214         Cloth *cloth1;
215         float w1, w2, w3, u1, u2, u3;
216         float v1[3], v2[3], relativeVelocity[3];
217         float magrelVel;
218         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
219
220         cloth1 = clmd->clothObject;
221
222         for ( ; collpair != collision_end; collpair++ ) {
223                 float i1[3], i2[3], i3[3];
224
225                 zero_v3(i1);
226                 zero_v3(i2);
227                 zero_v3(i3);
228
229                 /* only handle static collisions here */
230                 if ( collpair->flag & COLLISION_IN_FUTURE )
231                         continue;
232
233                 /* compute barycentric coordinates for both collision points */
234                 collision_compute_barycentric ( collpair->pa,
235                         cloth1->verts[collpair->ap1].txold,
236                         cloth1->verts[collpair->ap2].txold,
237                         cloth1->verts[collpair->ap3].txold,
238                         &w1, &w2, &w3 );
239
240                 /* was: txold */
241                 collision_compute_barycentric ( collpair->pb,
242                         collmd->current_x[collpair->bp1].co,
243                         collmd->current_x[collpair->bp2].co,
244                         collmd->current_x[collpair->bp3].co,
245                         &u1, &u2, &u3 );
246
247                 /* Calculate relative "velocity". */
248                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
249
250                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
251
252                 sub_v3_v3v3(relativeVelocity, v2, v1);
253
254                 /* Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). */
255                 magrelVel = dot_v3v3(relativeVelocity, collpair->normal);
256
257                 /* printf("magrelVel: %f\n", magrelVel); */
258
259                 /* Calculate masses of points.
260                  * TODO */
261
262                 /* If v_n_mag < 0 the edges are approaching each other. */
263                 if ( magrelVel > ALMOST_ZERO ) {
264                         /* Calculate Impulse magnitude to stop all motion in normal direction. */
265                         float magtangent = 0, repulse = 0, d = 0;
266                         double impulse = 0.0;
267                         float vrel_t_pre[3];
268                         float temp[3], spf;
269
270                         /* calculate tangential velocity */
271                         copy_v3_v3 ( temp, collpair->normal );
272                         mul_v3_fl(temp, magrelVel);
273                         sub_v3_v3v3(vrel_t_pre, relativeVelocity, temp);
274
275                         /* Decrease in magnitude of relative tangential velocity due to coulomb friction
276                          * in original formula "magrelVel" should be the "change of relative velocity in normal direction" */
277                         magtangent = minf(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre)));
278
279                         /* Apply friction impulse. */
280                         if ( magtangent > ALMOST_ZERO ) {
281                                 normalize_v3(vrel_t_pre);
282
283                                 impulse = magtangent / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* 2.0 * */
284                                 VECADDMUL ( i1, vrel_t_pre, w1 * impulse );
285                                 VECADDMUL ( i2, vrel_t_pre, w2 * impulse );
286                                 VECADDMUL ( i3, vrel_t_pre, w3 * impulse );
287                         }
288
289                         /* Apply velocity stopping impulse
290                          * I_c = m * v_N / 2.0
291                          * no 2.0 * magrelVel normally, but looks nicer DG */
292                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
293
294                         VECADDMUL ( i1, collpair->normal, w1 * impulse );
295                         cloth1->verts[collpair->ap1].impulse_count++;
296
297                         VECADDMUL ( i2, collpair->normal, w2 * impulse );
298                         cloth1->verts[collpair->ap2].impulse_count++;
299
300                         VECADDMUL ( i3, collpair->normal, w3 * impulse );
301                         cloth1->verts[collpair->ap3].impulse_count++;
302
303                         /* Apply repulse impulse if distance too short
304                          * I_r = -min(dt*kd, m(0, 1d/dt - v_n))
305                          * DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
306                          * v += impulse; x_new = x + v;
307                          * We don't use dt!!
308                          * DG TODO: Fix usage of dt here! */
309                         spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
310
311                         d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
312                         if ( ( magrelVel < 0.1f*d*spf ) && ( d > ALMOST_ZERO ) ) {
313                                 repulse = MIN2 ( d*1.0f/spf, 0.1f*d*spf - magrelVel );
314
315                                 /* stay on the safe side and clamp repulse */
316                                 if ( impulse > ALMOST_ZERO )
317                                         repulse = MIN2 ( repulse, 5.0*impulse );
318                                 repulse = MAX2 ( impulse, repulse );
319
320                                 impulse = repulse / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* original 2.0 / 0.25 */
321                                 VECADDMUL ( i1, collpair->normal,  impulse );
322                                 VECADDMUL ( i2, collpair->normal,  impulse );
323                                 VECADDMUL ( i3, collpair->normal,  impulse );
324                         }
325
326                         result = 1;
327                 }
328                 else {
329                         /* Apply repulse impulse if distance too short
330                          * I_r = -min(dt*kd, max(0, 1d/dt - v_n))
331                          * DG: this formula ineeds to be changed for this code since we apply impulses/repulses like this:
332                          * v += impulse; x_new = x + v;
333                          * We don't use dt!! */
334                         float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
335
336                         float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance;
337                         if ( d > ALMOST_ZERO) {
338                                 /* stay on the safe side and clamp repulse */
339                                 float repulse = d*1.0f/spf;
340
341                                 float impulse = repulse / ( 3.0 * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */
342
343                                 VECADDMUL ( i1, collpair->normal,  impulse );
344                                 VECADDMUL ( i2, collpair->normal,  impulse );
345                                 VECADDMUL ( i3, collpair->normal,  impulse );
346
347                                 cloth1->verts[collpair->ap1].impulse_count++;
348                                 cloth1->verts[collpair->ap2].impulse_count++;
349                                 cloth1->verts[collpair->ap3].impulse_count++;
350
351                                 result = 1;
352                         }
353                 }
354
355                 if (result) {
356                         int i = 0;
357
358                         for (i = 0; i < 3; i++) {
359                                 if (cloth1->verts[collpair->ap1].impulse_count > 0 && ABS(cloth1->verts[collpair->ap1].impulse[i]) < ABS(i1[i]))
360                                         cloth1->verts[collpair->ap1].impulse[i] = i1[i];
361
362                                 if (cloth1->verts[collpair->ap2].impulse_count > 0 && ABS(cloth1->verts[collpair->ap2].impulse[i]) < ABS(i2[i]))
363                                         cloth1->verts[collpair->ap2].impulse[i] = i2[i];
364
365                                 if (cloth1->verts[collpair->ap3].impulse_count > 0 && ABS(cloth1->verts[collpair->ap3].impulse[i]) < ABS(i3[i]))
366                                         cloth1->verts[collpair->ap3].impulse[i] = i3[i];
367                         }
368                 }
369         }
370         return result;
371 }
372
373 //Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned
374 static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2,
375                                  BVHTreeOverlap *overlap, CollPair *collpair, float UNUSED(dt))
376 {
377         ClothModifierData *clmd = (ClothModifierData *)md1;
378         CollisionModifierData *collmd = (CollisionModifierData *) md2;
379         /* Cloth *cloth = clmd->clothObject; */ /* UNUSED */
380         MFace *face1=NULL, *face2 = NULL;
381 #ifdef USE_BULLET
382         ClothVertex *verts1 = clmd->clothObject->verts;
383 #endif
384         double distance = 0;
385         float epsilon1 = clmd->coll_parms->epsilon;
386         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
387         int i;
388
389         face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
390         face2 = & ( collmd->mfaces[overlap->indexB] );
391
392         // check all 4 possible collisions
393         for ( i = 0; i < 4; i++ ) {
394                 if ( i == 0 ) {
395                         // fill faceA
396                         collpair->ap1 = face1->v1;
397                         collpair->ap2 = face1->v2;
398                         collpair->ap3 = face1->v3;
399
400                         // fill faceB
401                         collpair->bp1 = face2->v1;
402                         collpair->bp2 = face2->v2;
403                         collpair->bp3 = face2->v3;
404                 }
405                 else if ( i == 1 ) {
406                         if ( face1->v4 ) {
407                                 // fill faceA
408                                 collpair->ap1 = face1->v1;
409                                 collpair->ap2 = face1->v3;
410                                 collpair->ap3 = face1->v4;
411
412                                 // fill faceB
413                                 collpair->bp1 = face2->v1;
414                                 collpair->bp2 = face2->v2;
415                                 collpair->bp3 = face2->v3;
416                         }
417                         else {
418                                 i++;
419                         }
420                 }
421                 if ( i == 2 ) {
422                         if ( face2->v4 ) {
423                                 // fill faceA
424                                 collpair->ap1 = face1->v1;
425                                 collpair->ap2 = face1->v2;
426                                 collpair->ap3 = face1->v3;
427
428                                 // fill faceB
429                                 collpair->bp1 = face2->v1;
430                                 collpair->bp2 = face2->v4;
431                                 collpair->bp3 = face2->v3;
432                         }
433                         else {
434                                 break;
435                         }
436                 }
437                 else if ( i == 3 ) {
438                         if ( face1->v4 && face2->v4 ) {
439                                 // fill faceA
440                                 collpair->ap1 = face1->v1;
441                                 collpair->ap2 = face1->v3;
442                                 collpair->ap3 = face1->v4;
443
444                                 // fill faceB
445                                 collpair->bp1 = face2->v1;
446                                 collpair->bp2 = face2->v3;
447                                 collpair->bp3 = face2->v4;
448                         }
449                         else {
450                                 break;
451                         }
452                 }
453                 
454 #ifdef USE_BULLET
455                 // calc distance + normal
456                 distance = plNearestPoints (
457                         verts1[collpair->ap1].txold, verts1[collpair->ap2].txold, verts1[collpair->ap3].txold, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, collpair->pa, collpair->pb, collpair->vector );
458 #else
459                 // just be sure that we don't add anything
460                 distance = 2.0 * (double)( epsilon1 + epsilon2 + ALMOST_ZERO );
461 #endif
462
463                 if (distance <= (epsilon1 + epsilon2 + ALMOST_ZERO)) {
464                         normalize_v3_v3(collpair->normal, collpair->vector);
465
466                         collpair->distance = distance;
467                         collpair->flag = 0;
468                         collpair++;
469                 }/*
470                 else {
471                         float w1, w2, w3, u1, u2, u3;
472                         float v1[3], v2[3], relativeVelocity[3];
473
474                         // calc relative velocity
475                         
476                         // compute barycentric coordinates for both collision points
477                         collision_compute_barycentric ( collpair->pa,
478                         verts1[collpair->ap1].txold,
479                         verts1[collpair->ap2].txold,
480                         verts1[collpair->ap3].txold,
481                         &w1, &w2, &w3 );
482
483                         // was: txold
484                         collision_compute_barycentric ( collpair->pb,
485                         collmd->current_x[collpair->bp1].co,
486                         collmd->current_x[collpair->bp2].co,
487                         collmd->current_x[collpair->bp3].co,
488                         &u1, &u2, &u3 );
489
490                         // Calculate relative "velocity".
491                         collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
492
493                         collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
494
495                         sub_v3_v3v3(relativeVelocity, v2, v1);
496
497                         if (sqrt(dot_v3v3(relativeVelocity, relativeVelocity)) >= distance)
498                         {
499                                 // check for collision in the future
500                                 collpair->flag |= COLLISION_IN_FUTURE;
501                                 collpair++;
502                         }
503                 }*/
504         }
505         return collpair;
506 }
507
508 static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned int *maxobj, Object *ob, Object *self, int level, unsigned int modifier_type)
509 {
510         CollisionModifierData *cmd= NULL;
511
512         if (ob == self)
513                 return;
514
515         /* only get objects with collision modifier */
516         if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision))
517                 cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type);
518         
519         if (cmd) {      
520                 /* extend array */
521                 if (*numobj >= *maxobj) {
522                         *maxobj *= 2;
523                         *objs= MEM_reallocN(*objs, sizeof(Object*)*(*maxobj));
524                 }
525                 
526                 (*objs)[*numobj] = ob;
527                 (*numobj)++;
528         }
529
530         /* objects in dupli groups, one level only for now */
531         if (ob->dup_group && level == 0) {
532                 GroupObject *go;
533                 Group *group= ob->dup_group;
534
535                 /* add objects */
536                 for (go= group->gobject.first; go; go= go->next)
537                         add_collision_object(objs, numobj, maxobj, go->ob, self, level+1, modifier_type);
538         }       
539 }
540
541 // return all collision objects in scene
542 // collision object will exclude self 
543 Object **get_collisionobjects(Scene *scene, Object *self, Group *group, unsigned int *numcollobj, unsigned int modifier_type)
544 {
545         Base *base;
546         Object **objs;
547         GroupObject *go;
548         unsigned int numobj= 0, maxobj= 100;
549         
550         objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
551
552         /* gather all collision objects */
553         if (group) {
554                 /* use specified group */
555                 for (go= group->gobject.first; go; go= go->next)
556                         add_collision_object(&objs, &numobj, &maxobj, go->ob, self, 0, modifier_type);
557         }
558         else {
559                 Scene *sce_iter;
560                 /* add objects in same layer in scene */
561                 for (SETLOOPER(scene, sce_iter, base)) {
562                         if (base->lay & self->lay)
563                                 add_collision_object(&objs, &numobj, &maxobj, base->object, self, 0, modifier_type);
564
565                 }
566         }
567
568         *numcollobj= numobj;
569
570         return objs;
571 }
572
573 static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, int level)
574 {
575         CollisionModifierData *cmd= NULL;
576         ColliderCache *col;
577
578         if (ob == self)
579                 return;
580
581         if (ob->pd && ob->pd->deflect)
582                 cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision);
583         
584         if (cmd && cmd->bvhtree) {      
585                 if (*objs == NULL)
586                         *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array");
587
588                 col = MEM_callocN(sizeof(ColliderCache), "ColliderCache");
589                 col->ob = ob;
590                 col->collmd = cmd;
591                 /* make sure collider is properly set up */
592                 collision_move_object(cmd, 1.0, 0.0);
593                 BLI_addtail(*objs, col);
594         }
595
596         /* objects in dupli groups, one level only for now */
597         if (ob->dup_group && level == 0) {
598                 GroupObject *go;
599                 Group *group= ob->dup_group;
600
601                 /* add objects */
602                 for (go= group->gobject.first; go; go= go->next)
603                         add_collider_cache_object(objs, go->ob, self, level+1);
604         }
605 }
606
607 ListBase *get_collider_cache(Scene *scene, Object *self, Group *group)
608 {
609         GroupObject *go;
610         ListBase *objs= NULL;
611         
612         /* add object in same layer in scene */
613         if (group) {
614                 for (go= group->gobject.first; go; go= go->next)
615                         add_collider_cache_object(&objs, go->ob, self, 0);
616         }
617         else {
618                 Scene *sce_iter;
619                 Base *base;
620
621                 /* add objects in same layer in scene */
622                 for (SETLOOPER(scene, sce_iter, base)) {
623                         if (!self || (base->lay & self->lay))
624                                 add_collider_cache_object(&objs, base->object, self, 0);
625
626                 }
627         }
628
629         return objs;
630 }
631
632 void free_collider_cache(ListBase **colliders)
633 {
634         if (*colliders) {
635                 BLI_freelistN(*colliders);
636                 MEM_freeN(*colliders);
637                 *colliders = NULL;
638         }
639 }
640
641
642 static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd,
643         CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt)
644 {
645         int i;
646         
647         *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 64, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
648         *collisions_index = *collisions;
649
650         for ( i = 0; i < numresult; i++ ) {
651                 *collisions_index = cloth_collision ( (ModifierData *)clmd, (ModifierData *)collmd,
652                                                       overlap+i, *collisions_index, dt );
653         }
654 }
655
656 static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
657 {
658         Cloth *cloth = clmd->clothObject;
659         int i=0, j = 0, /*numfaces = 0, */ numverts = 0;
660         ClothVertex *verts = NULL;
661         int ret = 0;
662         int result = 0;
663         
664         numverts = clmd->clothObject->numverts;
665         verts = cloth->verts;
666         
667         // process all collisions (calculate impulses, TODO: also repulses if distance too short)
668         result = 1;
669         for ( j = 0; j < 2; j++ ) { /* 5 is just a value that ensures convergence */
670                 result = 0;
671
672                 if ( collmd->bvhtree ) {
673                         result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
674
675                         // apply impulses in parallel
676                         if (result) {
677                                 for (i = 0; i < numverts; i++) {
678                                         // calculate "velocities" (just xnew = xold + v; no dt in v)
679                                         if (verts[i].impulse_count) {
680                                                 // VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
681                                                 VECADD ( verts[i].tv, verts[i].tv, verts[i].impulse);
682                                                 zero_v3(verts[i].impulse);
683                                                 verts[i].impulse_count = 0;
684
685                                                 ret++;
686                                         }
687                                 }
688                         }
689                 }
690
691                 if (!result) {
692                         break;
693                 }
694         }
695         return ret;
696 }
697
698 // cloth - object collisions
699 int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, float dt )
700 {
701         Cloth *cloth= clmd->clothObject;
702         BVHTree *cloth_bvh= cloth->bvhtree;
703         unsigned int i=0, /* numfaces = 0, */ /* UNUSED */ numverts = 0, k, l, j;
704         int rounds = 0; // result counts applied collisions; ic is for debug output;
705         ClothVertex *verts = NULL;
706         int ret = 0, ret2 = 0;
707         Object **collobjs = NULL;
708         unsigned int numcollobj = 0;
709
710         if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL)
711                 return 0;
712         
713         verts = cloth->verts;
714         /* numfaces = cloth->numfaces; */ /* UNUSED */
715         numverts = cloth->numverts;
716
717         ////////////////////////////////////////////////////////////
718         // static collisions
719         ////////////////////////////////////////////////////////////
720
721         // update cloth bvh
722         bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
723         bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
724         
725         collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision);
726         
727         if (!collobjs)
728                 return 0;
729
730         /* move object to position (step) in time */
731         for (i = 0; i < numcollobj; i++) {
732                 Object *collob= collobjs[i];
733                 CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
734
735                 if (!collmd->bvhtree)
736                         continue;
737
738                 /* move object to position (step) in time */
739                 collision_move_object ( collmd, step + dt, step );
740         }
741
742         do
743         {
744                 CollPair **collisions, **collisions_index;
745                 
746                 ret2 = 0;
747
748                 collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair");
749                 collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair");
750                 
751                 // check all collision objects
752                 for (i = 0; i < numcollobj; i++) {
753                         Object *collob= collobjs[i];
754                         CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
755                         BVHTreeOverlap *overlap = NULL;
756                         unsigned int result = 0;
757                         
758                         if (!collmd->bvhtree)
759                                 continue;
760                         
761                         /* search for overlapping collision pairs */
762                         overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
763                                 
764                         // go to next object if no overlap is there
765                         if ( result && overlap ) {
766                                 /* check if collisions really happen (costly near check) */
767                                 cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], 
768                                         &collisions_index[i], result, overlap, dt/(float)clmd->coll_parms->loop_count);
769                         
770                                 // resolve nearby collisions
771                                 ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i],  collisions_index[i]);
772                                 ret2 += ret;
773                         }
774
775                         if ( overlap )
776                                 MEM_freeN ( overlap );
777                 }
778                 rounds++;
779                 
780                 for (i = 0; i < numcollobj; i++) {
781                         if ( collisions[i] ) MEM_freeN ( collisions[i] );
782                 }
783                         
784                 MEM_freeN(collisions);
785                 MEM_freeN(collisions_index);
786
787                 ////////////////////////////////////////////////////////////
788                 // update positions
789                 // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
790                 ////////////////////////////////////////////////////////////
791
792                 // verts come from clmd
793                 for ( i = 0; i < numverts; i++ ) {
794                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) {
795                                 if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) {
796                                         continue;
797                                 }
798                         }
799
800                         VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
801                 }
802                 ////////////////////////////////////////////////////////////
803                 
804                 
805                 ////////////////////////////////////////////////////////////
806                 // Test on *simple* selfcollisions
807                 ////////////////////////////////////////////////////////////
808                 if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) {
809                         for (l = 0; l < (unsigned int)clmd->coll_parms->self_loop_count; l++) {
810                                 /* TODO: add coll quality rounds again */
811                                 BVHTreeOverlap *overlap = NULL;
812                                 unsigned int result = 0;
813         
814                                 // collisions = 1;
815                                 verts = cloth->verts; // needed for openMP
816         
817                                 /* numfaces = cloth->numfaces; */ /* UNUSED */
818                                 numverts = cloth->numverts;
819         
820                                 verts = cloth->verts;
821         
822                                 if ( cloth->bvhselftree ) {
823                                         // search for overlapping collision pairs
824                                         overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
825         
826         // #pragma omp parallel for private(k, i, j) schedule(static)
827                                         for ( k = 0; k < result; k++ ) {
828                                                 float temp[3];
829                                                 float length = 0;
830                                                 float mindistance;
831         
832                                                 i = overlap[k].indexA;
833                                                 j = overlap[k].indexB;
834         
835                                                 mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
836         
837                                                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) {
838                                                         if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) &&
839                                                              ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
840                                                         {
841                                                                 continue;
842                                                         }
843                                                 }
844
845                                                 if ((cloth->verts[i].flags & CLOTH_VERT_FLAG_NOSELFCOLL) ||
846                                                     (cloth->verts[j].flags & CLOTH_VERT_FLAG_NOSELFCOLL))
847                                                 {
848                                                         continue;
849                                                 }
850         
851                                                 sub_v3_v3v3(temp, verts[i].tx, verts[j].tx);
852         
853                                                 if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
854         
855                                                 // check for adjacent points (i must be smaller j)
856                                                 if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) ) {
857                                                         continue;
858                                                 }
859         
860                                                 length = normalize_v3(temp );
861         
862                                                 if ( length < mindistance ) {
863                                                         float correction = mindistance - length;
864         
865                                                         if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) {
866                                                                 mul_v3_fl(temp, -correction);
867                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
868                                                         }
869                                                         else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) {
870                                                                 mul_v3_fl(temp, correction);
871                                                                 VECADD ( verts[i].tx, verts[i].tx, temp );
872                                                         }
873                                                         else {
874                                                                 mul_v3_fl(temp, correction * -0.5);
875                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
876         
877                                                                 sub_v3_v3v3(verts[i].tx, verts[i].tx, temp);
878                                                         }
879                                                         ret = 1;
880                                                         ret2 += ret;
881                                                 }
882                                                 else {
883                                                         // check for approximated time collisions
884                                                 }
885                                         }
886         
887                                         if ( overlap )
888                                                 MEM_freeN ( overlap );
889         
890                                 }
891                         }
892                         ////////////////////////////////////////////////////////////
893
894                         ////////////////////////////////////////////////////////////
895                         // SELFCOLLISIONS: update velocities
896                         ////////////////////////////////////////////////////////////
897                         if ( ret2 ) {
898                                 for ( i = 0; i < cloth->numverts; i++ ) {
899                                         if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) ) {
900                                                 sub_v3_v3v3(verts[i].tv, verts[i].tx, verts[i].txold);
901                                         }
902                                 }
903                         }
904                         ////////////////////////////////////////////////////////////
905                 }
906         }
907         while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
908         
909         if (collobjs)
910                 MEM_freeN(collobjs);
911
912         return 1|MIN2 ( ret, 1 );
913 }