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