building without bullet didnt work
[blender.git] / source / blender / blenkernel / intern / collision.c
1 /*  collision.c
2 *
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) Blender Foundation
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): none yet.
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 */
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BKE_cloth.h"
33
34 #include "DNA_cloth_types.h"
35 #include "DNA_group_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_object_force.h"
39 #include "DNA_scene_types.h"
40
41 #include "BKE_DerivedMesh.h"
42 #include "BKE_global.h"
43 #include "BKE_mesh.h"
44 #include "BKE_object.h"
45 #include "BKE_modifier.h"
46 #include "BKE_utildefines.h"
47 #include "BKE_DerivedMesh.h"
48 #ifdef USE_BULLET
49 #include "Bullet-C-Api.h"
50 #endif
51 #include "BLI_kdopbvh.h"
52 #include "BKE_collision.h"
53
54
55 /***********************************
56 Collision modifier code start
57 ***********************************/
58
59 /* step is limited from 0 (frame start position) to 1 (frame end position) */
60 void collision_move_object ( CollisionModifierData *collmd, float step, float prevstep )
61 {
62         float tv[3] = {0,0,0};
63         unsigned int i = 0;
64
65         for ( i = 0; i < collmd->numverts; i++ )
66         {
67                 VECSUB ( tv, collmd->xnew[i].co, collmd->x[i].co );
68                 VECADDS ( collmd->current_x[i].co, collmd->x[i].co, tv, prevstep );
69                 VECADDS ( collmd->current_xnew[i].co, collmd->x[i].co, tv, step );
70                 VECSUB ( collmd->current_v[i].co, collmd->current_xnew[i].co, collmd->current_x[i].co );
71         }
72         bvhtree_update_from_mvert ( collmd->bvhtree, collmd->mfaces, collmd->numfaces, collmd->current_x, collmd->current_xnew, collmd->numverts, 1 );
73 }
74
75 BVHTree *bvhtree_build_from_mvert ( MFace *mfaces, unsigned int numfaces, MVert *x, unsigned int numverts, float epsilon )
76 {
77         BVHTree *tree;
78         float co[12];
79         int i;
80         MFace *tface = mfaces;
81
82         tree = BLI_bvhtree_new ( numfaces*2, epsilon, 4, 26 );
83
84         // fill tree
85         for ( i = 0; i < numfaces; i++, tface++ )
86         {
87                 VECCOPY ( &co[0*3], x[tface->v1].co );
88                 VECCOPY ( &co[1*3], x[tface->v2].co );
89                 VECCOPY ( &co[2*3], x[tface->v3].co );
90                 if ( tface->v4 )
91                         VECCOPY ( &co[3*3], x[tface->v4].co );
92
93                 BLI_bvhtree_insert ( tree, i, co, ( mfaces->v4 ? 4 : 3 ) );
94         }
95
96         // balance tree
97         BLI_bvhtree_balance ( tree );
98
99         return tree;
100 }
101
102 void bvhtree_update_from_mvert ( BVHTree * bvhtree, MFace *faces, int numfaces, MVert *x, MVert *xnew, int numverts, int moving )
103 {
104         int i;
105         MFace *mfaces = faces;
106         float co[12], co_moving[12];
107         int ret = 0;
108
109         if ( !bvhtree )
110                 return;
111
112         if ( x )
113         {
114                 for ( i = 0; i < numfaces; i++, mfaces++ )
115                 {
116                         VECCOPY ( &co[0*3], x[mfaces->v1].co );
117                         VECCOPY ( &co[1*3], x[mfaces->v2].co );
118                         VECCOPY ( &co[2*3], x[mfaces->v3].co );
119                         if ( mfaces->v4 )
120                                 VECCOPY ( &co[3*3], x[mfaces->v4].co );
121
122                         // copy new locations into array
123                         if ( moving && xnew )
124                         {
125                                 // update moving positions
126                                 VECCOPY ( &co_moving[0*3], xnew[mfaces->v1].co );
127                                 VECCOPY ( &co_moving[1*3], xnew[mfaces->v2].co );
128                                 VECCOPY ( &co_moving[2*3], xnew[mfaces->v3].co );
129                                 if ( mfaces->v4 )
130                                         VECCOPY ( &co_moving[3*3], xnew[mfaces->v4].co );
131
132                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, co_moving, ( mfaces->v4 ? 4 : 3 ) );
133                         }
134                         else
135                         {
136                                 ret = BLI_bvhtree_update_node ( bvhtree, i, co, NULL, ( mfaces->v4 ? 4 : 3 ) );
137                         }
138
139                         // check if tree is already full
140                         if ( !ret )
141                                 break;
142                 }
143
144                 BLI_bvhtree_update_tree ( bvhtree );
145         }
146 }
147
148 /***********************************
149 Collision modifier code end
150 ***********************************/
151
152 /**
153 * gsl_poly_solve_cubic -
154 *
155 * copied from SOLVE_CUBIC.C --> GSL
156 */
157
158 #define mySWAP(a,b) do { double tmp = b ; b = a ; a = tmp ; } while(0)
159
160 int 
161 gsl_poly_solve_cubic (double a, double b, double c, 
162                                           double *x0, double *x1, double *x2)
163 {
164         double q = (a * a - 3 * b);
165         double r = (2 * a * a * a - 9 * a * b + 27 * c);
166
167         double Q = q / 9;
168         double R = r / 54;
169
170         double Q3 = Q * Q * Q;
171         double R2 = R * R;
172
173         double CR2 = 729 * r * r;
174         double CQ3 = 2916 * q * q * q;
175
176         if (R == 0 && Q == 0)
177         {
178                 *x0 = - a / 3 ;
179                 *x1 = - a / 3 ;
180                 *x2 = - a / 3 ;
181                 return 3 ;
182         }
183         else if (CR2 == CQ3) 
184         {
185                 /* this test is actually R2 == Q3, written in a form suitable
186                 for exact computation with integers */
187
188                 /* Due to finite precision some double roots may be missed, and
189                 considered to be a pair of complex roots z = x +/- epsilon i
190                 close to the real axis. */
191
192                 double sqrtQ = sqrt (Q);
193
194                 if (R > 0)
195                 {
196                         *x0 = -2 * sqrtQ  - a / 3;
197                         *x1 = sqrtQ - a / 3;
198                         *x2 = sqrtQ - a / 3;
199                 }
200                 else
201                 {
202                         *x0 = - sqrtQ  - a / 3;
203                         *x1 = - sqrtQ - a / 3;
204                         *x2 = 2 * sqrtQ - a / 3;
205                 }
206                 return 3 ;
207         }
208         else if (CR2 < CQ3) /* equivalent to R2 < Q3 */
209         {
210                 double sqrtQ = sqrt (Q);
211                 double sqrtQ3 = sqrtQ * sqrtQ * sqrtQ;
212                 double theta = acos (R / sqrtQ3);
213                 double norm = -2 * sqrtQ;
214                 *x0 = norm * cos (theta / 3) - a / 3;
215                 *x1 = norm * cos ((theta + 2.0 * M_PI) / 3) - a / 3;
216                 *x2 = norm * cos ((theta - 2.0 * M_PI) / 3) - a / 3;
217
218                 /* Sort *x0, *x1, *x2 into increasing order */
219
220                 if (*x0 > *x1)
221                         mySWAP(*x0, *x1) ;
222
223                 if (*x1 > *x2)
224                 {
225                         mySWAP(*x1, *x2) ;
226
227                         if (*x0 > *x1)
228                                 mySWAP(*x0, *x1) ;
229                 }
230
231                 return 3;
232         }
233         else
234         {
235                 double sgnR = (R >= 0 ? 1 : -1);
236                 double A = -sgnR * pow (fabs (R) + sqrt (R2 - Q3), 1.0/3.0);
237                 double B = Q / A ;
238                 *x0 = A + B - a / 3;
239                 return 1;
240         }
241 }
242
243
244
245 /**
246 * gsl_poly_solve_quadratic
247 *
248 * copied from GSL
249 */
250 int 
251 gsl_poly_solve_quadratic (double a, double b, double c, 
252                                                   double *x0, double *x1)
253 {
254         double disc = b * b - 4 * a * c;
255
256         if (a == 0) /* Handle linear case */
257         {
258                 if (b == 0)
259                 {
260                         return 0;
261                 }
262                 else
263                 {
264                         *x0 = -c / b;
265                         return 1;
266                 };
267         }
268
269         if (disc > 0)
270         {
271                 if (b == 0)
272                 {
273                         double r = fabs (0.5 * sqrt (disc) / a);
274                         *x0 = -r;
275                         *x1 =  r;
276                 }
277                 else
278                 {
279                         double sgnb = (b > 0 ? 1 : -1);
280                         double temp = -0.5 * (b + sgnb * sqrt (disc));
281                         double r1 = temp / a ;
282                         double r2 = c / temp ;
283
284                         if (r1 < r2) 
285                         {
286                                 *x0 = r1 ;
287                                 *x1 = r2 ;
288                         } 
289                         else 
290                         {
291                                 *x0 = r2 ;
292                                 *x1 = r1 ;
293                         }
294                 }
295                 return 2;
296         }
297         else if (disc == 0) 
298         {
299                 *x0 = -0.5 * b / a ;
300                 *x1 = -0.5 * b / a ;
301                 return 2 ;
302         }
303         else
304         {
305                 return 0;
306         }
307 }
308
309
310
311
312 /*
313 * See Bridson et al. "Robust Treatment of Collision, Contact and Friction for Cloth Animation"
314 *     page 4, left column
315 */
316 static int cloth_get_collision_time ( double a[3], double b[3], double c[3], double d[3], double e[3], double f[3], double solution[3] )
317 {
318         int num_sols = 0;
319
320         // x^0 - checked 
321         double g =      a[0] * c[1] * e[2] - a[0] * c[2] * e[1] +
322                 a[1] * c[2] * e[0] - a[1] * c[0] * e[2] + 
323                 a[2] * c[0] * e[1] - a[2] * c[1] * e[0];
324
325         // x^1
326         double h = -b[2] * c[1] * e[0] + b[1] * c[2] * e[0] - a[2] * d[1] * e[0] +
327                 a[1] * d[2] * e[0] + b[2] * c[0] * e[1] - b[0] * c[2] * e[1] +
328                 a[2] * d[0] * e[1] - a[0] * d[2] * e[1] - b[1] * c[0] * e[2] +
329                 b[0] * c[1] * e[2] - a[1] * d[0] * e[2] + a[0] * d[1] * e[2] -
330                 a[2] * c[1] * f[0] + a[1] * c[2] * f[0] + a[2] * c[0] * f[1] -
331                 a[0] * c[2] * f[1] - a[1] * c[0] * f[2] + a[0] * c[1] * f[2];
332
333         // x^2
334         double i = -b[2] * d[1] * e[0] + b[1] * d[2] * e[0] +
335                 b[2] * d[0] * e[1] - b[0] * d[2] * e[1] -
336                 b[1] * d[0] * e[2] + b[0] * d[1] * e[2] -
337                 b[2] * c[1] * f[0] + b[1] * c[2] * f[0] -
338                 a[2] * d[1] * f[0] + a[1] * d[2] * f[0] +
339                 b[2] * c[0] * f[1] - b[0] * c[2] * f[1] + 
340                 a[2] * d[0] * f[1] - a[0] * d[2] * f[1] -
341                 b[1] * c[0] * f[2] + b[0] * c[1] * f[2] -
342                 a[1] * d[0] * f[2] + a[0] * d[1] * f[2];
343
344         // x^3 - checked
345         double j = -b[2] * d[1] * f[0] + b[1] * d[2] * f[0] +
346                 b[2] * d[0] * f[1] - b[0] * d[2] * f[1] -
347                 b[1] * d[0] * f[2] + b[0] * d[1] * f[2];
348
349         /*
350         printf("r1: %lf\n", a[0] * c[1] * e[2] - a[0] * c[2] * e[1]);
351         printf("r2: %lf\n", a[1] * c[2] * e[0] - a[1] * c[0] * e[2]);
352         printf("r3: %lf\n", a[2] * c[0] * e[1] - a[2] * c[1] * e[0]);
353
354         printf("x1 x: %f, y: %f, z: %f\n", a[0], a[1], a[2]);
355         printf("x2 x: %f, y: %f, z: %f\n", c[0], c[1], c[2]);
356         printf("x3 x: %f, y: %f, z: %f\n", e[0], e[1], e[2]);
357
358         printf("v1 x: %f, y: %f, z: %f\n", b[0], b[1], b[2]);
359         printf("v2 x: %f, y: %f, z: %f\n", d[0], d[1], d[2]);
360         printf("v3 x: %f, y: %f, z: %f\n", f[0], f[1], f[2]);
361
362         printf("t^3: %lf, t^2: %lf, t^1: %lf, t^0: %lf\n", j, i, h, g);
363         
364 */
365         // Solve cubic equation to determine times t1, t2, t3, when the collision will occur.
366         if ( ABS ( j ) > DBL_EPSILON )
367         {
368                 i /= j;
369                 h /= j;
370                 g /= j;
371                 num_sols = gsl_poly_solve_cubic ( i, h, g, &solution[0], &solution[1], &solution[2] );
372         }
373         else
374         {
375                 num_sols = gsl_poly_solve_quadratic ( i, h, g, &solution[0], &solution[1] );
376                 solution[2] = -1.0;
377         }
378
379         // printf("num_sols: %d, sol1: %lf, sol2: %lf, sol3: %lf\n", num_sols, solution[0],  solution[1],  solution[2]);
380
381         // Discard negative solutions
382         if ( ( num_sols >= 1 ) && ( solution[0] < DBL_EPSILON ) )
383         {
384                 --num_sols;
385                 solution[0] = solution[num_sols];
386         }
387         if ( ( num_sols >= 2 ) && ( solution[1] < DBL_EPSILON ) )
388         {
389                 --num_sols;
390                 solution[1] = solution[num_sols];
391         }
392         if ( ( num_sols == 3 ) && ( solution[2] < DBL_EPSILON ) )
393         {
394                 --num_sols;
395         }
396
397         // Sort
398         if ( num_sols == 2 )
399         {
400                 if ( solution[0] > solution[1] )
401                 {
402                         double tmp = solution[0];
403                         solution[0] = solution[1];
404                         solution[1] = tmp;
405                 }
406         }
407         else if ( num_sols == 3 )
408         {
409
410                 // Bubblesort
411                 if ( solution[0] > solution[1] )
412                 {
413                         double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
414                 }
415                 if ( solution[1] > solution[2] )
416                 {
417                         double tmp = solution[1]; solution[1] = solution[2]; solution[2] = tmp;
418                 }
419                 if ( solution[0] > solution[1] )
420                 {
421                         double tmp = solution[0]; solution[0] = solution[1]; solution[1] = tmp;
422                 }
423         }
424
425         return num_sols;
426 }
427
428
429 // w3 is not perfect
430 static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3], float p3[3], float *w1, float *w2, float *w3 )
431 {
432         double  tempV1[3], tempV2[3], tempV4[3];
433         double  a,b,c,d,e,f;
434
435         VECSUB ( tempV1, p1, p3 );
436         VECSUB ( tempV2, p2, p3 );
437         VECSUB ( tempV4, pv, p3 );
438
439         a = INPR ( tempV1, tempV1 );
440         b = INPR ( tempV1, tempV2 );
441         c = INPR ( tempV2, tempV2 );
442         e = INPR ( tempV1, tempV4 );
443         f = INPR ( tempV2, tempV4 );
444
445         d = ( a * c - b * b );
446
447         if ( ABS ( d ) < ALMOST_ZERO )
448         {
449                 *w1 = *w2 = *w3 = 1.0 / 3.0;
450                 return;
451         }
452
453         w1[0] = ( float ) ( ( e * c - b * f ) / d );
454
455         if ( w1[0] < 0 )
456                 w1[0] = 0;
457
458         w2[0] = ( float ) ( ( f - b * ( double ) w1[0] ) / c );
459
460         if ( w2[0] < 0 )
461                 w2[0] = 0;
462
463         w3[0] = 1.0f - w1[0] - w2[0];
464 }
465
466 DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 )
467 {
468         to[0] = to[1] = to[2] = 0;
469         VECADDMUL ( to, v1, w1 );
470         VECADDMUL ( to, v2, w2 );
471         VECADDMUL ( to, v3, w3 );
472 }
473
474
475 int cloth_collision_response_static ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
476 {
477         int result = 0;
478         Cloth *cloth1;
479         float w1, w2, w3, u1, u2, u3;
480         float v1[3], v2[3], relativeVelocity[3];
481         float magrelVel;
482         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
483
484         cloth1 = clmd->clothObject;
485
486         for ( ; collpair != collision_end; collpair++ )
487         {
488                 // only handle static collisions here
489                 if ( collpair->flag & COLLISION_IN_FUTURE )
490                         continue;
491
492                 // compute barycentric coordinates for both collision points
493                 collision_compute_barycentric ( collpair->pa,
494                         cloth1->verts[collpair->ap1].txold,
495                         cloth1->verts[collpair->ap2].txold,
496                         cloth1->verts[collpair->ap3].txold,
497                         &w1, &w2, &w3 );
498
499                 // was: txold
500                 collision_compute_barycentric ( collpair->pb,
501                         collmd->current_x[collpair->bp1].co,
502                         collmd->current_x[collpair->bp2].co,
503                         collmd->current_x[collpair->bp3].co,
504                         &u1, &u2, &u3 );
505
506                 // Calculate relative "velocity".
507                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
508
509                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
510
511                 VECSUB ( relativeVelocity, v2, v1 );
512
513                 // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
514                 magrelVel = INPR ( relativeVelocity, collpair->normal );
515
516                 // printf("magrelVel: %f\n", magrelVel);
517
518                 // Calculate masses of points.
519                 // TODO
520
521                 // If v_n_mag < 0 the edges are approaching each other.
522                 if ( magrelVel > ALMOST_ZERO )
523                 {
524                         // Calculate Impulse magnitude to stop all motion in normal direction.
525                         float magtangent = 0, repulse = 0, d = 0;
526                         double impulse = 0.0;
527                         float vrel_t_pre[3];
528                         float temp[3];
529
530                         // calculate tangential velocity
531                         VECCOPY ( temp, collpair->normal );
532                         VecMulf ( temp, magrelVel );
533                         VECSUB ( vrel_t_pre, relativeVelocity, temp );
534
535                         // Decrease in magnitude of relative tangential velocity due to coulomb friction
536                         // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
537                         magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
538
539                         // Apply friction impulse.
540                         if ( magtangent > ALMOST_ZERO )
541                         {
542                                 Normalize ( vrel_t_pre );
543
544                                 impulse = magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // 2.0 * 
545                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
546                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
547                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
548                         }
549
550                         // Apply velocity stopping impulse
551                         // I_c = m * v_N / 2.0
552                         // no 2.0 * magrelVel normally, but looks nicer DG
553                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
554
555                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
556                         cloth1->verts[collpair->ap1].impulse_count++;
557
558                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
559                         cloth1->verts[collpair->ap2].impulse_count++;
560
561                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
562                         cloth1->verts[collpair->ap3].impulse_count++;
563
564                         // Apply repulse impulse if distance too short
565                         // I_r = -min(dt*kd, m(0,1d/dt - v_n))
566                         d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
567                         if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
568                         {
569                                 repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
570
571                                 // stay on the safe side and clamp repulse
572                                 if ( impulse > ALMOST_ZERO )
573                                         repulse = MIN2 ( repulse, 5.0*impulse );
574                                 repulse = MAX2 ( impulse, repulse );
575
576                                 impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
577                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal,  impulse );
578                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal,  impulse );
579                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal,  impulse );
580                         }
581
582                         result = 1;
583                 }
584         }
585         return result;
586 }
587
588 //Determines collisions on overlap, collisions are writen to collpair[i] and collision+number_collision_found is returned
589 CollPair* cloth_collision ( ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair )
590 {
591         ClothModifierData *clmd = ( ClothModifierData * ) md1;
592         CollisionModifierData *collmd = ( CollisionModifierData * ) md2;
593         MFace *face1=NULL, *face2 = NULL;
594 #ifdef USE_BULLET
595         ClothVertex *verts1 = clmd->clothObject->verts;
596 #endif
597         double distance = 0;
598         float epsilon1 = clmd->coll_parms->epsilon;
599         float epsilon2 = BLI_bvhtree_getepsilon ( collmd->bvhtree );
600         int i;
601
602         face1 = & ( clmd->clothObject->mfaces[overlap->indexA] );
603         face2 = & ( collmd->mfaces[overlap->indexB] );
604
605         // check all 4 possible collisions
606         for ( i = 0; i < 4; i++ )
607         {
608                 if ( i == 0 )
609                 {
610                         // fill faceA
611                         collpair->ap1 = face1->v1;
612                         collpair->ap2 = face1->v2;
613                         collpair->ap3 = face1->v3;
614
615                         // fill faceB
616                         collpair->bp1 = face2->v1;
617                         collpair->bp2 = face2->v2;
618                         collpair->bp3 = face2->v3;
619                 }
620                 else if ( i == 1 )
621                 {
622                         if ( face1->v4 )
623                         {
624                                 // fill faceA
625                                 collpair->ap1 = face1->v1;
626                                 collpair->ap2 = face1->v4;
627                                 collpair->ap3 = face1->v3;
628
629                                 // fill faceB
630                                 collpair->bp1 = face2->v1;
631                                 collpair->bp2 = face2->v2;
632                                 collpair->bp3 = face2->v3;
633                         }
634                         else
635                                 i++;
636                 }
637                 if ( i == 2 )
638                 {
639                         if ( face2->v4 )
640                         {
641                                 // fill faceA
642                                 collpair->ap1 = face1->v1;
643                                 collpair->ap2 = face1->v2;
644                                 collpair->ap3 = face1->v3;
645
646                                 // fill faceB
647                                 collpair->bp1 = face2->v1;
648                                 collpair->bp2 = face2->v4;
649                                 collpair->bp3 = face2->v3;
650                         }
651                         else
652                                 break;
653                 }
654                 else if ( i == 3 )
655                 {
656                         if ( face1->v4 && face2->v4 )
657                         {
658                                 // fill faceA
659                                 collpair->ap1 = face1->v1;
660                                 collpair->ap2 = face1->v4;
661                                 collpair->ap3 = face1->v3;
662
663                                 // fill faceB
664                                 collpair->bp1 = face2->v1;
665                                 collpair->bp2 = face2->v4;
666                                 collpair->bp3 = face2->v3;
667                         }
668                         else
669                                 break;
670                 }
671
672 #ifdef USE_BULLET
673                 // calc distance + normal
674                 distance = plNearestPoints (
675                         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 );
676 #else
677                 // just be sure that we don't add anything
678                 distance = 2.0 * ( epsilon1 + epsilon2 + ALMOST_ZERO );
679 #endif
680
681                 if ( distance <= ( epsilon1 + epsilon2 + ALMOST_ZERO ) )
682                 {
683                         VECCOPY ( collpair->normal, collpair->vector );
684                         Normalize ( collpair->normal );
685
686                         collpair->distance = distance;
687                         collpair->flag = 0;
688                         collpair++;
689                 }/*
690                 else
691                 {
692                         float w1, w2, w3, u1, u2, u3;
693                         float v1[3], v2[3], relativeVelocity[3];
694
695                         // calc relative velocity
696                         
697                         // compute barycentric coordinates for both collision points
698                         collision_compute_barycentric ( collpair->pa,
699                         verts1[collpair->ap1].txold,
700                         verts1[collpair->ap2].txold,
701                         verts1[collpair->ap3].txold,
702                         &w1, &w2, &w3 );
703
704                         // was: txold
705                         collision_compute_barycentric ( collpair->pb,
706                         collmd->current_x[collpair->bp1].co,
707                         collmd->current_x[collpair->bp2].co,
708                         collmd->current_x[collpair->bp3].co,
709                         &u1, &u2, &u3 );
710
711                         // Calculate relative "velocity".
712                         collision_interpolateOnTriangle ( v1, verts1[collpair->ap1].tv, verts1[collpair->ap2].tv, verts1[collpair->ap3].tv, w1, w2, w3 );
713
714                         collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
715
716                         VECSUB ( relativeVelocity, v2, v1 );
717
718                         if(sqrt(INPR(relativeVelocity, relativeVelocity)) >= distance)
719                         {
720                                 // check for collision in the future
721                                 collpair->flag |= COLLISION_IN_FUTURE;
722                                 collpair++;
723                         }
724                 }*/
725         }
726         return collpair;
727 }
728
729 static int cloth_collision_response_moving( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
730 {
731         int result = 0;
732         Cloth *cloth1;
733         float w1, w2, w3, u1, u2, u3;
734         float v1[3], v2[3], relativeVelocity[3];
735         float magrelVel;
736
737         cloth1 = clmd->clothObject;
738
739         for ( ; collpair != collision_end; collpair++ )
740         {
741                 // compute barycentric coordinates for both collision points
742                 collision_compute_barycentric ( collpair->pa,
743                         cloth1->verts[collpair->ap1].txold,
744                         cloth1->verts[collpair->ap2].txold,
745                         cloth1->verts[collpair->ap3].txold,
746                         &w1, &w2, &w3 );
747
748                 // was: txold
749                 collision_compute_barycentric ( collpair->pb,
750                         collmd->current_x[collpair->bp1].co,
751                         collmd->current_x[collpair->bp2].co,
752                         collmd->current_x[collpair->bp3].co,
753                         &u1, &u2, &u3 );
754
755                 // Calculate relative "velocity".
756                 collision_interpolateOnTriangle ( v1, cloth1->verts[collpair->ap1].tv, cloth1->verts[collpair->ap2].tv, cloth1->verts[collpair->ap3].tv, w1, w2, w3 );
757
758                 collision_interpolateOnTriangle ( v2, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3 );
759
760                 VECSUB ( relativeVelocity, v2, v1 );
761
762                 // Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal').
763                 magrelVel = INPR ( relativeVelocity, collpair->normal );
764
765                 // printf("magrelVel: %f\n", magrelVel);
766
767                 // Calculate masses of points.
768                 // TODO
769
770                 // If v_n_mag < 0 the edges are approaching each other.
771                 if ( magrelVel > ALMOST_ZERO )
772                 {
773                         // Calculate Impulse magnitude to stop all motion in normal direction.
774                         float magtangent = 0;
775                         double impulse = 0.0;
776                         float vrel_t_pre[3];
777                         float temp[3];
778
779                         // calculate tangential velocity
780                         VECCOPY ( temp, collpair->normal );
781                         VecMulf ( temp, magrelVel );
782                         VECSUB ( vrel_t_pre, relativeVelocity, temp );
783
784                         // Decrease in magnitude of relative tangential velocity due to coulomb friction
785                         // in original formula "magrelVel" should be the "change of relative velocity in normal direction"
786                         magtangent = MIN2 ( clmd->coll_parms->friction * 0.01 * magrelVel,sqrt ( INPR ( vrel_t_pre,vrel_t_pre ) ) );
787
788                         // Apply friction impulse.
789                         if ( magtangent > ALMOST_ZERO )
790                         {
791                                 Normalize ( vrel_t_pre );
792
793                                 impulse = 2.0 * magtangent / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
794                                 VECADDMUL ( cloth1->verts[collpair->ap1].impulse, vrel_t_pre, w1 * impulse );
795                                 VECADDMUL ( cloth1->verts[collpair->ap2].impulse, vrel_t_pre, w2 * impulse );
796                                 VECADDMUL ( cloth1->verts[collpair->ap3].impulse, vrel_t_pre, w3 * impulse );
797                         }
798
799                         // Apply velocity stopping impulse
800                         // I_c = m * v_N / 2.0
801                         // no 2.0 * magrelVel normally, but looks nicer DG
802                         impulse =  magrelVel / ( 1.0 + w1*w1 + w2*w2 + w3*w3 );
803
804                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal, w1 * impulse );
805                         cloth1->verts[collpair->ap1].impulse_count++;
806
807                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal, w2 * impulse );
808                         cloth1->verts[collpair->ap2].impulse_count++;
809
810                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal, w3 * impulse );
811                         cloth1->verts[collpair->ap3].impulse_count++;
812
813                         // Apply repulse impulse if distance too short
814                         // I_r = -min(dt*kd, m(0,1d/dt - v_n))
815                         /*
816                         d = clmd->coll_parms->epsilon*8.0/9.0 + epsilon2*8.0/9.0 - collpair->distance;
817                         if ( ( magrelVel < 0.1*d*clmd->sim_parms->stepsPerFrame ) && ( d > ALMOST_ZERO ) )
818                         {
819                         repulse = MIN2 ( d*1.0/clmd->sim_parms->stepsPerFrame, 0.1*d*clmd->sim_parms->stepsPerFrame - magrelVel );
820
821                         // stay on the safe side and clamp repulse
822                         if ( impulse > ALMOST_ZERO )
823                         repulse = MIN2 ( repulse, 5.0*impulse );
824                         repulse = MAX2 ( impulse, repulse );
825
826                         impulse = repulse / ( 1.0 + w1*w1 + w2*w2 + w3*w3 ); // original 2.0 / 0.25
827                         VECADDMUL ( cloth1->verts[collpair->ap1].impulse, collpair->normal,  impulse );
828                         VECADDMUL ( cloth1->verts[collpair->ap2].impulse, collpair->normal,  impulse );
829                         VECADDMUL ( cloth1->verts[collpair->ap3].impulse, collpair->normal,  impulse );
830                         }
831                         */
832                         result = 1;
833                 }
834         }
835         return result;
836 }
837
838 static float projectPointOntoLine(float *p, float *a, float *b) 
839 {
840    float ba[3], pa[3];
841    VECSUB(ba, b, a);
842    VECSUB(pa, p, a);
843    return INPR(pa, ba) / INPR(ba, ba);
844 }
845
846 static void calculateEENormal(float *np1, float *np2, float *np3, float *np4,float *out_normal) 
847 {
848         float line1[3], line2[3];
849         float length;
850
851         VECSUB(line1, np2, np1);
852         VECSUB(line2, np3, np1);
853
854         // printf("l1: %f, l1: %f, l2: %f, l2: %f\n", line1[0], line1[1], line2[0], line2[1]);
855
856         Crossf(out_normal, line1, line2);
857
858         
859
860         length = Normalize(out_normal);
861         if (length <= FLT_EPSILON)
862         { // lines are collinear
863                 VECSUB(out_normal, np2, np1);
864                 Normalize(out_normal);
865         }
866 }
867
868 static void findClosestPointsEE(float *x1, float *x2, float *x3, float *x4, float *w1, float *w2)
869 {
870         float temp[3], temp2[3];
871         
872         double a, b, c, e, f; 
873
874         VECSUB(temp, x2, x1);
875         a = INPR(temp, temp);
876
877         VECSUB(temp2, x4, x3);
878         b = -INPR(temp, temp2);
879
880         c = INPR(temp2, temp2);
881
882         VECSUB(temp2, x3, x1);
883         e = INPR(temp, temp2);
884
885         VECSUB(temp, x4, x3);
886         f = -INPR(temp, temp2);
887
888         *w1 = (e * c - b * f) / (a * c - b * b);
889         *w2 = (f - b * *w1) / c;
890
891 }
892
893 // calculates the distance of 2 edges
894 static float edgedge_distance(float np11[3], float np12[3], float np21[3], float np22[3], float *out_a1, float *out_a2, float *out_normal)
895 {
896         float line1[3], line2[3], cross[3];
897         float length;
898         float temp[3], temp2[3];
899         float dist_a1, dist_a2;
900         
901         VECSUB(line1, np12, np11);
902         VECSUB(line2, np22, np21);
903
904         Crossf(cross, line1, line2);
905         length = INPR(cross, cross);
906
907         if (length < FLT_EPSILON) 
908         {
909                 *out_a2 = projectPointOntoLine(np11, np21, np22);
910                 if ((*out_a2 >= -FLT_EPSILON) && (*out_a2 <= 1.0 + FLT_EPSILON)) 
911                 {
912                         *out_a1 = 0;
913                         calculateEENormal(np11, np12, np21, np22, out_normal);
914                         VECSUB(temp, np22, np21);
915                         VecMulf(temp, *out_a2);
916                         VECADD(temp2, temp, np21);
917                         VECADD(temp2, temp2, np11);
918                         return INPR(temp2, temp2);
919                 }
920
921                 CLAMP(*out_a2, 0.0, 1.0);
922                 if (*out_a2 > .5) 
923                 { // == 1.0
924                         *out_a1 = projectPointOntoLine(np22, np11, np12);
925                         if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) 
926                         {
927                                 calculateEENormal(np11, np12, np21, np22, out_normal);
928
929                                 // return (np22 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
930                                 VECSUB(temp, np12, np11);
931                                 VecMulf(temp, *out_a1);
932                                 VECADD(temp2, temp, np11);
933                                 VECSUB(temp2, np22, temp2);
934                                 return INPR(temp2, temp2);
935                         }
936                 } 
937                 else 
938                 { // == 0.0
939                         *out_a1 = projectPointOntoLine(np21, np11, np12);
940                         if ((*out_a1 >= -FLT_EPSILON) && (*out_a1 <= 1.0 + FLT_EPSILON)) 
941                         {
942                                 calculateEENormal(np11, np11, np21, np22, out_normal);
943
944                                 // return (np21 - (np11 + (np12 - np11) * out_a1)).lengthSquared();
945                                 VECSUB(temp, np12, np11);
946                                 VecMulf(temp, *out_a1);
947                                 VECADD(temp2, temp, np11);
948                                 VECSUB(temp2, np21, temp2);
949                                 return INPR(temp2, temp2);
950                         }
951                 }
952
953                 CLAMP(*out_a1, 0.0, 1.0);
954                 calculateEENormal(np11, np12, np21, np22, out_normal);
955                 if(*out_a1 > .5)
956                 {
957                         if(*out_a2 > .5)
958                         {
959                                 VECSUB(temp, np12, np22);
960                         }
961                         else
962                         {
963                                 VECSUB(temp, np12, np21);
964                         }
965                 }
966                 else
967                 {
968                         if(*out_a2 > .5)
969                         {
970                                 VECSUB(temp, np11, np22);
971                         }
972                         else
973                         {
974                                 VECSUB(temp, np11, np21);
975                         }
976                 }
977
978                 return INPR(temp, temp);
979         }
980         else
981         {
982                 
983                 // If the lines aren't parallel (but coplanar) they have to intersect
984
985                 findClosestPointsEE(np11, np12, np21, np22, out_a1, out_a2);
986
987                 // If both points are on the finite edges, we're done.
988                 if (*out_a1 >= 0.0 && *out_a1 <= 1.0 && *out_a2 >= 0.0 && *out_a2 <= 1.0) 
989                 {
990                         float p1[3], p2[3];
991                         
992                         // p1= np11 + (np12 - np11) * out_a1;
993                         VECSUB(temp, np12, np11);
994                         VecMulf(temp, *out_a1);
995                         VECADD(p1, np11, temp);
996                         
997                         // p2 = np21 + (np22 - np21) * out_a2;
998                         VECSUB(temp, np22, np21);
999                         VecMulf(temp, *out_a2);
1000                         VECADD(p2, np21, temp);
1001
1002                         calculateEENormal(np11, np12, np21, np22, out_normal);
1003                         VECSUB(temp, p1, p2);
1004                         return INPR(temp, temp);
1005                 }
1006
1007                 
1008                 /*
1009                 * Clamp both points to the finite edges.
1010                 * The one that moves most during clamping is one part of the solution.
1011                 */
1012                 dist_a1 = *out_a1;
1013                 CLAMP(dist_a1, 0.0, 1.0);
1014                 dist_a2 = *out_a2;
1015                 CLAMP(dist_a2, 0.0, 1.0);
1016
1017                 // Now project the "most clamped" point on the other line.
1018                 if (dist_a1 > dist_a2) 
1019                 { 
1020                         /* keep out_a1 */
1021                         float p1[3];
1022
1023                         // p1 = np11 + (np12 - np11) * out_a1;
1024                         VECSUB(temp, np12, np11);
1025                         VecMulf(temp, *out_a1);
1026                         VECADD(p1, np11, temp);
1027
1028                         *out_a2 = projectPointOntoLine(p1, np21, np22);
1029                         CLAMP(*out_a2, 0.0, 1.0);
1030
1031                         calculateEENormal(np11, np12, np21, np22, out_normal);
1032
1033                         // return (p1 - (np21 + (np22 - np21) * out_a2)).lengthSquared();
1034                         VECSUB(temp, np22, np21);
1035                         VecMulf(temp, *out_a2);
1036                         VECADD(temp, temp, np21);
1037                         VECSUB(temp, p1, temp);
1038                         return INPR(temp, temp);
1039                 } 
1040                 else 
1041                 {       
1042                         /* keep out_a2 */
1043                         float p2[3];
1044                         
1045                         // p2 = np21 + (np22 - np21) * out_a2;
1046                         VECSUB(temp, np22, np21);
1047                         VecMulf(temp, *out_a2);
1048                         VECADD(p2, np21, temp);
1049
1050                         *out_a1 = projectPointOntoLine(p2, np11, np12);
1051                         CLAMP(*out_a1, 0.0, 1.0);
1052
1053                         calculateEENormal(np11, np12, np21, np22, out_normal);
1054                         
1055                         // return ((np11 + (np12 - np11) * out_a1) - p2).lengthSquared();
1056                         VECSUB(temp, np12, np11);
1057                         VecMulf(temp, *out_a1);
1058                         VECADD(temp, temp, np11);
1059                         VECSUB(temp, temp, p2);
1060                         return INPR(temp, temp);
1061                 }
1062         }
1063         
1064         printf("Error in edgedge_distance: end of function\n");
1065         return 0;
1066 }
1067
1068 static int cloth_collision_moving_edges ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair )
1069 {
1070         EdgeCollPair edgecollpair;
1071         Cloth *cloth1=NULL;
1072         ClothVertex *verts1=NULL;
1073         unsigned int i = 0, k = 0;
1074         int numsolutions = 0;
1075         double x1[3], v1[3], x2[3], v2[3], x3[3], v3[3];
1076         double solution[3], solution2[3];
1077         MVert *verts2 = collmd->current_x; // old x
1078         MVert *velocity2 = collmd->current_v; // velocity
1079         float distance = 0;
1080         float triA[3][3], triB[3][3];
1081         int result = 0;
1082
1083         cloth1 = clmd->clothObject;
1084         verts1 = cloth1->verts;
1085
1086         for(i = 0; i < 9; i++)
1087         {
1088                 // 9 edge - edge possibilities
1089
1090                 if(i == 0) // cloth edge: 1-2; coll edge: 1-2
1091                 {
1092                         edgecollpair.p11 = collpair->ap1;
1093                         edgecollpair.p12 = collpair->ap2;
1094
1095                         edgecollpair.p21 = collpair->bp1;
1096                         edgecollpair.p22 = collpair->bp2;
1097                 }
1098                 else if(i == 1) // cloth edge: 1-2; coll edge: 2-3
1099                 {
1100                         edgecollpair.p11 = collpair->ap1;
1101                         edgecollpair.p12 = collpair->ap2;
1102
1103                         edgecollpair.p21 = collpair->bp2;
1104                         edgecollpair.p22 = collpair->bp3;
1105                 }
1106                 else if(i == 2) // cloth edge: 1-2; coll edge: 1-3
1107                 {
1108                         edgecollpair.p11 = collpair->ap1;
1109                         edgecollpair.p12 = collpair->ap2;
1110
1111                         edgecollpair.p21 = collpair->bp1;
1112                         edgecollpair.p22 = collpair->bp3;
1113                 }
1114                 else if(i == 3) // cloth edge: 2-3; coll edge: 1-2
1115                 {
1116                         edgecollpair.p11 = collpair->ap2;
1117                         edgecollpair.p12 = collpair->ap3;
1118
1119                         edgecollpair.p21 = collpair->bp1;
1120                         edgecollpair.p22 = collpair->bp2;
1121                 }
1122                 else if(i == 4) // cloth edge: 2-3; coll edge: 2-3
1123                 {
1124                         edgecollpair.p11 = collpair->ap2;
1125                         edgecollpair.p12 = collpair->ap3;
1126
1127                         edgecollpair.p21 = collpair->bp2;
1128                         edgecollpair.p22 = collpair->bp3;
1129                 }
1130                 else if(i == 5) // cloth edge: 2-3; coll edge: 1-3
1131                 {
1132                         edgecollpair.p11 = collpair->ap2;
1133                         edgecollpair.p12 = collpair->ap3;
1134
1135                         edgecollpair.p21 = collpair->bp1;
1136                         edgecollpair.p22 = collpair->bp3;
1137                 }
1138                 else if(i ==6) // cloth edge: 1-3; coll edge: 1-2
1139                 {
1140                         edgecollpair.p11 = collpair->ap1;
1141                         edgecollpair.p12 = collpair->ap3;
1142
1143                         edgecollpair.p21 = collpair->bp1;
1144                         edgecollpair.p22 = collpair->bp2;
1145                 }
1146                 else if(i ==7) // cloth edge: 1-3; coll edge: 2-3
1147                 {
1148                         edgecollpair.p11 = collpair->ap1;
1149                         edgecollpair.p12 = collpair->ap3;
1150
1151                         edgecollpair.p21 = collpair->bp2;
1152                         edgecollpair.p22 = collpair->bp3;
1153                 }
1154                 else if(i == 8) // cloth edge: 1-3; coll edge: 1-3
1155                 {
1156                         edgecollpair.p11 = collpair->ap1;
1157                         edgecollpair.p12 = collpair->ap3;
1158
1159                         edgecollpair.p21 = collpair->bp1;
1160                         edgecollpair.p22 = collpair->bp3;
1161                 }
1162                 /*
1163                 if((edgecollpair.p11 == 3) && (edgecollpair.p12 == 16))
1164                         printf("Ahier!\n");
1165                 if((edgecollpair.p11 == 16) && (edgecollpair.p12 == 3))
1166                         printf("Ahier!\n");
1167                 */
1168
1169                 // if ( !cloth_are_edges_adjacent ( clmd, collmd, &edgecollpair ) )
1170                 {
1171                         // always put coll points in p21/p22
1172                         VECSUB ( x1, verts1[edgecollpair.p12].txold, verts1[edgecollpair.p11].txold );
1173                         VECSUB ( v1, verts1[edgecollpair.p12].tv, verts1[edgecollpair.p11].tv );
1174
1175                         VECSUB ( x2, verts2[edgecollpair.p21].co, verts1[edgecollpair.p11].txold );
1176                         VECSUB ( v2, velocity2[edgecollpair.p21].co, verts1[edgecollpair.p11].tv );
1177
1178                         VECSUB ( x3, verts2[edgecollpair.p22].co, verts1[edgecollpair.p11].txold );
1179                         VECSUB ( v3, velocity2[edgecollpair.p22].co, verts1[edgecollpair.p11].tv );
1180
1181                         numsolutions = cloth_get_collision_time ( x1, v1, x2, v2, x3, v3, solution );
1182
1183                         if((edgecollpair.p11 == 3 && edgecollpair.p12==16)|| (edgecollpair.p11==16 && edgecollpair.p12==3))
1184                         {
1185                                 if(edgecollpair.p21==6 || edgecollpair.p22 == 6)
1186                                 {
1187                                         printf("dist: %f, sol[k]: %lf, sol2[k]: %lf\n", distance, solution[k], solution2[k]);
1188                                         printf("a1: %f, a2: %f, b1: %f, b2: %f\n", x1[0], x2[0], x3[0], v1[0]);
1189                                         printf("b21: %d, b22: %d\n", edgecollpair.p21, edgecollpair.p22);
1190                                 }
1191                         }
1192
1193                         for ( k = 0; k < numsolutions; k++ )
1194                         {
1195                                 // printf("sol %d: %lf\n", k, solution[k]);
1196                                 if ( ( solution[k] >= ALMOST_ZERO ) && ( solution[k] <= 1.0 ) && ( solution[k] >  ALMOST_ZERO))
1197                                 {
1198                                         float a,b;
1199                                         float out_normal[3];
1200                                         float distance;
1201                                         float impulse = 0;
1202                                         float I_mag;
1203
1204                                         // move verts
1205                                         VECADDS(triA[0], verts1[edgecollpair.p11].txold, verts1[edgecollpair.p11].tv, solution[k]);
1206                                         VECADDS(triA[1], verts1[edgecollpair.p12].txold, verts1[edgecollpair.p12].tv, solution[k]);
1207
1208                                         VECADDS(triB[0], collmd->current_x[edgecollpair.p21].co, collmd->current_v[edgecollpair.p21].co, solution[k]);
1209                                         VECADDS(triB[1], collmd->current_x[edgecollpair.p22].co, collmd->current_v[edgecollpair.p22].co, solution[k]);
1210
1211                                         // TODO: check for collisions
1212                                         distance = edgedge_distance(triA[0], triA[1], triB[0], triB[1], &a, &b, out_normal);
1213                                         
1214                                         if ((distance <= clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree ) + ALMOST_ZERO) && (INPR(out_normal, out_normal) > 0))
1215                                         {
1216                                                 float vrel_1_to_2[3], temp[3], temp2[3], out_normalVelocity;
1217                                                 float desiredVn;
1218
1219                                                 VECCOPY(vrel_1_to_2, verts1[edgecollpair.p11].tv);
1220                                                 VecMulf(vrel_1_to_2, 1.0 - a);
1221                                                 VECCOPY(temp, verts1[edgecollpair.p12].tv);
1222                                                 VecMulf(temp, a);
1223
1224                                                 VECADD(vrel_1_to_2, vrel_1_to_2, temp);
1225
1226                                                 VECCOPY(temp, verts1[edgecollpair.p21].tv);
1227                                                 VecMulf(temp, 1.0 - b);
1228                                                 VECCOPY(temp2, verts1[edgecollpair.p22].tv);
1229                                                 VecMulf(temp2, b);
1230                                                 VECADD(temp, temp, temp2);
1231
1232                                                 VECSUB(vrel_1_to_2, vrel_1_to_2, temp);
1233
1234                                                 out_normalVelocity = INPR(vrel_1_to_2, out_normal);
1235 /*
1236                                                 // this correction results in wrong normals sometimes?
1237                                                 if(out_normalVelocity < 0.0)
1238                                                 {
1239                                                         out_normalVelocity*= -1.0;
1240                                                         VecNegf(out_normal);
1241                                                 }
1242 */
1243                                                 /* Inelastic repulsion impulse. */
1244
1245                                                 // Calculate which normal velocity we need. 
1246                                                 desiredVn = (out_normalVelocity * (float)solution[k] - (.1 * (clmd->coll_parms->epsilon + BLI_bvhtree_getepsilon ( collmd->bvhtree )) - sqrt(distance)) - ALMOST_ZERO);
1247
1248                                                 // Now calculate what impulse we need to reach that velocity. 
1249                                                 I_mag = (out_normalVelocity - desiredVn) / 2.0; // / (1/m1 + 1/m2);
1250
1251                                                 // Finally apply that impulse. 
1252                                                 impulse = (2.0 * -I_mag) / (a*a + (1.0-a)*(1.0-a) + b*b + (1.0-b)*(1.0-b));
1253
1254                                                 VECADDMUL ( verts1[edgecollpair.p11].impulse, out_normal, (1.0-a) * impulse );
1255                                                 verts1[edgecollpair.p11].impulse_count++;
1256
1257                                                 VECADDMUL ( verts1[edgecollpair.p12].impulse, out_normal, a * impulse );
1258                                                 verts1[edgecollpair.p12].impulse_count++;
1259
1260                                                 // return true;
1261                                                 result = 1;
1262                                                 break;
1263                                         }
1264                                         else
1265                                         {
1266                                                 // missing from collision.hpp
1267                                         }
1268                                         // mintime = MIN2(mintime, (float)solution[k]);
1269
1270                                         break;
1271                                 }
1272                         }
1273                 }
1274         }
1275         return result;
1276 }
1277
1278 static int cloth_collision_moving ( ClothModifierData *clmd, CollisionModifierData *collmd, CollPair *collpair, CollPair *collision_end )
1279 {
1280         Cloth *cloth1;
1281         cloth1 = clmd->clothObject;
1282
1283         for ( ; collpair != collision_end; collpair++ )
1284         {
1285                 // only handle moving collisions here
1286                 if (!( collpair->flag & COLLISION_IN_FUTURE ))
1287                         continue;
1288
1289                 cloth_collision_moving_edges ( clmd, collmd, collpair);
1290                 // cloth_collision_moving_tris ( clmd, collmd, collpair);
1291         }
1292
1293         return 1;
1294 }
1295
1296
1297 // return all collision objects in scene
1298 // collision object will exclude self 
1299 Object **get_collisionobjects(Scene *scene, Object *self, int *numcollobj)
1300 {
1301         Base *base=NULL;
1302         Object **objs = NULL;
1303         Object *coll_ob = NULL;
1304         CollisionModifierData *collmd = NULL;
1305         int numobj = 0, maxobj = 100;
1306         
1307         objs = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1308         // check all collision objects
1309         for ( base = scene->base.first; base; base = base->next )
1310         {
1311                 /*Only proceed for mesh object in same layer */
1312                 if(!(base->object->type==OB_MESH && (base->lay & self->lay))) 
1313                         continue;
1314                 
1315                 coll_ob = base->object;
1316                 
1317                 if(coll_ob == self)
1318                                 continue;
1319                 
1320                 if(coll_ob->pd && coll_ob->pd->deflect)
1321                 {
1322                         collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1323                 }
1324                 else
1325                         collmd = NULL;
1326                 
1327                 if ( collmd )
1328                 {       
1329                         if(numobj >= maxobj)
1330                         {
1331                                 // realloc
1332                                 int oldmax = maxobj;
1333                                 Object **tmp;
1334                                 maxobj *= 2;
1335                                 tmp = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1336                                 memcpy(tmp, objs, sizeof(Object *)*oldmax);
1337                                 MEM_freeN(objs);
1338                                 objs = tmp;
1339                                 
1340                         }
1341                         
1342                         objs[numobj] = coll_ob;
1343                         numobj++;
1344                 }
1345                 else
1346                 {
1347                         if ( coll_ob->dup_group )
1348                         {
1349                                 GroupObject *go;
1350                                 Group *group = coll_ob->dup_group;
1351
1352                                 for ( go= group->gobject.first; go; go= go->next )
1353                                 {
1354                                         coll_ob = go->ob;
1355                                         collmd = NULL;
1356                                         
1357                                         if(coll_ob == self)
1358                                                 continue;
1359                                         
1360                                         if(coll_ob->pd && coll_ob->pd->deflect)
1361                                         {
1362                                                 collmd = ( CollisionModifierData * ) modifiers_findByType ( coll_ob, eModifierType_Collision );
1363                                         }
1364                                         else
1365                                                 collmd = NULL;
1366
1367                                         if ( !collmd )
1368                                                 continue;
1369                                         
1370                                         if( !collmd->bvhtree)
1371                                                 continue;
1372
1373                                         if(numobj >= maxobj)
1374                                         {
1375                                                 // realloc
1376                                                 int oldmax = maxobj;
1377                                                 Object **tmp;
1378                                                 maxobj *= 2;
1379                                                 tmp = MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray");
1380                                                 memcpy(tmp, objs, sizeof(Object *)*oldmax);
1381                                                 MEM_freeN(objs);
1382                                                 objs = tmp;
1383                                         }
1384                                         
1385                                         objs[numobj] = coll_ob;
1386                                         numobj++;
1387                                 }
1388                         }
1389                 }       
1390         }
1391         *numcollobj = numobj;
1392         return objs;
1393 }
1394
1395 static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap)
1396 {
1397         int i;
1398         
1399         *collisions = ( CollPair* ) MEM_mallocN ( sizeof ( CollPair ) * numresult * 4, "collision array" ); //*4 since cloth_collision_static can return more than 1 collision
1400         *collisions_index = *collisions;
1401
1402         for ( i = 0; i < numresult; i++ )
1403         {
1404                 *collisions_index = cloth_collision ( ( ModifierData * ) clmd, ( ModifierData * ) collmd, overlap+i, *collisions_index );
1405         }
1406 }
1407
1408 static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, CollisionModifierData *collmd, CollPair *collisions, CollPair *collisions_index)
1409 {
1410         Cloth *cloth = clmd->clothObject;
1411         int i=0, j = 0, numfaces = 0, numverts = 0;
1412         ClothVertex *verts = NULL;
1413         int ret = 0;
1414         int result = 0;
1415         float tnull[3] = {0,0,0};
1416         
1417         numfaces = clmd->clothObject->numfaces;
1418         numverts = clmd->clothObject->numverts;
1419  
1420         verts = cloth->verts;
1421         
1422         // process all collisions (calculate impulses, TODO: also repulses if distance too short)
1423         result = 1;
1424         for ( j = 0; j < 5; j++ ) // 5 is just a value that ensures convergence
1425         {
1426                 result = 0;
1427
1428                 if ( collmd->bvhtree )
1429                 {
1430                         result += cloth_collision_response_static ( clmd, collmd, collisions, collisions_index );
1431
1432                         // apply impulses in parallel
1433                         if ( result )
1434                         {
1435                                 for ( i = 0; i < numverts; i++ )
1436                                 {
1437                                         // calculate "velocities" (just xnew = xold + v; no dt in v)
1438                                         if ( verts[i].impulse_count )
1439                                         {
1440                                                 VECADDMUL ( verts[i].tv, verts[i].impulse, 1.0f / verts[i].impulse_count );
1441                                                 VECCOPY ( verts[i].impulse, tnull );
1442                                                 verts[i].impulse_count = 0;
1443
1444                                                 ret++;
1445                                         }
1446                                 }
1447                         }
1448                 }
1449         }
1450         return ret;
1451 }
1452
1453 // cloth - object collisions
1454 int cloth_bvh_objcollision (Object *ob, ClothModifierData * clmd, float step, float dt )
1455 {
1456         Cloth *cloth=NULL;
1457         BVHTree *cloth_bvh=NULL;
1458         int i=0, numfaces = 0, numverts = 0, k, l, j;
1459         int rounds = 0; // result counts applied collisions; ic is for debug output;
1460         ClothVertex *verts = NULL;
1461         int ret = 0, ret2 = 0;
1462         Object **collobjs = NULL;
1463         int numcollobj = 0;
1464
1465         if ( ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ ) || ! ( ( ( Cloth * ) clmd->clothObject )->bvhtree ) )
1466         {
1467                 return 0;
1468         }
1469
1470         cloth = clmd->clothObject;
1471         verts = cloth->verts;
1472         cloth_bvh = ( BVHTree * ) cloth->bvhtree;
1473         numfaces = clmd->clothObject->numfaces;
1474         numverts = clmd->clothObject->numverts;
1475
1476         ////////////////////////////////////////////////////////////
1477         // static collisions
1478         ////////////////////////////////////////////////////////////
1479
1480         // update cloth bvh
1481         bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function)
1482         bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function)
1483         
1484         collobjs = get_collisionobjects(clmd->scene, ob, &numcollobj);
1485         
1486         if(!collobjs)
1487                 return 0;
1488
1489         do
1490         {
1491                 CollPair **collisions, **collisions_index;
1492                 
1493                 ret2 = 0;
1494
1495                 collisions = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
1496                 collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj , "CollPair");
1497                 
1498                 // check all collision objects
1499                 for(i = 0; i < numcollobj; i++)
1500                 {
1501                         Object *collob= collobjs[i];
1502                         CollisionModifierData *collmd = (CollisionModifierData*)modifiers_findByType(collob, eModifierType_Collision);
1503                         BVHTreeOverlap *overlap = NULL;
1504                         int result = 0;
1505                         
1506                         if(!collmd->bvhtree)
1507                                 continue;
1508                         
1509                         /* move object to position (step) in time */
1510                         collision_move_object ( collmd, step + dt, step );
1511                         
1512                         /* search for overlapping collision pairs */
1513                         overlap = BLI_bvhtree_overlap ( cloth_bvh, collmd->bvhtree, &result );
1514                                 
1515                         // go to next object if no overlap is there
1516                         if(!result || !overlap)
1517                         {
1518                                 if ( overlap )
1519                                         MEM_freeN ( overlap );
1520                                 continue;
1521                         }
1522                         
1523                         /* check if collisions really happen (costly near check) */
1524                         cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap);
1525                         
1526                         // resolve nearby collisions
1527                         ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i],  collisions_index[i]);
1528                         ret2 += ret;
1529                         
1530                         if ( overlap )
1531                                 MEM_freeN ( overlap );
1532                 }
1533                 rounds++;
1534                 
1535                 for(i = 0; i < numcollobj; i++)
1536                 {
1537                         if ( collisions[i] ) MEM_freeN ( collisions[i] );
1538                 }
1539                         
1540                 MEM_freeN(collisions);
1541                 MEM_freeN(collisions_index);
1542
1543                 ////////////////////////////////////////////////////////////
1544                 // update positions
1545                 // this is needed for bvh_calc_DOP_hull_moving() [kdop.c]
1546                 ////////////////////////////////////////////////////////////
1547
1548                 // verts come from clmd
1549                 for ( i = 0; i < numverts; i++ )
1550                 {
1551                         if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1552                         {
1553                                 if ( verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1554                                 {
1555                                         continue;
1556                                 }
1557                         }
1558
1559                         VECADD ( verts[i].tx, verts[i].txold, verts[i].tv );
1560                 }
1561                 ////////////////////////////////////////////////////////////
1562                 
1563                 
1564                 ////////////////////////////////////////////////////////////
1565                 // Test on *simple* selfcollisions
1566                 ////////////////////////////////////////////////////////////
1567                 if ( clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF )
1568                 {
1569                         for(l = 0; l < clmd->coll_parms->self_loop_count; l++)
1570                         {
1571                                 // TODO: add coll quality rounds again
1572                                 BVHTreeOverlap *overlap = NULL;
1573                                 int result = 0;
1574         
1575                                 // collisions = 1;
1576                                 verts = cloth->verts; // needed for openMP
1577         
1578                                 numfaces = clmd->clothObject->numfaces;
1579                                 numverts = clmd->clothObject->numverts;
1580         
1581                                 verts = cloth->verts;
1582         
1583                                 if ( cloth->bvhselftree )
1584                                 {
1585                                         // search for overlapping collision pairs 
1586                                         overlap = BLI_bvhtree_overlap ( cloth->bvhselftree, cloth->bvhselftree, &result );
1587         
1588         // #pragma omp parallel for private(k, i, j) schedule(static)
1589                                         for ( k = 0; k < result; k++ )
1590                                         {
1591                                                 float temp[3];
1592                                                 float length = 0;
1593                                                 float mindistance;
1594         
1595                                                 i = overlap[k].indexA;
1596                                                 j = overlap[k].indexB;
1597         
1598                                                 mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len );
1599         
1600                                                 if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )
1601                                                 {
1602                                                         if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1603                                                                                 && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) )
1604                                                         {
1605                                                                 continue;
1606                                                         }
1607                                                 }
1608         
1609                                                 VECSUB ( temp, verts[i].tx, verts[j].tx );
1610         
1611                                                 if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue;
1612         
1613                                                 // check for adjacent points (i must be smaller j)
1614                                                 if ( BLI_edgehash_haskey ( cloth->edgehash, MIN2(i, j), MAX2(i, j) ) )
1615                                                 {
1616                                                         continue;
1617                                                 }
1618         
1619                                                 length = Normalize ( temp );
1620         
1621                                                 if ( length < mindistance )
1622                                                 {
1623                                                         float correction = mindistance - length;
1624         
1625                                                         if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED )
1626                                                         {
1627                                                                 VecMulf ( temp, -correction );
1628                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
1629                                                         }
1630                                                         else if ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED )
1631                                                         {
1632                                                                 VecMulf ( temp, correction );
1633                                                                 VECADD ( verts[i].tx, verts[i].tx, temp );
1634                                                         }
1635                                                         else
1636                                                         {
1637                                                                 VecMulf ( temp, -correction*0.5 );
1638                                                                 VECADD ( verts[j].tx, verts[j].tx, temp );
1639         
1640                                                                 VECSUB ( verts[i].tx, verts[i].tx, temp );
1641                                                         }
1642                                                         ret = 1;
1643                                                         ret2 += ret;
1644                                                 }
1645                                                 else
1646                                                 {
1647                                                         // check for approximated time collisions
1648                                                 }
1649                                         }
1650         
1651                                         if ( overlap )
1652                                                 MEM_freeN ( overlap );
1653         
1654                                 }
1655                         }
1656                         ////////////////////////////////////////////////////////////
1657
1658                         ////////////////////////////////////////////////////////////
1659                         // SELFCOLLISIONS: update velocities
1660                         ////////////////////////////////////////////////////////////
1661                         if ( ret2 )
1662                         {
1663                                 for ( i = 0; i < cloth->numverts; i++ )
1664                                 {
1665                                         if ( ! ( verts [i].flags & CLOTH_VERT_FLAG_PINNED ) )
1666                                         {
1667                                                 VECSUB ( verts[i].tv, verts[i].tx, verts[i].txold );
1668                                         }
1669                                 }
1670                         }
1671                         ////////////////////////////////////////////////////////////
1672                 }
1673         }
1674         while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) );
1675         
1676         if(collobjs)
1677                 MEM_freeN(collobjs);
1678
1679         return MIN2 ( ret, 1 );
1680 }