Cloth: Add "velocity damping" to damping options. This will help with the "cloth...
[blender.git] / source / blender / blenkernel / intern / implicit.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/implicit.c
29  *  \ingroup bke
30  */
31
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_scene_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_object_force.h"
38 #include "DNA_meshdata_types.h"
39
40 #include "BLI_threads.h"
41 #include "BLI_math.h"
42 #include "BLI_linklist.h"
43 #include "BLI_utildefines.h"
44
45 #include "BKE_cloth.h"
46 #include "BKE_collision.h"
47 #include "BKE_effect.h"
48 #include "BKE_global.h"
49
50
51 #define CLOTH_OPENMP_LIMIT 512
52
53 #ifdef _WIN32
54 #include <windows.h>
55 static LARGE_INTEGER _itstart, _itend;
56 static LARGE_INTEGER ifreq;
57 static void itstart(void)
58 {
59         static int first = 1;
60         if(first) {
61                 QueryPerformanceFrequency(&ifreq);
62                 first = 0;
63         }
64         QueryPerformanceCounter(&_itstart);
65 }
66 static void itend(void)
67 {
68         QueryPerformanceCounter(&_itend);
69 }
70 double itval(void)
71 {
72         return ((double)_itend.QuadPart -
73                         (double)_itstart.QuadPart)/((double)ifreq.QuadPart);
74 }
75 #else
76 #include <sys/time.h>
77 // intrinsics need better compile flag checking
78 // #include <xmmintrin.h>
79 // #include <pmmintrin.h>
80 // #include <pthread.h>
81
82 static struct timeval _itstart, _itend;
83 static struct timezone itz;
84 void itstart(void)
85 {
86         gettimeofday(&_itstart, &itz);
87 }
88 static void itend(void)
89 {
90         gettimeofday(&_itend,&itz);
91 }
92 double itval(void)
93 {
94         double t1, t2;
95         t1 =  (double)_itstart.tv_sec + (double)_itstart.tv_usec/(1000*1000);
96         t2 =  (double)_itend.tv_sec + (double)_itend.tv_usec/(1000*1000);
97         return t2-t1;
98 }
99 #endif
100
101 static float I[3][3] = {{1,0,0},{0,1,0},{0,0,1}};
102 static float ZERO[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}};
103
104 /*
105 #define C99
106 #ifdef C99
107 #defineDO_INLINE inline 
108 #else 
109 #defineDO_INLINE static 
110 #endif
111 */
112 struct Cloth;
113
114 //////////////////////////////////////////
115 /* fast vector / matrix library, enhancements are welcome :) -dg */
116 /////////////////////////////////////////
117
118 /* DEFINITIONS */
119 typedef float lfVector[3];
120 typedef struct fmatrix3x3 {
121         float m[3][3]; /* 3x3 matrix */
122         unsigned int c,r; /* column and row number */
123         int pinned; /* is this vertex allowed to move? */
124         float n1,n2,n3; /* three normal vectors for collision constrains */
125         unsigned int vcount; /* vertex count */
126         unsigned int scount; /* spring count */ 
127 } fmatrix3x3;
128
129 ///////////////////////////
130 // float[3] vector
131 ///////////////////////////
132 /* simple vector code */
133 /* STATUS: verified */
134 DO_INLINE void mul_fvector_S(float to[3], float from[3], float scalar)
135 {
136         to[0] = from[0] * scalar;
137         to[1] = from[1] * scalar;
138         to[2] = from[2] * scalar;
139 }
140 /* simple cross product */
141 /* STATUS: verified */
142 DO_INLINE void cross_fvector(float to[3], float vectorA[3], float vectorB[3])
143 {
144         to[0] = vectorA[1] * vectorB[2] - vectorA[2] * vectorB[1];
145         to[1] = vectorA[2] * vectorB[0] - vectorA[0] * vectorB[2];
146         to[2] = vectorA[0] * vectorB[1] - vectorA[1] * vectorB[0];
147 }
148 /* simple v^T * v product ("outer product") */
149 /* STATUS: HAS TO BE verified (*should* work) */
150 DO_INLINE void mul_fvectorT_fvector(float to[3][3], float vectorA[3], float vectorB[3])
151 {
152         mul_fvector_S(to[0], vectorB, vectorA[0]);
153         mul_fvector_S(to[1], vectorB, vectorA[1]);
154         mul_fvector_S(to[2], vectorB, vectorA[2]);
155 }
156 /* simple v^T * v product with scalar ("outer product") */
157 /* STATUS: HAS TO BE verified (*should* work) */
158 DO_INLINE void mul_fvectorT_fvectorS(float to[3][3], float vectorA[3], float vectorB[3], float aS)
159 {       
160         mul_fvectorT_fvector(to, vectorA, vectorB);
161         
162         mul_fvector_S(to[0], to[0], aS);
163         mul_fvector_S(to[1], to[1], aS);
164         mul_fvector_S(to[2], to[2], aS);
165 }
166
167
168 /* printf vector[3] on console: for debug output */
169 static void print_fvector(float m3[3])
170 {
171         printf("%f\n%f\n%f\n\n",m3[0],m3[1],m3[2]);
172 }
173
174 ///////////////////////////
175 // long float vector float (*)[3]
176 ///////////////////////////
177 /* print long vector on console: for debug output */
178 DO_INLINE void print_lfvector(float (*fLongVector)[3], unsigned int verts)
179 {
180         unsigned int i = 0;
181         for(i = 0; i < verts; i++)
182         {
183                 print_fvector(fLongVector[i]);
184         }
185 }
186 /* create long vector */
187 DO_INLINE lfVector *create_lfvector(unsigned int verts)
188 {
189         // TODO: check if memory allocation was successfull */
190         return  (lfVector *)MEM_callocN (verts * sizeof(lfVector), "cloth_implicit_alloc_vector");
191         // return (lfVector *)cloth_aligned_malloc(&MEMORY_BASE, verts * sizeof(lfVector));
192 }
193 /* delete long vector */
194 DO_INLINE void del_lfvector(float (*fLongVector)[3])
195 {
196         if (fLongVector != NULL)
197         {
198                 MEM_freeN (fLongVector);
199                 // cloth_aligned_free(&MEMORY_BASE, fLongVector);
200         }
201 }
202 /* copy long vector */
203 DO_INLINE void cp_lfvector(float (*to)[3], float (*from)[3], unsigned int verts)
204 {
205         memcpy(to, from, verts * sizeof(lfVector));
206 }
207 /* init long vector with float[3] */
208 DO_INLINE void init_lfvector(float (*fLongVector)[3], float vector[3], unsigned int verts)
209 {
210         unsigned int i = 0;
211         for(i = 0; i < verts; i++)
212         {
213                 VECCOPY(fLongVector[i], vector);
214         }
215 }
216 /* zero long vector with float[3] */
217 DO_INLINE void zero_lfvector(float (*to)[3], unsigned int verts)
218 {
219         memset(to, 0.0f, verts * sizeof(lfVector));
220 }
221 /* multiply long vector with scalar*/
222 DO_INLINE void mul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
223 {
224         unsigned int i = 0;
225
226         for(i = 0; i < verts; i++)
227         {
228                 mul_fvector_S(to[i], fLongVector[i], scalar);
229         }
230 }
231 /* multiply long vector with scalar*/
232 /* A -= B * float */
233 DO_INLINE void submul_lfvectorS(float (*to)[3], float (*fLongVector)[3], float scalar, unsigned int verts)
234 {
235         unsigned int i = 0;
236         for(i = 0; i < verts; i++)
237         {
238                 VECSUBMUL(to[i], fLongVector[i], scalar);
239         }
240 }
241 /* dot product for big vector */
242 DO_INLINE float dot_lfvector(float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
243 {
244         long i = 0;
245         float temp = 0.0;
246 // XXX brecht, disabled this for now (first schedule line was already disabled),
247 // due to non-commutative nature of floating point ops this makes the sim give
248 // different results each time you run it!
249 // schedule(guided, 2)
250 //#pragma omp parallel for reduction(+: temp) if(verts > CLOTH_OPENMP_LIMIT)
251         for(i = 0; i < (long)verts; i++)
252         {
253                 temp += INPR(fLongVectorA[i], fLongVectorB[i]);
254         }
255         return temp;
256 }
257 /* A = B + C  --> for big vector */
258 DO_INLINE void add_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
259 {
260         unsigned int i = 0;
261
262         for(i = 0; i < verts; i++)
263         {
264                 VECADD(to[i], fLongVectorA[i], fLongVectorB[i]);
265         }
266
267 }
268 /* A = B + C * float --> for big vector */
269 DO_INLINE void add_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
270 {
271         unsigned int i = 0;
272
273         for(i = 0; i < verts; i++)
274         {
275                 VECADDS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
276
277         }
278 }
279 /* A = B * float + C * float --> for big vector */
280 DO_INLINE void add_lfvectorS_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float aS, float (*fLongVectorB)[3], float bS, unsigned int verts)
281 {
282         unsigned int i = 0;
283
284         for(i = 0; i < verts; i++)
285         {
286                 VECADDSS(to[i], fLongVectorA[i], aS, fLongVectorB[i], bS);
287         }
288 }
289 /* A = B - C * float --> for big vector */
290 DO_INLINE void sub_lfvector_lfvectorS(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], float bS, unsigned int verts)
291 {
292         unsigned int i = 0;
293         for(i = 0; i < verts; i++)
294         {
295                 VECSUBS(to[i], fLongVectorA[i], fLongVectorB[i], bS);
296         }
297
298 }
299 /* A = B - C --> for big vector */
300 DO_INLINE void sub_lfvector_lfvector(float (*to)[3], float (*fLongVectorA)[3], float (*fLongVectorB)[3], unsigned int verts)
301 {
302         unsigned int i = 0;
303
304         for(i = 0; i < verts; i++)
305         {
306                 VECSUB(to[i], fLongVectorA[i], fLongVectorB[i]);
307         }
308
309 }
310 ///////////////////////////
311 // 3x3 matrix
312 ///////////////////////////
313 #if 0
314 /* printf 3x3 matrix on console: for debug output */
315 static void print_fmatrix(float m3[3][3])
316 {
317         printf("%f\t%f\t%f\n",m3[0][0],m3[0][1],m3[0][2]);
318         printf("%f\t%f\t%f\n",m3[1][0],m3[1][1],m3[1][2]);
319         printf("%f\t%f\t%f\n\n",m3[2][0],m3[2][1],m3[2][2]);
320 }
321 #endif
322
323 /* copy 3x3 matrix */
324 DO_INLINE void cp_fmatrix(float to[3][3], float from[3][3])
325 {
326         // memcpy(to, from, sizeof (float) * 9);
327         VECCOPY(to[0], from[0]);
328         VECCOPY(to[1], from[1]);
329         VECCOPY(to[2], from[2]);
330 }
331
332 /* copy 3x3 matrix */
333 DO_INLINE void initdiag_fmatrixS(float to[3][3], float aS)
334 {
335         cp_fmatrix(to, ZERO);
336         
337         to[0][0] = aS;
338         to[1][1] = aS;
339         to[2][2] = aS;
340 }
341
342 /* calculate determinant of 3x3 matrix */
343 DO_INLINE float det_fmatrix(float m[3][3])
344 {
345         return  m[0][0]*m[1][1]*m[2][2] + m[1][0]*m[2][1]*m[0][2] + m[0][1]*m[1][2]*m[2][0] 
346                         -m[0][0]*m[1][2]*m[2][1] - m[0][1]*m[1][0]*m[2][2] - m[2][0]*m[1][1]*m[0][2];
347 }
348
349 DO_INLINE void inverse_fmatrix(float to[3][3], float from[3][3])
350 {
351         unsigned int i, j;
352         float d;
353
354         if((d=det_fmatrix(from))==0)
355         {
356                 printf("can't build inverse");
357                 exit(0);
358         }
359         for(i=0;i<3;i++) 
360         {
361                 for(j=0;j<3;j++) 
362                 {
363                         int i1=(i+1)%3;
364                         int i2=(i+2)%3;
365                         int j1=(j+1)%3;
366                         int j2=(j+2)%3;
367                         // reverse indexs i&j to take transpose
368                         to[j][i] = (from[i1][j1]*from[i2][j2]-from[i1][j2]*from[i2][j1])/d;
369                         /*
370                         if(i==j)
371                         to[i][j] = 1.0f / from[i][j];
372                         else
373                         to[i][j] = 0;
374                         */
375                 }
376         }
377
378 }
379
380 /* 3x3 matrix multiplied by a scalar */
381 /* STATUS: verified */
382 DO_INLINE void mul_fmatrix_S(float matrix[3][3], float scalar)
383 {
384         mul_fvector_S(matrix[0], matrix[0],scalar);
385         mul_fvector_S(matrix[1], matrix[1],scalar);
386         mul_fvector_S(matrix[2], matrix[2],scalar);
387 }
388
389 /* a vector multiplied by a 3x3 matrix */
390 /* STATUS: verified */
391 DO_INLINE void mul_fvector_fmatrix(float *to, float *from, float matrix[3][3])
392 {
393         to[0] = matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
394         to[1] = matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
395         to[2] = matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
396 }
397
398 /* 3x3 matrix multiplied by a vector */
399 /* STATUS: verified */
400 DO_INLINE void mul_fmatrix_fvector(float *to, float matrix[3][3], float *from)
401 {
402         to[0] = INPR(matrix[0],from);
403         to[1] = INPR(matrix[1],from);
404         to[2] = INPR(matrix[2],from);
405 }
406 /* 3x3 matrix multiplied by a 3x3 matrix */
407 /* STATUS: verified */
408 DO_INLINE void mul_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
409 {
410         mul_fvector_fmatrix(to[0], matrixA[0],matrixB);
411         mul_fvector_fmatrix(to[1], matrixA[1],matrixB);
412         mul_fvector_fmatrix(to[2], matrixA[2],matrixB);
413 }
414 /* 3x3 matrix addition with 3x3 matrix */
415 DO_INLINE void add_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
416 {
417         VECADD(to[0], matrixA[0], matrixB[0]);
418         VECADD(to[1], matrixA[1], matrixB[1]);
419         VECADD(to[2], matrixA[2], matrixB[2]);
420 }
421 /* 3x3 matrix add-addition with 3x3 matrix */
422 DO_INLINE void addadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
423 {
424         VECADDADD(to[0], matrixA[0], matrixB[0]);
425         VECADDADD(to[1], matrixA[1], matrixB[1]);
426         VECADDADD(to[2], matrixA[2], matrixB[2]);
427 }
428 /* 3x3 matrix sub-addition with 3x3 matrix */
429 DO_INLINE void addsub_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
430 {
431         VECADDSUBSS(to[0], matrixA[0], aS, matrixB[0], bS);
432         VECADDSUBSS(to[1], matrixA[1], aS, matrixB[1], bS);
433         VECADDSUBSS(to[2], matrixA[2], aS, matrixB[2], bS);
434 }
435 /* A -= B + C (3x3 matrix sub-addition with 3x3 matrix) */
436 DO_INLINE void subadd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
437 {
438         VECSUBADD(to[0], matrixA[0], matrixB[0]);
439         VECSUBADD(to[1], matrixA[1], matrixB[1]);
440         VECSUBADD(to[2], matrixA[2], matrixB[2]);
441 }
442 /* A -= B*x + C*y (3x3 matrix sub-addition with 3x3 matrix) */
443 DO_INLINE void subadd_fmatrixS_fmatrixS(float to[3][3], float matrixA[3][3], float aS, float matrixB[3][3], float bS)
444 {
445         VECSUBADDSS(to[0], matrixA[0], aS, matrixB[0], bS);
446         VECSUBADDSS(to[1], matrixA[1], aS, matrixB[1], bS);
447         VECSUBADDSS(to[2], matrixA[2], aS, matrixB[2], bS);
448 }
449 /* A = B - C (3x3 matrix subtraction with 3x3 matrix) */
450 DO_INLINE void sub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
451 {
452         VECSUB(to[0], matrixA[0], matrixB[0]);
453         VECSUB(to[1], matrixA[1], matrixB[1]);
454         VECSUB(to[2], matrixA[2], matrixB[2]);
455 }
456 /* A += B - C (3x3 matrix add-subtraction with 3x3 matrix) */
457 DO_INLINE void addsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
458 {
459         VECADDSUB(to[0], matrixA[0], matrixB[0]);
460         VECADDSUB(to[1], matrixA[1], matrixB[1]);
461         VECADDSUB(to[2], matrixA[2], matrixB[2]);
462 }
463 /////////////////////////////////////////////////////////////////
464 // special functions
465 /////////////////////////////////////////////////////////////////
466 /* a vector multiplied and added to/by a 3x3 matrix */
467 DO_INLINE void muladd_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
468 {
469         to[0] += matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
470         to[1] += matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
471         to[2] += matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
472 }
473 /* 3x3 matrix multiplied and added  to/by a 3x3 matrix  and added to another 3x3 matrix */
474 DO_INLINE void muladd_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
475 {
476         muladd_fvector_fmatrix(to[0], matrixA[0],matrixB);
477         muladd_fvector_fmatrix(to[1], matrixA[1],matrixB);
478         muladd_fvector_fmatrix(to[2], matrixA[2],matrixB);
479 }
480 /* a vector multiplied and sub'd to/by a 3x3 matrix */
481 DO_INLINE void mulsub_fvector_fmatrix(float to[3], float from[3], float matrix[3][3])
482 {
483         to[0] -= matrix[0][0]*from[0] + matrix[1][0]*from[1] + matrix[2][0]*from[2];
484         to[1] -= matrix[0][1]*from[0] + matrix[1][1]*from[1] + matrix[2][1]*from[2];
485         to[2] -= matrix[0][2]*from[0] + matrix[1][2]*from[1] + matrix[2][2]*from[2];
486 }
487 /* 3x3 matrix multiplied and sub'd  to/by a 3x3 matrix  and added to another 3x3 matrix */
488 DO_INLINE void mulsub_fmatrix_fmatrix(float to[3][3], float matrixA[3][3], float matrixB[3][3])
489 {
490         mulsub_fvector_fmatrix(to[0], matrixA[0],matrixB);
491         mulsub_fvector_fmatrix(to[1], matrixA[1],matrixB);
492         mulsub_fvector_fmatrix(to[2], matrixA[2],matrixB);
493 }
494 /* 3x3 matrix multiplied+added by a vector */
495 /* STATUS: verified */
496 DO_INLINE void muladd_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
497 {
498         to[0] += INPR(matrix[0],from);
499         to[1] += INPR(matrix[1],from);
500         to[2] += INPR(matrix[2],from);  
501 }
502 /* 3x3 matrix multiplied+sub'ed by a vector */
503 DO_INLINE void mulsub_fmatrix_fvector(float to[3], float matrix[3][3], float from[3])
504 {
505         to[0] -= INPR(matrix[0],from);
506         to[1] -= INPR(matrix[1],from);
507         to[2] -= INPR(matrix[2],from);
508 }
509 /////////////////////////////////////////////////////////////////
510
511 ///////////////////////////
512 // SPARSE SYMMETRIC big matrix with 3x3 matrix entries
513 ///////////////////////////
514 /* printf a big matrix on console: for debug output */
515 #if 0
516 static void print_bfmatrix(fmatrix3x3 *m3)
517 {
518         unsigned int i = 0;
519
520         for(i = 0; i < m3[0].vcount + m3[0].scount; i++)
521         {
522                 print_fmatrix(m3[i].m);
523         }
524 }
525 #endif
526
527 /* create big matrix */
528 DO_INLINE fmatrix3x3 *create_bfmatrix(unsigned int verts, unsigned int springs)
529 {
530         // TODO: check if memory allocation was successfull */
531         fmatrix3x3 *temp = (fmatrix3x3 *)MEM_callocN (sizeof (fmatrix3x3) * (verts + springs), "cloth_implicit_alloc_matrix");
532         temp[0].vcount = verts;
533         temp[0].scount = springs;
534         return temp;
535 }
536 /* delete big matrix */
537 DO_INLINE void del_bfmatrix(fmatrix3x3 *matrix)
538 {
539         if (matrix != NULL)
540         {
541                 MEM_freeN (matrix);
542         }
543 }
544
545 /* copy big matrix */
546 DO_INLINE void cp_bfmatrix(fmatrix3x3 *to, fmatrix3x3 *from)
547 {       
548         // TODO bounds checking 
549         memcpy(to, from, sizeof(fmatrix3x3) * (from[0].vcount+from[0].scount) );
550 }
551
552 /* init big matrix */
553 // slow in parallel
554 DO_INLINE void init_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
555 {
556         unsigned int i;
557
558         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
559         {               
560                 cp_fmatrix(matrix[i].m, m3); 
561         }
562 }
563
564 /* init the diagonal of big matrix */
565 // slow in parallel
566 DO_INLINE void initdiag_bfmatrix(fmatrix3x3 *matrix, float m3[3][3])
567 {
568         unsigned int i,j;
569         float tmatrix[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
570
571         for(i = 0; i < matrix[0].vcount; i++)
572         {               
573                 cp_fmatrix(matrix[i].m, m3); 
574         }
575         for(j = matrix[0].vcount; j < matrix[0].vcount+matrix[0].scount; j++)
576         {
577                 cp_fmatrix(matrix[j].m, tmatrix); 
578         }
579 }
580
581 /* multiply big matrix with scalar*/
582 DO_INLINE void mul_bfmatrix_S(fmatrix3x3 *matrix, float scalar)
583 {
584         unsigned int i = 0;
585         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
586         {
587                 mul_fmatrix_S(matrix[i].m, scalar);
588         }
589 }
590
591 /* SPARSE SYMMETRIC multiply big matrix with long vector*/
592 /* STATUS: verified */
593 DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
594 {
595         unsigned int i = 0;
596         unsigned int vcount = from[0].vcount;
597         lfVector *temp = create_lfvector(vcount);
598         
599         zero_lfvector(to, vcount);
600
601 #pragma omp parallel sections private(i) if(vcount > CLOTH_OPENMP_LIMIT)
602         {
603 #pragma omp section
604                 {
605                         for(i = from[0].vcount; i < from[0].vcount+from[0].scount; i++)
606                         {
607                                 muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]);
608                         }
609                 }       
610 #pragma omp section
611                 {
612                         for(i = 0; i < from[0].vcount+from[0].scount; i++)
613                         {
614                                 muladd_fmatrix_fvector(temp[from[i].r], from[i].m, fLongVector[from[i].c]);
615                         }
616                 }
617         }
618         add_lfvector_lfvector(to, to, temp, from[0].vcount);
619         
620         del_lfvector(temp);
621         
622         
623 }
624
625 /* SPARSE SYMMETRIC multiply big matrix with long vector (for diagonal preconditioner) */
626 /* STATUS: verified */
627 DO_INLINE void mul_prevfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector *fLongVector)
628 {
629         unsigned int i = 0;
630         
631         for(i = 0; i < from[0].vcount; i++)
632         {
633                 mul_fmatrix_fvector(to[from[i].r], from[i].m, fLongVector[from[i].c]);
634         }
635 }
636
637 /* SPARSE SYMMETRIC add big matrix with big matrix: A = B + C*/
638 DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
639 {
640         unsigned int i = 0;
641
642         /* process diagonal elements */
643         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
644         {
645                 add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);   
646         }
647
648 }
649 /* SPARSE SYMMETRIC add big matrix with big matrix: A += B + C */
650 DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
651 {
652         unsigned int i = 0;
653
654         /* process diagonal elements */
655         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
656         {
657                 addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
658         }
659
660 }
661 /* SPARSE SYMMETRIC subadd big matrix with big matrix: A -= B + C */
662 DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
663 {
664         unsigned int i = 0;
665
666         /* process diagonal elements */
667         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
668         {
669                 subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
670         }
671
672 }
673 /*  A = B - C (SPARSE SYMMETRIC sub big matrix with big matrix) */
674 DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
675 {
676         unsigned int i = 0;
677
678         /* process diagonal elements */
679         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
680         {
681                 sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);   
682         }
683
684 }
685 /* SPARSE SYMMETRIC sub big matrix with big matrix S (special constraint matrix with limited entries) */
686 DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
687 {
688         unsigned int i = 0;
689
690         /* process diagonal elements */
691         for(i = 0; i < matrix[0].vcount; i++)
692         {
693                 sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m);       
694         }
695
696 }
697 /* A += B - C (SPARSE SYMMETRIC addsub big matrix with big matrix) */
698 DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from,  fmatrix3x3 *matrix)
699 {
700         unsigned int i = 0;
701
702         /* process diagonal elements */
703         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
704         {
705                 addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m);        
706         }
707
708 }
709 /* SPARSE SYMMETRIC sub big matrix with big matrix*/
710 /* A -= B * float + C * float --> for big matrix */
711 /* VERIFIED */
712 DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, float aS,  fmatrix3x3 *matrix, float bS)
713 {
714         unsigned int i = 0;
715
716         /* process diagonal elements */
717         for(i = 0; i < matrix[0].vcount+matrix[0].scount; i++)
718         {
719                 subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS);      
720         }
721
722 }
723
724 ///////////////////////////////////////////////////////////////////
725 // simulator start
726 ///////////////////////////////////////////////////////////////////
727 typedef struct Implicit_Data 
728 {
729         lfVector *X, *V, *Xnew, *Vnew, *olddV, *F, *B, *dV, *z;
730         fmatrix3x3 *A, *dFdV, *dFdX, *S, *P, *Pinv, *bigI, *M; 
731 } Implicit_Data;
732
733 int implicit_init (Object *UNUSED(ob), ClothModifierData *clmd)
734 {
735         unsigned int i = 0;
736         unsigned int pinned = 0;
737         Cloth *cloth = NULL;
738         ClothVertex *verts = NULL;
739         ClothSpring *spring = NULL;
740         Implicit_Data *id = NULL;
741         LinkNode *search = NULL;
742         
743         if(G.rt > 0)
744                 printf("implicit_init\n");
745
746         // init memory guard
747         // MEMORY_BASE.first = MEMORY_BASE.last = NULL;
748
749         cloth = (Cloth *)clmd->clothObject;
750         verts = cloth->verts;
751
752         // create implicit base
753         id = (Implicit_Data *)MEM_callocN (sizeof(Implicit_Data), "implicit vecmat");
754         cloth->implicit = id;
755
756         /* process diagonal elements */         
757         id->A = create_bfmatrix(cloth->numverts, cloth->numsprings);
758         id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings);
759         id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings);
760         id->S = create_bfmatrix(cloth->numverts, 0);
761         id->Pinv = create_bfmatrix(cloth->numverts, cloth->numsprings);
762         id->P = create_bfmatrix(cloth->numverts, cloth->numsprings);
763         id->bigI = create_bfmatrix(cloth->numverts, cloth->numsprings); // TODO 0 springs
764         id->M = create_bfmatrix(cloth->numverts, cloth->numsprings);
765         id->X = create_lfvector(cloth->numverts);
766         id->Xnew = create_lfvector(cloth->numverts);
767         id->V = create_lfvector(cloth->numverts);
768         id->Vnew = create_lfvector(cloth->numverts);
769         id->olddV = create_lfvector(cloth->numverts);
770         zero_lfvector(id->olddV, cloth->numverts);
771         id->F = create_lfvector(cloth->numverts);
772         id->B = create_lfvector(cloth->numverts);
773         id->dV = create_lfvector(cloth->numverts);
774         id->z = create_lfvector(cloth->numverts);
775         
776         for(i=0;i<cloth->numverts;i++) 
777         {
778                 id->A[i].r = id->A[i].c = id->dFdV[i].r = id->dFdV[i].c = id->dFdX[i].r = id->dFdX[i].c = id->P[i].c = id->P[i].r = id->Pinv[i].c = id->Pinv[i].r = id->bigI[i].c = id->bigI[i].r = id->M[i].r = id->M[i].c = i;
779
780                 if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
781                 {
782                         id->S[pinned].pinned = 1;
783                         id->S[pinned].c = id->S[pinned].r = i;
784                         pinned++;
785                 }
786                 
787                 initdiag_fmatrixS(id->M[i].m, verts[i].mass);
788         }
789
790         // S is special and needs specific vcount and scount
791         id->S[0].vcount = pinned; id->S[0].scount = 0;
792
793         // init springs 
794         search = cloth->springs;
795         for(i=0;i<cloth->numsprings;i++) 
796         {
797                 spring = search->link;
798                 
799                 // dFdV_start[i].r = big_I[i].r = big_zero[i].r = 
800                 id->A[i+cloth->numverts].r = id->dFdV[i+cloth->numverts].r = id->dFdX[i+cloth->numverts].r = 
801                                 id->P[i+cloth->numverts].r = id->Pinv[i+cloth->numverts].r = id->bigI[i+cloth->numverts].r = id->M[i+cloth->numverts].r = spring->ij;
802
803                 // dFdV_start[i].c = big_I[i].c = big_zero[i].c = 
804                 id->A[i+cloth->numverts].c = id->dFdV[i+cloth->numverts].c = id->dFdX[i+cloth->numverts].c = 
805                                 id->P[i+cloth->numverts].c = id->Pinv[i+cloth->numverts].c = id->bigI[i+cloth->numverts].c = id->M[i+cloth->numverts].c = spring->kl;
806
807                 spring->matrix_index = i + cloth->numverts;
808                 
809                 search = search->next;
810         }
811         
812         initdiag_bfmatrix(id->bigI, I);
813
814         for(i = 0; i < cloth->numverts; i++)
815         {               
816                 VECCOPY(id->X[i], verts[i].x);
817         }
818
819         return 1;
820 }
821 int     implicit_free (ClothModifierData *clmd)
822 {
823         Implicit_Data *id;
824         Cloth *cloth;
825         cloth = (Cloth *)clmd->clothObject;
826
827         if(cloth)
828         {
829                 id = cloth->implicit;
830
831                 if(id)
832                 {
833                         del_bfmatrix(id->A);
834                         del_bfmatrix(id->dFdV);
835                         del_bfmatrix(id->dFdX);
836                         del_bfmatrix(id->S);
837                         del_bfmatrix(id->P);
838                         del_bfmatrix(id->Pinv);
839                         del_bfmatrix(id->bigI);
840                         del_bfmatrix(id->M);
841
842                         del_lfvector(id->X);
843                         del_lfvector(id->Xnew);
844                         del_lfvector(id->V);
845                         del_lfvector(id->Vnew);
846                         del_lfvector(id->olddV);
847                         del_lfvector(id->F);
848                         del_lfvector(id->B);
849                         del_lfvector(id->dV);
850                         del_lfvector(id->z);
851
852                         MEM_freeN(id);
853                 }
854         }
855
856         return 1;
857 }
858
859 DO_INLINE float fb(float length, float L)
860 {
861         float x = length/L;
862         return (-11.541f*pow(x,4)+34.193f*pow(x,3)-39.083f*pow(x,2)+23.116f*x-9.713f);
863 }
864
865 DO_INLINE float fbderiv(float length, float L)
866 {
867         float x = length/L;
868
869         return (-46.164f*pow(x,3)+102.579f*pow(x,2)-78.166f*x+23.116f);
870 }
871
872 DO_INLINE float fbstar(float length, float L, float kb, float cb)
873 {
874         float tempfb = kb * fb(length, L);
875
876         float fbstar = cb * (length - L);
877         
878         if(tempfb < fbstar)
879                 return fbstar;
880         else
881                 return tempfb;          
882 }
883
884 // function to calculae bending spring force (taken from Choi & Co)
885 DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb)
886 {
887         float tempfb = kb * fb(length, L);
888         float fbstar = cb * (length - L);
889
890         if(tempfb < fbstar)
891         {               
892                 return cb;
893         }
894         else
895         {
896                 return kb * fbderiv(length, L); 
897         }       
898 }
899
900 DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
901 {
902         unsigned int i=0;
903
904         for(i=0;i<S[0].vcount;i++)
905         {
906                 mul_fvector_fmatrix(V[S[i].r], V[S[i].r], S[i].m);
907         }
908 }
909
910 static int  cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S)
911 {
912         // Solves for unknown X in equation AX=B
913         unsigned int conjgrad_loopcount=0, conjgrad_looplimit=100;
914         float conjgrad_epsilon=0.0001f /* , conjgrad_lasterror=0 */ /* UNUSED */;
915         lfVector *q, *d, *tmp, *r; 
916         float s, starget, a, s_prev;
917         unsigned int numverts = lA[0].vcount;
918         q = create_lfvector(numverts);
919         d = create_lfvector(numverts);
920         tmp = create_lfvector(numverts);
921         r = create_lfvector(numverts);
922
923         // zero_lfvector(ldV, CLOTHPARTICLES);
924         filter(ldV, S);
925
926         add_lfvector_lfvector(ldV, ldV, z, numverts);
927
928         // r = B - Mul(tmp,A,X);    // just use B if X known to be zero
929         cp_lfvector(r, lB, numverts);
930         mul_bfmatrix_lfvector(tmp, lA, ldV);
931         sub_lfvector_lfvector(r, r, tmp, numverts);
932
933         filter(r,S);
934
935         cp_lfvector(d, r, numverts);
936
937         s = dot_lfvector(r, r, numverts);
938         starget = s * sqrt(conjgrad_epsilon);
939
940         while(s>starget && conjgrad_loopcount < conjgrad_looplimit)
941         {       
942                 // Mul(q,A,d); // q = A*d;
943                 mul_bfmatrix_lfvector(q, lA, d);
944
945                 filter(q,S);
946
947                 a = s/dot_lfvector(d, q, numverts);
948
949                 // X = X + d*a;
950                 add_lfvector_lfvectorS(ldV, ldV, d, a, numverts);
951
952                 // r = r - q*a;
953                 sub_lfvector_lfvectorS(r, r, q, a, numverts);
954
955                 s_prev = s;
956                 s = dot_lfvector(r, r, numverts);
957
958                 //d = r+d*(s/s_prev);
959                 add_lfvector_lfvectorS(d, r, d, (s/s_prev), numverts);
960
961                 filter(d,S);
962
963                 conjgrad_loopcount++;
964         }
965         /* conjgrad_lasterror = s; */ /* UNUSED */
966
967         del_lfvector(q);
968         del_lfvector(d);
969         del_lfvector(tmp);
970         del_lfvector(r);
971         // printf("W/O conjgrad_loopcount: %d\n", conjgrad_loopcount);
972
973         return conjgrad_loopcount<conjgrad_looplimit;  // true means we reached desired accuracy in given time - ie stable
974 }
975
976 // block diagonalizer
977 DO_INLINE void BuildPPinv(fmatrix3x3 *lA, fmatrix3x3 *P, fmatrix3x3 *Pinv)
978 {
979         unsigned int i = 0;
980         
981         // Take only the diagonal blocks of A
982 // #pragma omp parallel for private(i) if(lA[0].vcount > CLOTH_OPENMP_LIMIT)
983         for(i = 0; i<lA[0].vcount; i++)
984         {
985                 // block diagonalizer
986                 cp_fmatrix(P[i].m, lA[i].m);
987                 inverse_fmatrix(Pinv[i].m, P[i].m);
988                 
989         }
990 }
991 #if 0
992 /*
993 // version 1.3
994 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv)
995 {
996         unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
997         float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0;
998         float conjgrad_epsilon=0.0001; // 0.2 is dt for steps=5
999         lfVector *r = create_lfvector(numverts);
1000         lfVector *p = create_lfvector(numverts);
1001         lfVector *s = create_lfvector(numverts);
1002         lfVector *h = create_lfvector(numverts);
1003         
1004         BuildPPinv(lA, P, Pinv);
1005         
1006         filter(dv, S);
1007         add_lfvector_lfvector(dv, dv, z, numverts);
1008         
1009         mul_bfmatrix_lfvector(r, lA, dv);
1010         sub_lfvector_lfvector(r, lB, r, numverts);
1011         filter(r, S);
1012         
1013         mul_prevfmatrix_lfvector(p, Pinv, r);
1014         filter(p, S);
1015         
1016         deltaNew = dot_lfvector(r, p, numverts);
1017         
1018         delta0 = deltaNew * sqrt(conjgrad_epsilon);
1019         
1020         // itstart();
1021         
1022         while ((deltaNew > delta0) && (iterations < conjgrad_looplimit))
1023         {
1024                 iterations++;
1025                 
1026                 mul_bfmatrix_lfvector(s, lA, p);
1027                 filter(s, S);
1028                 
1029                 alpha = deltaNew / dot_lfvector(p, s, numverts);
1030                 
1031                 add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
1032                 
1033                 add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
1034                 
1035                 mul_prevfmatrix_lfvector(h, Pinv, r);
1036                 filter(h, S);
1037                 
1038                 deltaOld = deltaNew;
1039                 
1040                 deltaNew = dot_lfvector(r, h, numverts);
1041                 
1042                 add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
1043                 
1044                 filter(p, S);
1045                 
1046         }
1047         
1048         // itend();
1049         // printf("cg_filtered_pre time: %f\n", (float)itval());
1050         
1051         del_lfvector(h);
1052         del_lfvector(s);
1053         del_lfvector(p);
1054         del_lfvector(r);
1055         
1056         printf("iterations: %d\n", iterations);
1057         
1058         return iterations<conjgrad_looplimit;
1059 }
1060 */
1061 // version 1.4
1062 static int cg_filtered_pre(lfVector *dv, fmatrix3x3 *lA, lfVector *lB, lfVector *z, fmatrix3x3 *S, fmatrix3x3 *P, fmatrix3x3 *Pinv, fmatrix3x3 *bigI)
1063 {
1064         unsigned int numverts = lA[0].vcount, iterations = 0, conjgrad_looplimit=100;
1065         float delta0 = 0, deltaNew = 0, deltaOld = 0, alpha = 0, tol = 0;
1066         lfVector *r = create_lfvector(numverts);
1067         lfVector *p = create_lfvector(numverts);
1068         lfVector *s = create_lfvector(numverts);
1069         lfVector *h = create_lfvector(numverts);
1070         lfVector *bhat = create_lfvector(numverts);
1071         lfVector *btemp = create_lfvector(numverts);
1072         
1073         BuildPPinv(lA, P, Pinv);
1074         
1075         initdiag_bfmatrix(bigI, I);
1076         sub_bfmatrix_Smatrix(bigI, bigI, S);
1077         
1078         // x = Sx_0+(I-S)z
1079         filter(dv, S);
1080         add_lfvector_lfvector(dv, dv, z, numverts);
1081         
1082         // b_hat = S(b-A(I-S)z)
1083         mul_bfmatrix_lfvector(r, lA, z);
1084         mul_bfmatrix_lfvector(bhat, bigI, r);
1085         sub_lfvector_lfvector(bhat, lB, bhat, numverts);
1086         
1087         // r = S(b-Ax)
1088         mul_bfmatrix_lfvector(r, lA, dv);
1089         sub_lfvector_lfvector(r, lB, r, numverts);
1090         filter(r, S);
1091         
1092         // p = SP^-1r
1093         mul_prevfmatrix_lfvector(p, Pinv, r);
1094         filter(p, S);
1095         
1096         // delta0 = bhat^TP^-1bhat
1097         mul_prevfmatrix_lfvector(btemp, Pinv, bhat);
1098         delta0 = dot_lfvector(bhat, btemp, numverts);
1099         
1100         // deltaNew = r^TP
1101         deltaNew = dot_lfvector(r, p, numverts);
1102         
1103         /*
1104         filter(dv, S);
1105         add_lfvector_lfvector(dv, dv, z, numverts);
1106         
1107         mul_bfmatrix_lfvector(r, lA, dv);
1108         sub_lfvector_lfvector(r, lB, r, numverts);
1109         filter(r, S);
1110         
1111         mul_prevfmatrix_lfvector(p, Pinv, r);
1112         filter(p, S);
1113         
1114         deltaNew = dot_lfvector(r, p, numverts);
1115         
1116         delta0 = deltaNew * sqrt(conjgrad_epsilon);
1117         */
1118         
1119         // itstart();
1120         
1121         tol = (0.01*0.2);
1122         
1123         while ((deltaNew > delta0*tol*tol) && (iterations < conjgrad_looplimit))
1124         {
1125                 iterations++;
1126                 
1127                 mul_bfmatrix_lfvector(s, lA, p);
1128                 filter(s, S);
1129                 
1130                 alpha = deltaNew / dot_lfvector(p, s, numverts);
1131                 
1132                 add_lfvector_lfvectorS(dv, dv, p, alpha, numverts);
1133                 
1134                 add_lfvector_lfvectorS(r, r, s, -alpha, numverts);
1135                 
1136                 mul_prevfmatrix_lfvector(h, Pinv, r);
1137                 filter(h, S);
1138                 
1139                 deltaOld = deltaNew;
1140                 
1141                 deltaNew = dot_lfvector(r, h, numverts);
1142                 
1143                 add_lfvector_lfvectorS(p, h, p, deltaNew / deltaOld, numverts);
1144                 
1145                 filter(p, S);
1146                 
1147         }
1148         
1149         // itend();
1150         // printf("cg_filtered_pre time: %f\n", (float)itval());
1151         
1152         del_lfvector(btemp);
1153         del_lfvector(bhat);
1154         del_lfvector(h);
1155         del_lfvector(s);
1156         del_lfvector(p);
1157         del_lfvector(r);
1158         
1159         // printf("iterations: %d\n", iterations);
1160         
1161         return iterations<conjgrad_looplimit;
1162 }
1163 #endif
1164
1165 // outer product is NOT cross product!!!
1166 DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length, float L, float dot, float k)
1167 {
1168         // dir is unit length direction, rest is spring's restlength, k is spring constant.
1169         // return  (outerprod(dir,dir)*k + (I - outerprod(dir,dir))*(k - ((k*L)/length)));
1170         float temp[3][3];
1171         float temp1 = k*(1.0 - (L/length));     
1172         
1173         mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot);
1174         sub_fmatrix_fmatrix(to, I, temp);
1175         mul_fmatrix_S(to, temp1);
1176         
1177         mul_fvectorT_fvectorS(temp, extent, extent, k/ dot);
1178         add_fmatrix_fmatrix(to, to, temp);
1179         
1180         /*
1181         mul_fvectorT_fvector(temp, dir, dir);
1182         sub_fmatrix_fmatrix(to, I, temp);
1183         mul_fmatrix_S(to, k* (1.0f-(L/length)));
1184         mul_fmatrix_S(temp, k);
1185         add_fmatrix_fmatrix(to, temp, to);
1186         */
1187 }
1188
1189 DO_INLINE void dfdx_spring_type2(float to[3][3], float dir[3], float length, float L, float k, float cb)
1190 {
1191         // return  outerprod(dir,dir)*fbstar_jacobi(length, L, k, cb);
1192         mul_fvectorT_fvectorS(to, dir, dir, fbstar_jacobi(length, L, k, cb));
1193 }
1194
1195 DO_INLINE void dfdv_damp(float to[3][3], float dir[3], float damping)
1196 {
1197         // derivative of force wrt velocity.  
1198         mul_fvectorT_fvectorS(to, dir, dir, damping);
1199         
1200 }
1201
1202 DO_INLINE void dfdx_spring(float to[3][3],  float dir[3],float length,float L,float k)
1203 {
1204         // dir is unit length direction, rest is spring's restlength, k is spring constant.
1205         //return  ( (I-outerprod(dir,dir))*Min(1.0f,rest/length) - I) * -k;
1206         mul_fvectorT_fvector(to, dir, dir);
1207         sub_fmatrix_fmatrix(to, I, to);
1208
1209         mul_fmatrix_S(to, (L/length)); 
1210         sub_fmatrix_fmatrix(to, to, I);
1211         mul_fmatrix_S(to, -k);
1212 }
1213
1214 // unused atm
1215 DO_INLINE void dfdx_damp(float to[3][3],  float dir[3],float length,const float vel[3],float rest,float damping)
1216 {
1217         // inner spring damping   vel is the relative velocity  of the endpoints.  
1218         //      return (I-outerprod(dir,dir)) * (-damping * -(dot(dir,vel)/Max(length,rest)));
1219         mul_fvectorT_fvector(to, dir, dir);
1220         sub_fmatrix_fmatrix(to, I, to);
1221         mul_fmatrix_S(to,  (-damping * -(INPR(dir,vel)/MAX2(length,rest)))); 
1222
1223 }
1224
1225 DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, lfVector *UNUSED(lF), lfVector *X, lfVector *V, fmatrix3x3 *UNUSED(dFdV), fmatrix3x3 *UNUSED(dFdX), float time)
1226 {
1227         Cloth *cloth = clmd->clothObject;
1228         ClothVertex *verts = cloth->verts;
1229         float extent[3];
1230         float length = 0, dot = 0;
1231         float dir[3] = {0,0,0};
1232         float vel[3];
1233         float k = 0.0f;
1234         float L = s->restlen;
1235         float cb; /* = clmd->sim_parms->structural; */ /*UNUSED*/
1236
1237         float nullf[3] = {0,0,0};
1238         float stretch_force[3] = {0,0,0};
1239         float bending_force[3] = {0,0,0};
1240         float damping_force[3] = {0,0,0};
1241         float nulldfdx[3][3]={ {0,0,0}, {0,0,0}, {0,0,0}};
1242         
1243         float scaling = 0.0;
1244
1245         int no_compress = clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS;
1246         
1247         VECCOPY(s->f, nullf);
1248         cp_fmatrix(s->dfdx, nulldfdx);
1249         cp_fmatrix(s->dfdv, nulldfdx);
1250
1251         // calculate elonglation
1252         VECSUB(extent, X[s->kl], X[s->ij]);
1253         VECSUB(vel, V[s->kl], V[s->ij]);
1254         dot = INPR(extent, extent);
1255         length = sqrt(dot);
1256         
1257         s->flags &= ~CLOTH_SPRING_FLAG_NEEDED;
1258         
1259         if(length > ALMOST_ZERO)
1260         {
1261                 /*
1262                 if(length>L)
1263                 {
1264                 if((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) 
1265                 && ((((length-L)*100.0f/L) > clmd->sim_parms->maxspringlen))) // cut spring!
1266                 {
1267                 s->flags |= CSPRING_FLAG_DEACTIVATE;
1268                 return;
1269         }
1270         } 
1271                 */
1272                 mul_fvector_S(dir, extent, 1.0f/length);
1273         }
1274         else    
1275         {
1276                 mul_fvector_S(dir, extent, 0.0f);
1277         }
1278         
1279         // calculate force of structural + shear springs
1280         if((s->type & CLOTH_SPRING_TYPE_STRUCTURAL) || (s->type & CLOTH_SPRING_TYPE_SHEAR))
1281         {
1282                 if(length > L || no_compress)
1283                 {
1284                         s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1285                         
1286                         k = clmd->sim_parms->structural;
1287                                 
1288                         scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
1289                         
1290                         k = scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
1291                         
1292                         // TODO: verify, half verified (couldn't see error)
1293                         mul_fvector_S(stretch_force, dir, k*(length-L)); 
1294
1295                         VECADD(s->f, s->f, stretch_force);
1296
1297                         // Ascher & Boxman, p.21: Damping only during elonglation
1298                         // something wrong with it...
1299                         mul_fvector_S(damping_force, dir, clmd->sim_parms->Cdis * INPR(vel,dir));
1300                         VECADD(s->f, s->f, damping_force);
1301                         
1302                         /* VERIFIED */
1303                         dfdx_spring(s->dfdx, dir, length, L, k);
1304                         
1305                         /* VERIFIED */
1306                         dfdv_damp(s->dfdv, dir, clmd->sim_parms->Cdis);
1307                         
1308                 }
1309         }
1310         else if(s->type & CLOTH_SPRING_TYPE_GOAL)
1311         {
1312                 float tvect[3];
1313                 
1314                 s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1315                 
1316                 // current_position = xold + t * (newposition - xold)
1317                 VECSUB(tvect, verts[s->ij].xconst, verts[s->ij].xold);
1318                 mul_fvector_S(tvect, tvect, time);
1319                 VECADD(tvect, tvect, verts[s->ij].xold);
1320
1321                 VECSUB(extent, X[s->ij], tvect);
1322                 
1323                 // SEE MSG BELOW (these are UNUSED)
1324                 // dot = INPR(extent, extent);
1325                 // length = sqrt(dot);
1326                 
1327                 k = clmd->sim_parms->goalspring;
1328                 
1329                 scaling = k + s->stiffness * ABS(clmd->sim_parms->max_struct-k);
1330                         
1331                 k = verts [s->ij].goal * scaling / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
1332                 
1333                 VECADDS(s->f, s->f, extent, -k);
1334                 
1335                 mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * INPR(vel,dir));
1336                 VECADD(s->f, s->f, damping_force);
1337                 
1338                 // HERE IS THE PROBLEM!!!!
1339                 // dfdx_spring(s->dfdx, dir, length, 0.0, k);
1340                 // dfdv_damp(s->dfdv, dir, MIN2(1.0, (clmd->sim_parms->goalfrict/100.0)));
1341         }
1342         else // calculate force of bending springs
1343         {
1344                 if(length < L)
1345                 {
1346                         s->flags |= CLOTH_SPRING_FLAG_NEEDED;
1347                         
1348                         k = clmd->sim_parms->bending;   
1349                         
1350                         scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k);                  
1351                         cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON));
1352
1353                         mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb));
1354                         VECADD(s->f, s->f, bending_force);
1355
1356                         dfdx_spring_type2(s->dfdx, dir, length,L, k, cb);
1357                 }
1358         }
1359 }
1360
1361 DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSpring *s, lfVector *lF, lfVector *UNUSED(X), lfVector *UNUSED(V), fmatrix3x3 *dFdV, fmatrix3x3 *dFdX)
1362 {
1363         if(s->flags & CLOTH_SPRING_FLAG_NEEDED)
1364         {
1365                 if(!(s->type & CLOTH_SPRING_TYPE_BENDING))
1366                 {
1367                         sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv);
1368                         sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv);
1369                         add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv); 
1370                 }
1371
1372                 VECADD(lF[s->ij], lF[s->ij], s->f);
1373                 
1374                 if(!(s->type & CLOTH_SPRING_TYPE_GOAL))
1375                         VECSUB(lF[s->kl], lF[s->kl], s->f);
1376                 
1377                 sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx);
1378                 sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx);
1379                 add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx);
1380         }       
1381 }
1382
1383
1384 static void CalcFloat( float *v1, float *v2, float *v3, float *n)
1385 {
1386         float n1[3],n2[3];
1387
1388         n1[0]= v1[0]-v2[0];
1389         n2[0]= v2[0]-v3[0];
1390         n1[1]= v1[1]-v2[1];
1391         n2[1]= v2[1]-v3[1];
1392         n1[2]= v1[2]-v2[2];
1393         n2[2]= v2[2]-v3[2];
1394         n[0]= n1[1]*n2[2]-n1[2]*n2[1];
1395         n[1]= n1[2]*n2[0]-n1[0]*n2[2];
1396         n[2]= n1[0]*n2[1]-n1[1]*n2[0];
1397 }
1398
1399 static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n)
1400 {
1401         /* real cross! */
1402         float n1[3],n2[3];
1403
1404         n1[0]= v1[0]-v3[0];
1405         n1[1]= v1[1]-v3[1];
1406         n1[2]= v1[2]-v3[2];
1407
1408         n2[0]= v2[0]-v4[0];
1409         n2[1]= v2[1]-v4[1];
1410         n2[2]= v2[2]-v4[2];
1411
1412         n[0]= n1[1]*n2[2]-n1[2]*n2[1];
1413         n[1]= n1[2]*n2[0]-n1[0]*n2[2];
1414         n[2]= n1[0]*n2[1]-n1[1]*n2[0];
1415 }
1416
1417 static float calculateVertexWindForce(float wind[3], float vertexnormal[3])  
1418 {
1419         return (INPR(wind, vertexnormal));
1420 }
1421
1422 typedef struct HairGridVert {
1423         float velocity[3];
1424         float density;
1425 } HairGridVert;
1426 #define HAIR_GRID_INDEX(vec, min, max, axis) (int)( (vec[axis] - min[axis]) / (max[axis] - min[axis]) * 9.99f );
1427 /* Smoothing of hair velocities:
1428  * adapted from
1429                 Volumetric Methods for Simulation and Rendering of Hair
1430                 by Lena Petrovic, Mark Henne and John Anderson
1431  *              Pixar Technical Memo #06-08, Pixar Animation Studios
1432  */
1433 static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVector *lX, lfVector *lV, unsigned int numverts)
1434 {
1435         /* TODO: This is an initial implementation and should be made much better in due time.
1436          * What should at least be implemented is a grid size parameter and a smoothing kernel
1437          * for bigger grids.
1438          */
1439
1440         /* 10x10x10 grid gives nice initial results */
1441         HairGridVert grid[10][10][10];
1442         HairGridVert colg[10][10][10];
1443         ListBase *colliders = get_collider_cache(clmd->scene, NULL, NULL);
1444         ColliderCache *col = NULL;
1445         float gmin[3], gmax[3], density;
1446         /* 2.0f is an experimental value that seems to give good results */
1447         float smoothfac = 2.0f * clmd->sim_parms->velocity_smooth;
1448         float collfac = 2.0f * clmd->sim_parms->collider_friction;
1449         unsigned int    v = 0;
1450         unsigned int    i = 0;
1451         int                             j = 0;
1452         int                             k = 0;
1453
1454         INIT_MINMAX(gmin, gmax);
1455
1456         for(i = 0; i < numverts; i++)
1457                 DO_MINMAX(lX[i], gmin, gmax);
1458
1459         /* initialize grid */
1460         for(i = 0; i < 10; i++) {
1461                 for(j = 0; j < 10; j++) {
1462                         for(k = 0; k < 10; k++) {
1463                                 grid[i][j][k].velocity[0] = 0.0f;
1464                                 grid[i][j][k].velocity[1] = 0.0f;
1465                                 grid[i][j][k].velocity[2] = 0.0f;
1466                                 grid[i][j][k].density = 0.0f;
1467
1468                                 colg[i][j][k].velocity[0] = 0.0f;
1469                                 colg[i][j][k].velocity[1] = 0.0f;
1470                                 colg[i][j][k].velocity[2] = 0.0f;
1471                                 colg[i][j][k].density = 0.0f;
1472                         }
1473                 }
1474         }
1475
1476         /* gather velocities & density */
1477         if(smoothfac > 0.0f) for(v = 0; v < numverts; v++) {
1478                 i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
1479                 j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
1480                 k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
1481                 if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
1482                         continue;
1483
1484                 grid[i][j][k].velocity[0] += lV[v][0];
1485                 grid[i][j][k].velocity[1] += lV[v][1];
1486                 grid[i][j][k].velocity[2] += lV[v][2];
1487                 grid[i][j][k].density += 1.0f;
1488         }
1489
1490         /* gather colliders */
1491         if(colliders && collfac > 0.0f) for(col = colliders->first; col; col = col->next)
1492         {
1493                 MVert *loc0 = col->collmd->x;
1494                 MVert *loc1 = col->collmd->xnew;
1495                 float vel[3];
1496
1497                 for(v=0; v<col->collmd->numverts; v++, loc0++, loc1++) {
1498                         i = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 0);
1499
1500                         if(i>=0 && i<10) {
1501                                 j = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 1);
1502
1503                                 if(j>=0 && j<10) {
1504                                         k = HAIR_GRID_INDEX(loc1->co, gmin, gmax, 2);
1505
1506                                         if(k>=0 && k<10) {
1507                                                 VECSUB(vel, loc1->co, loc0->co);
1508
1509                                                 colg[i][j][k].velocity[0] += vel[0];
1510                                                 colg[i][j][k].velocity[1] += vel[1];
1511                                                 colg[i][j][k].velocity[2] += vel[2];
1512                                                 colg[i][j][k].density += 1.0;
1513                                         }
1514                                 }
1515                         }
1516                 }
1517         }
1518         
1519
1520         /* divide velocity with density */
1521         for(i = 0; i < 10; i++) {
1522                 for(j = 0; j < 10; j++) {
1523                         for(k = 0; k < 10; k++) {
1524                                 density = grid[i][j][k].density;
1525                                 if(density > 0.0f) {
1526                                         grid[i][j][k].velocity[0] /= density;
1527                                         grid[i][j][k].velocity[1] /= density;
1528                                         grid[i][j][k].velocity[2] /= density;
1529                                 }
1530
1531                                 density = colg[i][j][k].density;
1532                                 if(density > 0.0f) {
1533                                         colg[i][j][k].velocity[0] /= density;
1534                                         colg[i][j][k].velocity[1] /= density;
1535                                         colg[i][j][k].velocity[2] /= density;
1536                                 }
1537                         }
1538                 }
1539         }
1540
1541         /* calculate forces */
1542         for(v = 0; v < numverts; v++) {
1543                 i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0);
1544                 j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1);
1545                 k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2);
1546                 if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10)
1547                         continue;
1548
1549                 lF[v][0] += smoothfac * (grid[i][j][k].velocity[0] - lV[v][0]);
1550                 lF[v][1] += smoothfac * (grid[i][j][k].velocity[1] - lV[v][1]);
1551                 lF[v][2] += smoothfac * (grid[i][j][k].velocity[2] - lV[v][2]);
1552
1553                 if(colg[i][j][k].density > 0.0f) {
1554                         lF[v][0] += collfac * (colg[i][j][k].velocity[0] - lV[v][0]);
1555                         lF[v][1] += collfac * (colg[i][j][k].velocity[1] - lV[v][1]);
1556                         lF[v][2] += collfac * (colg[i][j][k].velocity[2] - lV[v][2]);
1557                 }
1558         }
1559
1560         free_collider_cache(&colliders);
1561 }
1562
1563 static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVector *lF, lfVector *lX, lfVector *lV, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, ListBase *effectors, float time, fmatrix3x3 *M)
1564 {
1565         /* Collect forces and derivatives:  F,dFdX,dFdV */
1566         Cloth           *cloth          = clmd->clothObject;
1567         unsigned int i  = 0;
1568         float           spring_air      = clmd->sim_parms->Cvi * 0.01f; /* viscosity of air scaled in percent */
1569         float           gravity[3] = {0.0f, 0.0f, 0.0f};
1570         float           tm2[3][3]       = {{0}};
1571         MFace           *mfaces         = cloth->mfaces;
1572         unsigned int numverts = cloth->numverts;
1573         LinkNode *search;
1574         lfVector *winvec;
1575         EffectedPoint epoint;
1576
1577         tm2[0][0]= tm2[1][1]= tm2[2][2]= -spring_air;
1578         
1579         /* global acceleration (gravitation) */
1580         if(clmd->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) {
1581                 VECCOPY(gravity, clmd->scene->physics_settings.gravity);
1582                 mul_fvector_S(gravity, gravity, 0.001f * clmd->sim_parms->effector_weights->global_gravity); /* scale gravity force */
1583         }
1584
1585         /* set dFdX jacobi matrix to zero */
1586         init_bfmatrix(dFdX, ZERO);
1587         /* set dFdX jacobi matrix diagonal entries to -spring_air */ 
1588         initdiag_bfmatrix(dFdV, tm2);
1589
1590         init_lfvector(lF, gravity, numverts);
1591         
1592         if(clmd->sim_parms->velocity_smooth > 0.0f || clmd->sim_parms->collider_friction > 0.0f)
1593                 hair_velocity_smoothing(clmd, lF, lX, lV, numverts);
1594
1595         /* multiply lF with mass matrix
1596         // force = mass * acceleration (in this case: gravity)
1597         */
1598         for(i = 0; i < numverts; i++)
1599         {
1600                 float temp[3];
1601                 VECCOPY(temp, lF[i]);
1602                 mul_fmatrix_fvector(lF[i], M[i].m, temp);
1603         }
1604
1605         submul_lfvectorS(lF, lV, spring_air, numverts);
1606         
1607         /* handle external forces like wind */
1608         if(effectors)
1609         {       
1610                 // 0 = force, 1 = normalized force
1611                 winvec = create_lfvector(cloth->numverts);
1612                 
1613                 if(!winvec)
1614                         printf("winvec: out of memory in implicit.c\n");
1615                 
1616                 // precalculate wind forces
1617                 for(i = 0; i < cloth->numverts; i++)
1618                 {       
1619                         pd_point_from_loc(clmd->scene, (float*)lX[i], (float*)lV[i], i, &epoint);
1620                         pdDoEffectors(effectors, NULL, clmd->sim_parms->effector_weights, &epoint, winvec[i], NULL);
1621                 }
1622                 
1623                 for(i = 0; i < cloth->numfaces; i++)
1624                 {
1625                         float trinormal[3]={0,0,0}; // normalized triangle normal
1626                         float triunnormal[3]={0,0,0}; // not-normalized-triangle normal
1627                         float tmp[3]={0,0,0};
1628                         float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0;
1629                         factor *= 0.02;
1630                         
1631                         // calculate face normal
1632                         if(mfaces[i].v4)
1633                                 CalcFloat4(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],lX[mfaces[i].v4],triunnormal);
1634                         else
1635                                 CalcFloat(lX[mfaces[i].v1],lX[mfaces[i].v2],lX[mfaces[i].v3],triunnormal);
1636
1637                         normalize_v3_v3(trinormal, triunnormal);
1638                         
1639                         // add wind from v1
1640                         VECCOPY(tmp, trinormal);
1641                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v1], triunnormal));
1642                         VECADDS(lF[mfaces[i].v1], lF[mfaces[i].v1], tmp, factor);
1643                         
1644                         // add wind from v2
1645                         VECCOPY(tmp, trinormal);
1646                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v2], triunnormal));
1647                         VECADDS(lF[mfaces[i].v2], lF[mfaces[i].v2], tmp, factor);
1648                         
1649                         // add wind from v3
1650                         VECCOPY(tmp, trinormal);
1651                         mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v3], triunnormal));
1652                         VECADDS(lF[mfaces[i].v3], lF[mfaces[i].v3], tmp, factor);
1653                         
1654                         // add wind from v4
1655                         if(mfaces[i].v4)
1656                         {
1657                                 VECCOPY(tmp, trinormal);
1658                                 mul_v3_fl(tmp, calculateVertexWindForce(winvec[mfaces[i].v4], triunnormal));
1659                                 VECADDS(lF[mfaces[i].v4], lF[mfaces[i].v4], tmp, factor);
1660                         }
1661                 }
1662
1663                 /* Hair has only edges */
1664                 if(cloth->numfaces == 0) {
1665                         ClothSpring *spring;
1666                         float edgevec[3]={0,0,0}; //edge vector
1667                         float edgeunnormal[3]={0,0,0}; // not-normalized-edge normal
1668                         float tmp[3]={0,0,0};
1669                         float factor = 0.01;
1670
1671                         search = cloth->springs;
1672                         while(search) {
1673                                 spring = search->link;
1674                                 
1675                                 if(spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) {
1676                                         VECSUB(edgevec, (float*)lX[spring->ij], (float*)lX[spring->kl]);
1677
1678                                         project_v3_v3v3(tmp, winvec[spring->ij], edgevec);
1679                                         VECSUB(edgeunnormal, winvec[spring->ij], tmp);
1680                                         /* hair doesn't stretch too much so we can use restlen pretty safely */
1681                                         VECADDS(lF[spring->ij], lF[spring->ij], edgeunnormal, spring->restlen * factor);
1682
1683                                         project_v3_v3v3(tmp, winvec[spring->kl], edgevec);
1684                                         VECSUB(edgeunnormal, winvec[spring->kl], tmp);
1685                                         VECADDS(lF[spring->kl], lF[spring->kl], edgeunnormal, spring->restlen * factor);
1686                                 }
1687
1688                                 search = search->next;
1689                         }
1690                 }
1691
1692                 del_lfvector(winvec);
1693         }
1694                 
1695         // calculate spring forces
1696         search = cloth->springs;
1697         while(search)
1698         {
1699                 // only handle active springs
1700                 // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED)){}
1701                 cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time);
1702
1703                 search = search->next;
1704         }
1705         
1706         // apply spring forces
1707         search = cloth->springs;
1708         while(search)
1709         {
1710                 // only handle active springs
1711                 // if(((clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED) && !(springs[i].flags & CSPRING_FLAG_DEACTIVATE))|| !(clmd->sim_parms->flags & CSIMSETT_FLAG_TEARING_ENABLED))  
1712                 cloth_apply_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX);
1713                 search = search->next;
1714         }
1715         // printf("\n");
1716 }
1717
1718 static void simulate_implicit_euler(lfVector *Vnew, lfVector *UNUSED(lX), lfVector *lV, lfVector *lF, fmatrix3x3 *dFdV, fmatrix3x3 *dFdX, float dt, fmatrix3x3 *A, lfVector *B, lfVector *dV, fmatrix3x3 *S, lfVector *z, lfVector *olddV, fmatrix3x3 *UNUSED(P), fmatrix3x3 *UNUSED(Pinv), fmatrix3x3 *M, fmatrix3x3 *UNUSED(bigI))
1719 {
1720         unsigned int numverts = dFdV[0].vcount;
1721
1722         lfVector *dFdXmV = create_lfvector(numverts);
1723         zero_lfvector(dV, numverts);
1724         
1725         cp_bfmatrix(A, M);
1726         
1727         subadd_bfmatrixS_bfmatrixS(A, dFdV, dt, dFdX, (dt*dt));
1728
1729         mul_bfmatrix_lfvector(dFdXmV, dFdX, lV);
1730
1731         add_lfvectorS_lfvectorS(B, lF, dt, dFdXmV, (dt*dt), numverts);
1732         
1733         itstart();
1734         
1735         cg_filtered(dV, A, B, z, S); /* conjugate gradient algorithm to solve Ax=b */
1736         // cg_filtered_pre(dV, A, B, z, S, P, Pinv, bigI);
1737         
1738         itend();
1739         // printf("cg_filtered calc time: %f\n", (float)itval());
1740         
1741         cp_lfvector(olddV, dV, numverts);
1742
1743         // advance velocities
1744         add_lfvector_lfvector(Vnew, lV, dV, numverts);
1745         
1746
1747         del_lfvector(dFdXmV);
1748 }
1749
1750 /*computes where the cloth would be if it were subject to perfectly stiff edges
1751   (edge distance constraints) in a lagrangian solver.  then add forces to help
1752   guide the implicit solver to that state.  this function is called after
1753   collisions*/
1754 int cloth_calc_helper_forces(Object *UNUSED(ob), ClothModifierData * clmd, float (*initial_cos)[3], float UNUSED(step), float dt)
1755 {
1756         Cloth *cloth= clmd->clothObject;
1757         float (*cos)[3] = MEM_callocN(sizeof(float)*3*cloth->numverts, "cos cloth_calc_helper_forces");
1758         float *masses = MEM_callocN(sizeof(float)*cloth->numverts, "cos cloth_calc_helper_forces");
1759         LinkNode *node;
1760         ClothSpring *spring;
1761         ClothVertex *cv;
1762         int i, steps;
1763         
1764         cv = cloth->verts;
1765         for (i=0; i<cloth->numverts; i++, cv++) {
1766                 copy_v3_v3(cos[i], cv->tx);
1767                 
1768                 if (cv->goal == 1.0f || len_v3v3(initial_cos[i], cv->tx) != 0.0) {
1769                         masses[i] = 1e+10;      
1770                 } else {
1771                         masses[i] = cv->mass;
1772                 }
1773         }
1774         
1775         steps = 55;
1776         for (i=0; i<steps; i++) {
1777                 for (node=cloth->springs; node; node=node->next) {
1778                         /* ClothVertex *cv1, *cv2; */ /* UNUSED */
1779                         int v1, v2;
1780                         float len, c, l, vec[3];
1781                         
1782                         spring = node->link;
1783                         if (spring->type != CLOTH_SPRING_TYPE_STRUCTURAL && spring->type != CLOTH_SPRING_TYPE_SHEAR) 
1784                                 continue;
1785                         
1786                         v1 = spring->ij; v2 = spring->kl;
1787                         /* cv1 = cloth->verts + v1; */ /* UNUSED */
1788                         /* cv2 = cloth->verts + v2; */ /* UNUSED */
1789                         len = len_v3v3(cos[v1], cos[v2]);
1790                         
1791                         sub_v3_v3v3(vec, cos[v1], cos[v2]);
1792                         normalize_v3(vec);
1793                         
1794                         c = (len - spring->restlen);
1795                         if (c == 0.0)
1796                                 continue;
1797                         
1798                         l = c / ((1.0/masses[v1]) + (1.0/masses[v2]));
1799                         
1800                         mul_v3_fl(vec, -(1.0/masses[v1])*l);
1801                         add_v3_v3(cos[v1], vec);
1802         
1803                         sub_v3_v3v3(vec, cos[v2], cos[v1]);
1804                         normalize_v3(vec);
1805                         
1806                         mul_v3_fl(vec, -(1.0/masses[v2])*l);
1807                         add_v3_v3(cos[v2], vec);
1808                 }
1809         }
1810         
1811         cv = cloth->verts;
1812         for (i=0; i<cloth->numverts; i++, cv++) {
1813                 float vec[3];
1814                 
1815                 /*compute forces*/
1816                 sub_v3_v3v3(vec, cos[i], cv->tx);
1817                 mul_v3_fl(vec, cv->mass*dt*20.0f);
1818                 add_v3_v3(cv->tv, vec);
1819                 //copy_v3_v3(cv->tx, cos[i]);
1820         }
1821         
1822         MEM_freeN(cos);
1823         MEM_freeN(masses);
1824         
1825         return 1;
1826 }
1827 int implicit_solver (Object *ob, float frame, ClothModifierData *clmd, ListBase *effectors)
1828 {
1829         unsigned int i=0;
1830         float step=0.0f, tf=clmd->sim_parms->timescale;
1831         Cloth *cloth = clmd->clothObject;
1832         ClothVertex *verts = cloth->verts, *cv;
1833         unsigned int numverts = cloth->numverts;
1834         float dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame;
1835         float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale;
1836         float (*initial_cos)[3] = MEM_callocN(sizeof(float)*3*cloth->numverts, "initial_cos implicit.c");
1837         Implicit_Data *id = cloth->implicit;
1838         int do_extra_solve;
1839
1840         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) /* do goal stuff */
1841         {
1842                 for(i = 0; i < numverts; i++)
1843                 {                       
1844                         // update velocities with constrained velocities from pinned verts
1845                         if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
1846                         {                       
1847                                 VECSUB(id->V[i], verts[i].xconst, verts[i].xold);
1848                                 // mul_v3_fl(id->V[i], clmd->sim_parms->stepsPerFrame);
1849                         }
1850                 }       
1851         }
1852         
1853         while(step < tf)
1854         {       
1855                 // damping velocity for artistic reasons
1856                 mul_lfvectorS(id->V, id->V, clmd->sim_parms->vel_damping, numverts);
1857
1858                 // calculate forces
1859                 cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step, id->M);
1860                 
1861                 // calculate new velocity
1862                 simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
1863                 
1864                 // advance positions
1865                 add_lfvector_lfvectorS(id->Xnew, id->X, id->Vnew, dt, numverts);
1866                 
1867                 /* move pinned verts to correct position */
1868                 for(i = 0; i < numverts; i++)
1869                 {       
1870                         if(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) 
1871                         {                       
1872                                 if(verts [i].flags & CLOTH_VERT_FLAG_PINNED)
1873                                 {                       
1874                                         float tvect[3] = {.0,.0,.0};
1875                                         VECSUB(tvect, verts[i].xconst, verts[i].xold);
1876                                         mul_fvector_S(tvect, tvect, step+dt);
1877                                         VECADD(tvect, tvect, verts[i].xold);
1878                                         VECCOPY(id->Xnew[i], tvect);
1879                                 }       
1880                         }
1881                         
1882                         VECCOPY(verts[i].txold, id->X[i]);
1883                 }
1884
1885                 if(clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_ENABLED && clmd->clothObject->bvhtree)
1886                 {
1887                         // collisions 
1888                         // itstart();
1889                         
1890                         // update verts to current positions
1891                         for(i = 0; i < numverts; i++)
1892                         {
1893                                 VECCOPY(verts[i].tx, id->Xnew[i]);
1894
1895                                 VECSUB(verts[i].tv, verts[i].tx, verts[i].txold);
1896                                 VECCOPY(verts[i].v, verts[i].tv);
1897                         }
1898
1899                         for (i=0, cv=cloth->verts; i<cloth->numverts; i++, cv++) {
1900                                 copy_v3_v3(initial_cos[i], cv->tx);
1901                         }
1902                         
1903                         // call collision function
1904                         // TODO: check if "step" or "step+dt" is correct - dg
1905                         do_extra_solve = cloth_bvh_objcollision(ob, clmd, step/clmd->sim_parms->timescale, dt/clmd->sim_parms->timescale);
1906                                                 
1907                         // copy corrected positions back to simulation
1908                         for(i = 0; i < numverts; i++)
1909                         {               
1910                                 // correct velocity again, just to be sure we had to change it due to adaptive collisions
1911                                 VECSUB(verts[i].tv, verts[i].tx, id->X[i]);
1912                         }
1913
1914                         //if (do_extra_solve)
1915                         //      cloth_calc_helper_forces(ob, clmd, initial_cos, step/clmd->sim_parms->timescale, dt/clmd->sim_parms->timescale);
1916                         
1917                         for(i = 0; i < numverts; i++)
1918                         {               
1919
1920                                 if(do_extra_solve)
1921                                 {
1922                                         
1923                                         if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
1924                                                 continue;
1925
1926                                         VECCOPY(id->Xnew[i], verts[i].tx);
1927                                         VECCOPY(id->Vnew[i], verts[i].tv);
1928                                         mul_v3_fl(id->Vnew[i], spf);
1929                                 }
1930                         }
1931                         
1932                         // X = Xnew;
1933                         cp_lfvector(id->X, id->Xnew, numverts);
1934
1935                         // if there were collisions, advance the velocity from v_n+1/2 to v_n+1
1936                         
1937                         if(do_extra_solve)
1938                         {
1939                                 // V = Vnew;
1940                                 cp_lfvector(id->V, id->Vnew, numverts);
1941
1942                                 // calculate 
1943                                 cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M);      
1944                                 
1945                                 simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI);
1946                         }
1947                 }
1948                 else
1949                 {
1950                         // X = Xnew;
1951                         cp_lfvector(id->X, id->Xnew, numverts);
1952                 }
1953                 
1954                 // itend();
1955                 // printf("collision time: %f\n", (float)itval());
1956                 
1957                 // V = Vnew;
1958                 cp_lfvector(id->V, id->Vnew, numverts);
1959                 
1960                 step += dt;
1961         }
1962
1963         for(i = 0; i < numverts; i++)
1964         {                               
1965                 if((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) && (verts [i].flags & CLOTH_VERT_FLAG_PINNED))
1966                 {
1967                         VECCOPY(verts[i].txold, verts[i].xconst); // TODO: test --> should be .x 
1968                         VECCOPY(verts[i].x, verts[i].xconst);
1969                         VECCOPY(verts[i].v, id->V[i]);
1970                 }
1971                 else
1972                 {
1973                         VECCOPY(verts[i].txold, id->X[i]);
1974                         VECCOPY(verts[i].x, id->X[i]);
1975                         VECCOPY(verts[i].v, id->V[i]);
1976                 }
1977         }
1978         
1979         MEM_freeN(initial_cos);
1980         
1981         return 1;
1982 }
1983
1984 void implicit_set_positions (ClothModifierData *clmd)
1985 {
1986         Cloth *cloth = clmd->clothObject;
1987         ClothVertex *verts = cloth->verts;
1988         unsigned int numverts = cloth->numverts, i;
1989         Implicit_Data *id = cloth->implicit;
1990         
1991         for(i = 0; i < numverts; i++)
1992         {                               
1993                 VECCOPY(id->X[i], verts[i].x);
1994                 VECCOPY(id->V[i], verts[i].v);
1995         }
1996         if(G.rt > 0)
1997                 printf("implicit_set_positions\n");     
1998 }
1999