use BLI_strncpy and BLI_snprintf when the size of the string is known.
[blender.git] / source / blender / editors / armature / meshlaplacian.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) 2001-2002 by NaN Holding BV.
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  * meshlaplacian.c: Algorithms using the mesh laplacian.
27  */
28
29 /** \file blender/editors/armature/meshlaplacian.c
30  *  \ingroup edarmature
31  */
32
33
34 #include <math.h>
35 #include <string.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_object_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_scene_types.h"
43
44 #include "BLI_math.h"
45 #include "BLI_edgehash.h"
46 #include "BLI_memarena.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_string.h"
49
50 #include "BKE_DerivedMesh.h"
51 #include "BKE_modifier.h"
52
53
54 #ifdef RIGID_DEFORM
55 #include "BLI_editVert.h"
56 #include "BLI_polardecomp.h"
57 #endif
58
59 #include "ONL_opennl.h"
60
61 #include "BLO_sys_types.h" // for intptr_t support
62
63 #include "ED_mesh.h"
64 #include "ED_armature.h"
65
66 #include "meshlaplacian.h"
67
68
69 /* ************* XXX *************** */
70 static void waitcursor(int UNUSED(val)) {}
71 static void progress_bar(int UNUSED(dummy_val), const char *UNUSED(dummy)) {}
72 static void start_progress_bar(void) {}
73 static void end_progress_bar(void) {}
74 static void error(const char *str) { printf("error: %s\n", str); }
75 /* ************* XXX *************** */
76
77
78 /************************** Laplacian System *****************************/
79
80 struct LaplacianSystem {
81         NLContext context;      /* opennl context */
82
83         int totvert, totface;
84
85         float **verts;                  /* vertex coordinates */
86         float *varea;                   /* vertex weights for laplacian computation */
87         char *vpinned;                  /* vertex pinning */
88         int (*faces)[3];                /* face vertex indices */
89         float (*fweights)[3];   /* cotangent weights per face */
90
91         int areaweights;                /* use area in cotangent weights? */
92         int storeweights;               /* store cotangent weights in fweights */
93         int nlbegun;                    /* nlBegin(NL_SYSTEM/NL_MATRIX) done */
94
95         EdgeHash *edgehash;             /* edge hash for construction */
96
97         struct HeatWeighting {
98                 MFace *mface;
99                 int totvert;
100                 int totface;
101                 float (*verts)[3];      /* vertex coordinates */
102                 float (*vnors)[3];      /* vertex normals */
103
104                 float (*root)[3];       /* bone root */
105                 float (*tip)[3];        /* bone tip */
106                 float (*source)[3]; /* vertex source */
107                 int numsource;
108
109                 float *H;                       /* diagonal H matrix */
110                 float *p;                       /* values from all p vectors */
111                 float *mindist;         /* minimum distance to a bone for all vertices */
112                 
113                 BVHTree   *bvhtree;     /* ray tracing acceleration structure */
114                 MFace     **vface;      /* a face that the vertex belongs to */
115         } heat;
116
117 #ifdef RIGID_DEFORM
118         struct RigidDeformation {
119                 EditMesh *mesh;
120
121                 float (*R)[3][3];
122                 float (*rhs)[3];
123                 float (*origco)[3];
124                 int thrownerror;
125         } rigid;
126 #endif
127 };
128
129 /* Laplacian matrix construction */
130
131 /* Computation of these weights for the laplacian is based on:
132    "Discrete Differential-Geometry Operators for Triangulated 2-Manifolds",
133    Meyer et al, 2002. Section 3.5, formula (8).
134    
135    We do it a bit different by going over faces instead of going over each
136    vertex and adjacent faces, since we don't store this adjacency. Also, the
137    formulas are tweaked a bit to work for non-manifold meshes. */
138
139 static void laplacian_increase_edge_count(EdgeHash *edgehash, int v1, int v2)
140 {
141         void **p = BLI_edgehash_lookup_p(edgehash, v1, v2);
142
143         if(p)
144                 *p = (void*)((intptr_t)*p + (intptr_t)1);
145         else
146                 BLI_edgehash_insert(edgehash, v1, v2, (void*)(intptr_t)1);
147 }
148
149 static int laplacian_edge_count(EdgeHash *edgehash, int v1, int v2)
150 {
151         return (int)(intptr_t)BLI_edgehash_lookup(edgehash, v1, v2);
152 }
153
154 static float cotan_weight(float *v1, float *v2, float *v3)
155 {
156         float a[3], b[3], c[3], clen;
157
158         sub_v3_v3v3(a, v2, v1);
159         sub_v3_v3v3(b, v3, v1);
160         cross_v3_v3v3(c, a, b);
161
162         clen = len_v3(c);
163
164         if (clen == 0.0f)
165                 return 0.0f;
166         
167         return dot_v3v3(a, b)/clen;
168 }
169
170 static void laplacian_triangle_area(LaplacianSystem *sys, int i1, int i2, int i3)
171 {
172         float t1, t2, t3, len1, len2, len3, area;
173         float *varea= sys->varea, *v1, *v2, *v3;
174         int obtuse = 0;
175
176         v1= sys->verts[i1];
177         v2= sys->verts[i2];
178         v3= sys->verts[i3];
179
180         t1= cotan_weight(v1, v2, v3);
181         t2= cotan_weight(v2, v3, v1);
182         t3= cotan_weight(v3, v1, v2);
183
184         if(RAD2DEGF(angle_v3v3v3(v2, v1, v3)) > 90) obtuse= 1;
185         else if(RAD2DEGF(angle_v3v3v3(v1, v2, v3)) > 90) obtuse= 2;
186         else if(RAD2DEGF(angle_v3v3v3(v1, v3, v2)) > 90) obtuse= 3;
187
188         if (obtuse > 0) {
189                 area= area_tri_v3(v1, v2, v3);
190
191                 varea[i1] += (obtuse == 1)? area: area*0.5f;
192                 varea[i2] += (obtuse == 2)? area: area*0.5f;
193                 varea[i3] += (obtuse == 3)? area: area*0.5f;
194         }
195         else {
196                 len1= len_v3v3(v2, v3);
197                 len2= len_v3v3(v1, v3);
198                 len3= len_v3v3(v1, v2);
199
200                 t1 *= len1*len1;
201                 t2 *= len2*len2;
202                 t3 *= len3*len3;
203
204                 varea[i1] += (t2 + t3)*0.25f;
205                 varea[i2] += (t1 + t3)*0.25f;
206                 varea[i3] += (t1 + t2)*0.25f;
207         }
208 }
209
210 static void laplacian_triangle_weights(LaplacianSystem *sys, int f, int i1, int i2, int i3)
211 {
212         float t1, t2, t3;
213         float *varea= sys->varea, *v1, *v2, *v3;
214
215         v1= sys->verts[i1];
216         v2= sys->verts[i2];
217         v3= sys->verts[i3];
218
219         /* instead of *0.5 we divided by the number of faces of the edge, it still
220            needs to be verified that this is indeed the correct thing to do! */
221         t1= cotan_weight(v1, v2, v3)/laplacian_edge_count(sys->edgehash, i2, i3);
222         t2= cotan_weight(v2, v3, v1)/laplacian_edge_count(sys->edgehash, i3, i1);
223         t3= cotan_weight(v3, v1, v2)/laplacian_edge_count(sys->edgehash, i1, i2);
224
225         nlMatrixAdd(i1, i1, (t2+t3)*varea[i1]);
226         nlMatrixAdd(i2, i2, (t1+t3)*varea[i2]);
227         nlMatrixAdd(i3, i3, (t1+t2)*varea[i3]);
228
229         nlMatrixAdd(i1, i2, -t3*varea[i1]);
230         nlMatrixAdd(i2, i1, -t3*varea[i2]);
231
232         nlMatrixAdd(i2, i3, -t1*varea[i2]);
233         nlMatrixAdd(i3, i2, -t1*varea[i3]);
234
235         nlMatrixAdd(i3, i1, -t2*varea[i3]);
236         nlMatrixAdd(i1, i3, -t2*varea[i1]);
237
238         if(sys->storeweights) {
239                 sys->fweights[f][0]= t1*varea[i1];
240                 sys->fweights[f][1]= t2*varea[i2];
241                 sys->fweights[f][2]= t3*varea[i3];
242         }
243 }
244
245 static LaplacianSystem *laplacian_system_construct_begin(int totvert, int totface, int lsq)
246 {
247         LaplacianSystem *sys;
248
249         sys= MEM_callocN(sizeof(LaplacianSystem), "LaplacianSystem");
250
251         sys->verts= MEM_callocN(sizeof(float*)*totvert, "LaplacianSystemVerts");
252         sys->vpinned= MEM_callocN(sizeof(char)*totvert, "LaplacianSystemVpinned");
253         sys->faces= MEM_callocN(sizeof(int)*3*totface, "LaplacianSystemFaces");
254
255         sys->totvert= 0;
256         sys->totface= 0;
257
258         sys->areaweights= 1;
259         sys->storeweights= 0;
260
261         /* create opennl context */
262         nlNewContext();
263         nlSolverParameteri(NL_NB_VARIABLES, totvert);
264         if(lsq)
265                 nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE);
266
267         sys->context= nlGetCurrent();
268
269         return sys;
270 }
271
272 void laplacian_add_vertex(LaplacianSystem *sys, float *co, int pinned)
273 {
274         sys->verts[sys->totvert]= co;
275         sys->vpinned[sys->totvert]= pinned;
276         sys->totvert++;
277 }
278
279 void laplacian_add_triangle(LaplacianSystem *sys, int v1, int v2, int v3)
280 {
281         sys->faces[sys->totface][0]= v1;
282         sys->faces[sys->totface][1]= v2;
283         sys->faces[sys->totface][2]= v3;
284         sys->totface++;
285 }
286
287 static void laplacian_system_construct_end(LaplacianSystem *sys)
288 {
289         int (*face)[3];
290         int a, totvert=sys->totvert, totface=sys->totface;
291
292         laplacian_begin_solve(sys, 0);
293
294         sys->varea= MEM_callocN(sizeof(float)*totvert, "LaplacianSystemVarea");
295
296         sys->edgehash= BLI_edgehash_new();
297         for(a=0, face=sys->faces; a<sys->totface; a++, face++) {
298                 laplacian_increase_edge_count(sys->edgehash, (*face)[0], (*face)[1]);
299                 laplacian_increase_edge_count(sys->edgehash, (*face)[1], (*face)[2]);
300                 laplacian_increase_edge_count(sys->edgehash, (*face)[2], (*face)[0]);
301         }
302
303         if(sys->areaweights)
304                 for(a=0, face=sys->faces; a<sys->totface; a++, face++)
305                         laplacian_triangle_area(sys, (*face)[0], (*face)[1], (*face)[2]);
306         
307         for(a=0; a<totvert; a++) {
308                 if(sys->areaweights) {
309                         if(sys->varea[a] != 0.0f)
310                                 sys->varea[a]= 0.5f/sys->varea[a];
311                 }
312                 else
313                         sys->varea[a]= 1.0f;
314
315                 /* for heat weighting */
316                 if(sys->heat.H)
317                         nlMatrixAdd(a, a, sys->heat.H[a]);
318         }
319
320         if(sys->storeweights)
321                 sys->fweights= MEM_callocN(sizeof(float)*3*totface, "LaplacianFWeight");
322         
323         for(a=0, face=sys->faces; a<totface; a++, face++)
324                 laplacian_triangle_weights(sys, a, (*face)[0], (*face)[1], (*face)[2]);
325
326         MEM_freeN(sys->faces);
327         sys->faces= NULL;
328
329         if(sys->varea) {
330                 MEM_freeN(sys->varea);
331                 sys->varea= NULL;
332         }
333
334         BLI_edgehash_free(sys->edgehash, NULL);
335         sys->edgehash= NULL;
336 }
337
338 static void laplacian_system_delete(LaplacianSystem *sys)
339 {
340         if(sys->verts) MEM_freeN(sys->verts);
341         if(sys->varea) MEM_freeN(sys->varea);
342         if(sys->vpinned) MEM_freeN(sys->vpinned);
343         if(sys->faces) MEM_freeN(sys->faces);
344         if(sys->fweights) MEM_freeN(sys->fweights);
345
346         nlDeleteContext(sys->context);
347         MEM_freeN(sys);
348 }
349
350 void laplacian_begin_solve(LaplacianSystem *sys, int index)
351 {
352         int a;
353
354         if (!sys->nlbegun) {
355                 nlBegin(NL_SYSTEM);
356
357                 if(index >= 0) {
358                         for(a=0; a<sys->totvert; a++) {
359                                 if(sys->vpinned[a]) {
360                                         nlSetVariable(0, a, sys->verts[a][index]);
361                                         nlLockVariable(a);
362                                 }
363                         }
364                 }
365
366                 nlBegin(NL_MATRIX);
367                 sys->nlbegun = 1;
368         }
369 }
370
371 void laplacian_add_right_hand_side(LaplacianSystem *UNUSED(sys), int v, float value)
372 {
373         nlRightHandSideAdd(0, v, value);
374 }
375
376 int laplacian_system_solve(LaplacianSystem *sys)
377 {
378         nlEnd(NL_MATRIX);
379         nlEnd(NL_SYSTEM);
380         sys->nlbegun = 0;
381
382         //nlPrintMatrix();
383
384         return nlSolveAdvanced(NULL, NL_TRUE);
385 }
386
387 float laplacian_system_get_solution(int v)
388 {
389         return nlGetVariable(0, v);
390 }
391
392 /************************* Heat Bone Weighting ******************************/
393 /* From "Automatic Rigging and Animation of 3D Characters"
394                  Ilya Baran and Jovan Popovic, SIGGRAPH 2007 */
395
396 #define C_WEIGHT                        1.0f
397 #define WEIGHT_LIMIT_START      0.05f
398 #define WEIGHT_LIMIT_END        0.025f
399 #define DISTANCE_EPSILON        1e-4f
400
401 typedef struct BVHCallbackUserData {
402         float start[3];
403         float vec[3];
404         LaplacianSystem *sys;
405 } BVHCallbackUserData;
406
407 static void bvh_callback(void *userdata, int index, const BVHTreeRay *UNUSED(ray), BVHTreeRayHit *hit)
408 {
409         BVHCallbackUserData *data = (struct BVHCallbackUserData*)userdata;
410         MFace *mf = data->sys->heat.mface + index;
411         float (*verts)[3] = data->sys->heat.verts;
412         float lambda, uv[2], n[3], dir[3];
413
414         mul_v3_v3fl(dir, data->vec, hit->dist);
415
416         if(isect_ray_tri_v3(data->start, dir, verts[mf->v1], verts[mf->v2], verts[mf->v3], &lambda, uv)) {
417                 normal_tri_v3(n, verts[mf->v1], verts[mf->v2], verts[mf->v3]);
418                 if(lambda < 1.0f && dot_v3v3(n, data->vec) < -1e-5f) {
419                         hit->index = index;
420                         hit->dist *= lambda;
421                 }
422         }
423
424         mul_v3_v3fl(dir, data->vec, hit->dist);
425
426         if(isect_ray_tri_v3(data->start, dir, verts[mf->v1], verts[mf->v3], verts[mf->v4], &lambda, uv)) {
427                 normal_tri_v3(n, verts[mf->v1], verts[mf->v3], verts[mf->v4]);
428                 if(lambda < 1.0f && dot_v3v3(n, data->vec) < -1e-5f) {
429                         hit->index = index;
430                         hit->dist *= lambda;
431                 }
432         }
433 }
434
435 /* Raytracing for vertex to bone/vertex visibility */
436 static void heat_ray_tree_create(LaplacianSystem *sys)
437 {
438         MFace *mface = sys->heat.mface;
439         float (*verts)[3] = sys->heat.verts;
440         int totface = sys->heat.totface;
441         int totvert = sys->heat.totvert;
442         int a;
443
444         sys->heat.bvhtree = BLI_bvhtree_new(totface, 0.0f, 4, 6);
445         sys->heat.vface = MEM_callocN(sizeof(MFace*)*totvert, "HeatVFaces");
446
447         for(a=0; a<totface; a++) {
448                 MFace *mf = mface+a;
449                 float bb[6];
450
451                 INIT_MINMAX(bb, bb+3);
452                 DO_MINMAX(verts[mf->v1], bb, bb+3);
453                 DO_MINMAX(verts[mf->v2], bb, bb+3);
454                 DO_MINMAX(verts[mf->v3], bb, bb+3);
455                 if(mf->v4) {
456                         DO_MINMAX(verts[mf->v4], bb, bb+3);
457                 }
458
459                 BLI_bvhtree_insert(sys->heat.bvhtree, a, bb, 2);
460                 
461                 //Setup inverse pointers to use on isect.orig
462                 sys->heat.vface[mf->v1]= mf;
463                 sys->heat.vface[mf->v2]= mf;
464                 sys->heat.vface[mf->v3]= mf;
465                 if(mf->v4) sys->heat.vface[mf->v4]= mf;
466         }
467
468         BLI_bvhtree_balance(sys->heat.bvhtree); 
469 }
470
471 static int heat_ray_source_visible(LaplacianSystem *sys, int vertex, int source)
472 {
473         BVHTreeRayHit hit;
474         BVHCallbackUserData data;
475         MFace *mface;
476         float end[3];
477         int visible;
478
479         mface= sys->heat.vface[vertex];
480         if(!mface)
481                 return 1;
482
483         data.sys= sys;
484         copy_v3_v3(data.start, sys->heat.verts[vertex]);
485
486         if(sys->heat.root) /* bone */
487                 closest_to_line_segment_v3(end, data.start,
488                         sys->heat.root[source], sys->heat.tip[source]);
489         else /* vertex */
490                 copy_v3_v3(end, sys->heat.source[source]);
491
492         sub_v3_v3v3(data.vec, end, data.start);
493         madd_v3_v3v3fl(data.start, data.start, data.vec, 1e-5);
494         mul_v3_fl(data.vec, 1.0f - 2e-5f);
495
496         /* pass normalized vec + distance to bvh */
497         hit.index = -1;
498         hit.dist = normalize_v3(data.vec);
499
500         visible= BLI_bvhtree_ray_cast(sys->heat.bvhtree, data.start, data.vec, 0.0f, &hit, bvh_callback, (void*)&data) == -1;
501
502         return visible;
503 }
504
505 static float heat_source_distance(LaplacianSystem *sys, int vertex, int source)
506 {
507         float closest[3], d[3], dist, cosine;
508         
509         /* compute euclidian distance */
510         if(sys->heat.root) /* bone */
511                 closest_to_line_segment_v3(closest, sys->heat.verts[vertex],
512                         sys->heat.root[source], sys->heat.tip[source]);
513         else /* vertex */
514                 copy_v3_v3(closest, sys->heat.source[source]);
515
516         sub_v3_v3v3(d, sys->heat.verts[vertex], closest);
517         dist= normalize_v3(d);
518
519         /* if the vertex normal does not point along the bone, increase distance */
520         cosine= dot_v3v3(d, sys->heat.vnors[vertex]);
521
522         return dist/(0.5f*(cosine + 1.001f));
523 }
524
525 static int heat_source_closest(LaplacianSystem *sys, int vertex, int source)
526 {
527         float dist;
528
529         dist= heat_source_distance(sys, vertex, source);
530
531         if(dist <= sys->heat.mindist[vertex]*(1.0f + DISTANCE_EPSILON))
532                 if(heat_ray_source_visible(sys, vertex, source))
533                         return 1;
534                 
535         return 0;
536 }
537
538 static void heat_set_H(LaplacianSystem *sys, int vertex)
539 {
540         float dist, mindist, h;
541         int j, numclosest = 0;
542
543         mindist= 1e10;
544
545         /* compute minimum distance */
546         for(j=0; j<sys->heat.numsource; j++) {
547                 dist= heat_source_distance(sys, vertex, j);
548
549                 if(dist < mindist)
550                         mindist= dist;
551         }
552
553         sys->heat.mindist[vertex]= mindist;
554
555         /* count number of sources with approximately this minimum distance */
556         for(j=0; j<sys->heat.numsource; j++)
557                 if(heat_source_closest(sys, vertex, j))
558                         numclosest++;
559
560         sys->heat.p[vertex]= (numclosest > 0)? 1.0f/numclosest: 0.0f;
561
562         /* compute H entry */
563         if(numclosest > 0) {
564                 mindist= maxf(mindist, 1e-4f);
565                 h= numclosest*C_WEIGHT/(mindist*mindist);
566         }
567         else
568                 h= 0.0f;
569         
570         sys->heat.H[vertex]= h;
571 }
572
573 static void heat_calc_vnormals(LaplacianSystem *sys)
574 {
575         float fnor[3];
576         int a, v1, v2, v3, (*face)[3];
577
578         sys->heat.vnors= MEM_callocN(sizeof(float)*3*sys->totvert, "HeatVNors");
579
580         for(a=0, face=sys->faces; a<sys->totface; a++, face++) {
581                 v1= (*face)[0];
582                 v2= (*face)[1];
583                 v3= (*face)[2];
584
585                 normal_tri_v3( fnor,sys->verts[v1], sys->verts[v2], sys->verts[v3]);
586                 
587                 add_v3_v3(sys->heat.vnors[v1], fnor);
588                 add_v3_v3(sys->heat.vnors[v2], fnor);
589                 add_v3_v3(sys->heat.vnors[v3], fnor);
590         }
591
592         for(a=0; a<sys->totvert; a++)
593                 normalize_v3(sys->heat.vnors[a]);
594 }
595
596 static void heat_laplacian_create(LaplacianSystem *sys)
597 {
598         MFace *mface = sys->heat.mface, *mf;
599         int totface= sys->heat.totface;
600         int totvert= sys->heat.totvert;
601         int a;
602
603         /* heat specific definitions */
604         sys->heat.mindist= MEM_callocN(sizeof(float)*totvert, "HeatMinDist");
605         sys->heat.H= MEM_callocN(sizeof(float)*totvert, "HeatH");
606         sys->heat.p= MEM_callocN(sizeof(float)*totvert, "HeatP");
607
608         /* add verts and faces to laplacian */
609         for(a=0; a<totvert; a++)
610                 laplacian_add_vertex(sys, sys->heat.verts[a], 0);
611
612         for(a=0, mf=mface; a<totface; a++, mf++) {
613                 laplacian_add_triangle(sys, mf->v1, mf->v2, mf->v3);
614                 if(mf->v4)
615                         laplacian_add_triangle(sys, mf->v1, mf->v3, mf->v4);
616         }
617
618         /* for distance computation in set_H */
619         heat_calc_vnormals(sys);
620
621         for(a=0; a<totvert; a++)
622                 heat_set_H(sys, a);
623 }
624
625 static void heat_system_free(LaplacianSystem *sys)
626 {
627         BLI_bvhtree_free(sys->heat.bvhtree);
628         MEM_freeN(sys->heat.vface);
629
630         MEM_freeN(sys->heat.mindist);
631         MEM_freeN(sys->heat.H);
632         MEM_freeN(sys->heat.p);
633         MEM_freeN(sys->heat.vnors);
634 }
635
636 static float heat_limit_weight(float weight)
637 {
638         float t;
639
640         if(weight < WEIGHT_LIMIT_END) {
641                 return 0.0f;
642         }
643         else if(weight < WEIGHT_LIMIT_START) {
644                 t= (weight - WEIGHT_LIMIT_END)/(WEIGHT_LIMIT_START - WEIGHT_LIMIT_END);
645                 return t*WEIGHT_LIMIT_START;
646         }
647         else
648                 return weight;
649 }
650
651 void heat_bone_weighting(Object *ob, Mesh *me, float (*verts)[3], int numsource, bDeformGroup **dgrouplist, bDeformGroup **dgroupflip, float (*root)[3], float (*tip)[3], int *selected, const char **err_str)
652 {
653         LaplacianSystem *sys;
654         MFace *mface;
655         float solution, weight;
656         int *vertsflipped = NULL, *mask= NULL;
657         int a, totface, j, bbone, firstsegment, lastsegment;
658
659         MVert *mvert = me->mvert;
660         int use_vert_sel= FALSE;
661         int use_face_sel= FALSE;
662
663         *err_str= NULL;
664
665         /* count triangles and create mask */
666         if(     (use_face_sel= (me->editflag & ME_EDIT_PAINT_MASK) != 0) ||
667                 (use_vert_sel= ((me->editflag & ME_EDIT_VERT_SEL) != 0)))
668         {
669                 mask= MEM_callocN(sizeof(int)*me->totvert, "heat_bone_weighting mask");
670         }
671
672         for(totface=0, a=0, mface=me->mface; a<me->totface; a++, mface++) {
673                 totface++;
674                 if(mface->v4) totface++;
675
676                 /*  (added selectedVerts content for vertex mask, they used to just equal 1) */
677                 if(use_vert_sel) {
678                         mask[mface->v1]= (mvert[mface->v1].flag & SELECT) != 0;
679                         mask[mface->v2]= (mvert[mface->v2].flag & SELECT) != 0;
680                         mask[mface->v3]= (mvert[mface->v3].flag & SELECT) != 0;
681                         if(mface->v4) {
682                                 mask[mface->v4]= (mvert[mface->v4].flag & SELECT) != 0;
683                         }
684                 }
685                 else {
686                         if(use_face_sel) {
687                                 mask[mface->v1]= 1;
688                                 mask[mface->v2]= 1;
689                                 mask[mface->v3]= 1;
690                                 if(mface->v4) {
691                                         mask[mface->v4]= 1;
692                                 }
693                         }
694                 }
695         }
696
697         /* create laplacian */
698         sys = laplacian_system_construct_begin(me->totvert, totface, 1);
699
700         sys->heat.mface= me->mface;
701         sys->heat.totface= me->totface;
702         sys->heat.totvert= me->totvert;
703         sys->heat.verts= verts;
704         sys->heat.root= root;
705         sys->heat.tip= tip;
706         sys->heat.numsource= numsource;
707
708         heat_ray_tree_create(sys);
709         heat_laplacian_create(sys);
710
711         laplacian_system_construct_end(sys);
712
713         if(dgroupflip) {
714                 vertsflipped = MEM_callocN(sizeof(int)*me->totvert, "vertsflipped");
715                 for(a=0; a<me->totvert; a++)
716                         vertsflipped[a] = mesh_get_x_mirror_vert(ob, a);
717         }
718
719         /* compute weights per bone */
720         for(j=0; j<numsource; j++) {
721                 if(!selected[j])
722                         continue;
723
724                 firstsegment= (j == 0 || dgrouplist[j-1] != dgrouplist[j]);
725                 lastsegment= (j == numsource-1 || dgrouplist[j] != dgrouplist[j+1]);
726                 bbone= !(firstsegment && lastsegment);
727
728                 /* clear weights */
729                 if(bbone && firstsegment) {
730                         for(a=0; a<me->totvert; a++) {
731                                 if(mask && !mask[a])
732                                         continue;
733
734                                 ED_vgroup_vert_remove(ob, dgrouplist[j], a);
735                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0)
736                                         ED_vgroup_vert_remove(ob, dgroupflip[j], vertsflipped[a]);
737                         }
738                 }
739
740                 /* fill right hand side */
741                 laplacian_begin_solve(sys, -1);
742
743                 for(a=0; a<me->totvert; a++)
744                         if(heat_source_closest(sys, a, j))
745                                 laplacian_add_right_hand_side(sys, a,
746                                         sys->heat.H[a]*sys->heat.p[a]);
747
748                 /* solve */
749                 if(laplacian_system_solve(sys)) {
750                         /* load solution into vertex groups */
751                         for(a=0; a<me->totvert; a++) {
752                                 if(mask && !mask[a])
753                                         continue;
754
755                                 solution= laplacian_system_get_solution(a);
756                                 
757                                 if(bbone) {
758                                         if(solution > 0.0f)
759                                                 ED_vgroup_vert_add(ob, dgrouplist[j], a, solution,
760                                                         WEIGHT_ADD);
761                                 }
762                                 else {
763                                         weight= heat_limit_weight(solution);
764                                         if(weight > 0.0f)
765                                                 ED_vgroup_vert_add(ob, dgrouplist[j], a, weight,
766                                                         WEIGHT_REPLACE);
767                                         else
768                                                 ED_vgroup_vert_remove(ob, dgrouplist[j], a);
769                                 }
770
771                                 /* do same for mirror */
772                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
773                                         if(bbone) {
774                                                 if(solution > 0.0f)
775                                                         ED_vgroup_vert_add(ob, dgroupflip[j], vertsflipped[a],
776                                                                 solution, WEIGHT_ADD);
777                                         }
778                                         else {
779                                                 weight= heat_limit_weight(solution);
780                                                 if(weight > 0.0f)
781                                                         ED_vgroup_vert_add(ob, dgroupflip[j], vertsflipped[a],
782                                                                 weight, WEIGHT_REPLACE);
783                                                 else
784                                                         ED_vgroup_vert_remove(ob, dgroupflip[j], vertsflipped[a]);
785                                         }
786                                 }
787                         }
788                 }
789                 else if(*err_str == NULL) {
790                         *err_str= "Bone Heat Weighting: failed to find solution for one or more bones";
791                         break;
792                 }
793
794                 /* remove too small vertex weights */
795                 if(bbone && lastsegment) {
796                         for(a=0; a<me->totvert; a++) {
797                                 if(mask && !mask[a])
798                                         continue;
799
800                                 weight= ED_vgroup_vert_weight(ob, dgrouplist[j], a);
801                                 weight= heat_limit_weight(weight);
802                                 if(weight <= 0.0f)
803                                         ED_vgroup_vert_remove(ob, dgrouplist[j], a);
804
805                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
806                                         weight= ED_vgroup_vert_weight(ob, dgroupflip[j], vertsflipped[a]);
807                                         weight= heat_limit_weight(weight);
808                                         if(weight <= 0.0f)
809                                                 ED_vgroup_vert_remove(ob, dgroupflip[j], vertsflipped[a]);
810                                 }
811                         }
812                 }
813         }
814
815         /* free */
816         if(vertsflipped) MEM_freeN(vertsflipped);
817         if(mask) MEM_freeN(mask);
818
819         heat_system_free(sys);
820
821         laplacian_system_delete(sys);
822 }
823
824 #ifdef RIGID_DEFORM
825 /********************** As-Rigid-As-Possible Deformation ******************/
826 /* From "As-Rigid-As-Possible Surface Modeling",
827                 Olga Sorkine and Marc Alexa, ESGP 2007. */
828
829 /* investigate:
830    - transpose R in orthogonal
831    - flipped normals and per face adding
832    - move cancelling to transform, make origco pointer
833 */
834
835 static LaplacianSystem *RigidDeformSystem = NULL;
836
837 static void rigid_add_half_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
838 {
839         float e[3], e_[3];
840         int i;
841
842         sub_v3_v3v3(e, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
843         sub_v3_v3v3(e_, v1->co, v2->co);
844
845         /* formula (5) */
846         for (i=0; i<3; i++) {
847                 sys->rigid.R[v1->tmp.l][i][0] += w*e[0]*e_[i];
848                 sys->rigid.R[v1->tmp.l][i][1] += w*e[1]*e_[i];
849                 sys->rigid.R[v1->tmp.l][i][2] += w*e[2]*e_[i];
850         }
851 }
852
853 static void rigid_add_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
854 {
855         rigid_add_half_edge_to_R(sys, v1, v2, w);
856         rigid_add_half_edge_to_R(sys, v2, v1, w);
857 }
858
859 static void rigid_orthogonalize_R(float R[][3])
860 {
861         HMatrix M, Q, S;
862
863         copy_m4_m3(M, R);
864         polar_decomp(M, Q, S);
865         copy_m3_m4(R, Q);
866 }
867
868 static void rigid_add_half_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
869 {
870         /* formula (8) */
871         float Rsum[3][3], rhs[3];
872
873         if (sys->vpinned[v1->tmp.l])
874                 return;
875
876         add_m3_m3m3(Rsum, sys->rigid.R[v1->tmp.l], sys->rigid.R[v2->tmp.l]);
877         transpose_m3(Rsum);
878
879         sub_v3_v3v3(rhs, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
880         mul_m3_v3(Rsum, rhs);
881         mul_v3_fl(rhs, 0.5f);
882         mul_v3_fl(rhs, w);
883
884         add_v3_v3(sys->rigid.rhs[v1->tmp.l], rhs);
885 }
886
887 static void rigid_add_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
888 {
889         rigid_add_half_edge_to_rhs(sys, v1, v2, w);
890         rigid_add_half_edge_to_rhs(sys, v2, v1, w);
891 }
892
893 void rigid_deform_iteration()
894 {
895         LaplacianSystem *sys= RigidDeformSystem;
896         EditMesh *em;
897         EditVert *eve;
898         EditFace *efa;
899         int a, i;
900
901         if(!sys)
902                 return;
903         
904         nlMakeCurrent(sys->context);
905         em= sys->rigid.mesh;
906
907         /* compute R */
908         memset(sys->rigid.R, 0, sizeof(float)*3*3*sys->totvert);
909         memset(sys->rigid.rhs, 0, sizeof(float)*3*sys->totvert);
910
911         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
912                 rigid_add_edge_to_R(sys, efa->v1, efa->v2, sys->fweights[a][2]);
913                 rigid_add_edge_to_R(sys, efa->v2, efa->v3, sys->fweights[a][0]);
914                 rigid_add_edge_to_R(sys, efa->v3, efa->v1, sys->fweights[a][1]);
915
916                 if(efa->v4) {
917                         a++;
918                         rigid_add_edge_to_R(sys, efa->v1, efa->v3, sys->fweights[a][2]);
919                         rigid_add_edge_to_R(sys, efa->v3, efa->v4, sys->fweights[a][0]);
920                         rigid_add_edge_to_R(sys, efa->v4, efa->v1, sys->fweights[a][1]);
921                 }
922         }
923
924         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
925                 rigid_orthogonalize_R(sys->rigid.R[a]);
926                 eve->tmp.l= a;
927         }
928         
929         /* compute right hand sides for solving */
930         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
931                 rigid_add_edge_to_rhs(sys, efa->v1, efa->v2, sys->fweights[a][2]);
932                 rigid_add_edge_to_rhs(sys, efa->v2, efa->v3, sys->fweights[a][0]);
933                 rigid_add_edge_to_rhs(sys, efa->v3, efa->v1, sys->fweights[a][1]);
934
935                 if(efa->v4) {
936                         a++;
937                         rigid_add_edge_to_rhs(sys, efa->v1, efa->v3, sys->fweights[a][2]);
938                         rigid_add_edge_to_rhs(sys, efa->v3, efa->v4, sys->fweights[a][0]);
939                         rigid_add_edge_to_rhs(sys, efa->v4, efa->v1, sys->fweights[a][1]);
940                 }
941         }
942
943         /* solve for positions, for X,Y and Z separately */
944         for(i=0; i<3; i++) {
945                 laplacian_begin_solve(sys, i);
946
947                 for(a=0; a<sys->totvert; a++)
948                         if(!sys->vpinned[a])
949                                 laplacian_add_right_hand_side(sys, a, sys->rigid.rhs[a][i]);
950
951                 if(laplacian_system_solve(sys)) {
952                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
953                                 eve->co[i]= laplacian_system_get_solution(a);
954                 }
955                 else {
956                         if(!sys->rigid.thrownerror) {
957                                 error("RigidDeform: failed to find solution");
958                                 sys->rigid.thrownerror= 1;
959                         }
960                         break;
961                 }
962         }
963 }
964
965 static void rigid_laplacian_create(LaplacianSystem *sys)
966 {
967         EditMesh *em = sys->rigid.mesh;
968         EditVert *eve;
969         EditFace *efa;
970         int a;
971
972         /* add verts and faces to laplacian */
973         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
974                 laplacian_add_vertex(sys, eve->co, eve->pinned);
975                 eve->tmp.l= a;
976         }
977
978         for(efa=em->faces.first; efa; efa=efa->next) {
979                 laplacian_add_triangle(sys,
980                         efa->v1->tmp.l, efa->v2->tmp.l, efa->v3->tmp.l);
981                 if(efa->v4)
982                         laplacian_add_triangle(sys,
983                                 efa->v1->tmp.l, efa->v3->tmp.l, efa->v4->tmp.l);
984         }
985 }
986
987 void rigid_deform_begin(EditMesh *em)
988 {
989         LaplacianSystem *sys;
990         EditVert *eve;
991         EditFace *efa;
992         int a, totvert, totface;
993
994         /* count vertices, triangles */
995         for(totvert=0, eve=em->verts.first; eve; eve=eve->next)
996                 totvert++;
997
998         for(totface=0, efa=em->faces.first; efa; efa=efa->next) {
999                 totface++;
1000                 if(efa->v4) totface++;
1001         }
1002
1003         /* create laplacian */
1004         sys = laplacian_system_construct_begin(totvert, totface, 0);
1005
1006         sys->rigid.mesh= em;
1007         sys->rigid.R = MEM_callocN(sizeof(float)*3*3*totvert, "RigidDeformR");
1008         sys->rigid.rhs = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformRHS");
1009         sys->rigid.origco = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformCo");
1010
1011         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
1012                 copy_v3_v3(sys->rigid.origco[a], eve->co);
1013
1014         sys->areaweights= 0;
1015         sys->storeweights= 1;
1016
1017         rigid_laplacian_create(sys);
1018
1019         laplacian_system_construct_end(sys);
1020
1021         RigidDeformSystem = sys;
1022 }
1023
1024 void rigid_deform_end(int cancel)
1025 {
1026         LaplacianSystem *sys = RigidDeformSystem;
1027
1028         if(sys) {
1029                 EditMesh *em = sys->rigid.mesh;
1030                 EditVert *eve;
1031                 int a;
1032
1033                 if(cancel)
1034                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
1035                                 if(!eve->pinned)
1036                                         copy_v3_v3(eve->co, sys->rigid.origco[a]);
1037
1038                 if(sys->rigid.R) MEM_freeN(sys->rigid.R);
1039                 if(sys->rigid.rhs) MEM_freeN(sys->rigid.rhs);
1040                 if(sys->rigid.origco) MEM_freeN(sys->rigid.origco);
1041
1042                 /* free */
1043                 laplacian_system_delete(sys);
1044         }
1045
1046         RigidDeformSystem = NULL;
1047 }
1048 #endif
1049
1050 /************************** Harmonic Coordinates ****************************/
1051 /* From "Harmonic Coordinates for Character Articulation",
1052         Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki,
1053         SIGGRAPH 2007. */
1054
1055 #define EPSILON 0.0001f
1056
1057 #define MESHDEFORM_TAG_UNTYPED  0
1058 #define MESHDEFORM_TAG_BOUNDARY 1
1059 #define MESHDEFORM_TAG_INTERIOR 2
1060 #define MESHDEFORM_TAG_EXTERIOR 3
1061
1062 #define MESHDEFORM_LEN_THRESHOLD 1e-6f
1063
1064 #define MESHDEFORM_MIN_INFLUENCE 0.0005f
1065
1066 static int MESHDEFORM_OFFSET[7][3] =
1067                 {{0,0,0}, {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};
1068
1069 typedef struct MDefBoundIsect {
1070         float co[3], uvw[4];
1071         int nvert, v[4], facing;
1072         float len;
1073 } MDefBoundIsect;
1074
1075 typedef struct MDefBindInfluence {
1076         struct MDefBindInfluence *next;
1077         float weight;
1078         int vertex;
1079 } MDefBindInfluence;
1080
1081 typedef struct MeshDeformBind {
1082         /* grid dimensions */
1083         float min[3], max[3];
1084         float width[3], halfwidth[3];
1085         int size, size3;
1086
1087         /* meshes */
1088         DerivedMesh *cagedm;
1089         float (*cagecos)[3];
1090         float (*vertexcos)[3];
1091         int totvert, totcagevert;
1092
1093         /* grids */
1094         MemArena *memarena;
1095         MDefBoundIsect *(*boundisect)[6];
1096         int *semibound;
1097         int *tag;
1098         float *phi, *totalphi;
1099
1100         /* mesh stuff */
1101         int *inside;
1102         float *weights;
1103         MDefBindInfluence **dyngrid;
1104         float cagemat[4][4];
1105
1106         /* direct solver */
1107         int *varidx;
1108 } MeshDeformBind;
1109
1110 typedef struct MeshDeformIsect {
1111         float start[3];
1112         float vec[3];
1113         float labda;
1114
1115         void *face;
1116         int isect;
1117         float u, v;
1118         
1119 } MeshDeformIsect;
1120
1121 /* ray intersection */
1122
1123 /* our own triangle intersection, so we can fully control the epsilons and
1124  * prevent corner case from going wrong*/
1125 static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
1126         float vert1[3], float vert2[3], float *isectco, float *uvw)
1127 {
1128         float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
1129         float det,inv_det, u, v, dir[3], isectdir[3];
1130
1131         sub_v3_v3v3(dir, end, orig);
1132
1133         /* find vectors for two edges sharing vert0 */
1134         sub_v3_v3v3(edge1, vert1, vert0);
1135         sub_v3_v3v3(edge2, vert2, vert0);
1136
1137         /* begin calculating determinant - also used to calculate U parameter */
1138         cross_v3_v3v3(pvec, dir, edge2);
1139
1140         /* if determinant is near zero, ray lies in plane of triangle */
1141         det = dot_v3v3(edge1, pvec);
1142
1143         if (det == 0.0f)
1144                 return 0;
1145         inv_det = 1.0f / det;
1146
1147         /* calculate distance from vert0 to ray origin */
1148         sub_v3_v3v3(tvec, orig, vert0);
1149
1150         /* calculate U parameter and test bounds */
1151         u = dot_v3v3(tvec, pvec) * inv_det;
1152         if (u < -EPSILON || u > 1.0f+EPSILON)
1153                 return 0;
1154
1155         /* prepare to test V parameter */
1156         cross_v3_v3v3(qvec, tvec, edge1);
1157
1158         /* calculate V parameter and test bounds */
1159         v = dot_v3v3(dir, qvec) * inv_det;
1160         if (v < -EPSILON || u + v > 1.0f+EPSILON)
1161                 return 0;
1162
1163         isectco[0]= (1.0f - u - v)*vert0[0] + u*vert1[0] + v*vert2[0];
1164         isectco[1]= (1.0f - u - v)*vert0[1] + u*vert1[1] + v*vert2[1];
1165         isectco[2]= (1.0f - u - v)*vert0[2] + u*vert1[2] + v*vert2[2];
1166
1167         uvw[0]= 1.0f - u - v;
1168         uvw[1]= u;
1169         uvw[2]= v;
1170
1171         /* check if it is within the length of the line segment */
1172         sub_v3_v3v3(isectdir, isectco, orig);
1173
1174         if(dot_v3v3(dir, isectdir) < -EPSILON)
1175                 return 0;
1176         
1177         if(dot_v3v3(dir, dir) + EPSILON < dot_v3v3(isectdir, isectdir))
1178                 return 0;
1179
1180         return 1;
1181 }
1182
1183 static int meshdeform_intersect(MeshDeformBind *mdb, MeshDeformIsect *isec)
1184 {
1185         MFace *mface;
1186         float face[4][3], co[3], uvw[3], len, nor[3], end[3];
1187         int f, hit, is= 0, totface;
1188
1189         isec->labda= 1e10;
1190
1191         mface= mdb->cagedm->getFaceArray(mdb->cagedm);
1192         totface= mdb->cagedm->getNumFaces(mdb->cagedm);
1193
1194         add_v3_v3v3(end, isec->start, isec->vec);
1195
1196         for(f=0; f<totface; f++, mface++) {
1197                 copy_v3_v3(face[0], mdb->cagecos[mface->v1]);
1198                 copy_v3_v3(face[1], mdb->cagecos[mface->v2]);
1199                 copy_v3_v3(face[2], mdb->cagecos[mface->v3]);
1200
1201                 if(mface->v4) {
1202                         copy_v3_v3(face[3], mdb->cagecos[mface->v4]);
1203                         hit = meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1204
1205                         if(hit) {
1206                                 normal_tri_v3( nor,face[0], face[1], face[2]);
1207                         }
1208                         else {
1209                                 hit= meshdeform_tri_intersect(isec->start, end, face[0], face[2], face[3], co, uvw);
1210                                 normal_tri_v3( nor,face[0], face[2], face[3]);
1211                         }
1212                 }
1213                 else {
1214                         hit= meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1215                         normal_tri_v3( nor,face[0], face[1], face[2]);
1216                 }
1217
1218                 if(hit) {
1219                         len= len_v3v3(isec->start, co)/len_v3v3(isec->start, end);
1220                         if(len < isec->labda) {
1221                                 isec->labda= len;
1222                                 isec->face = mface;
1223                                 isec->isect= (dot_v3v3(isec->vec, nor) <= 0.0f);
1224                                 is= 1;
1225                         }
1226                 }
1227         }
1228
1229         return is;
1230 }
1231
1232 static MDefBoundIsect *meshdeform_ray_tree_intersect(MeshDeformBind *mdb, float *co1, float *co2)
1233 {
1234         MDefBoundIsect *isect;
1235         MeshDeformIsect isec;
1236         float (*cagecos)[3];
1237         MFace *mface;
1238         float vert[4][3], len, end[3];
1239         static float epsilon[3]= {0, 0, 0}; //1e-4, 1e-4, 1e-4};
1240
1241         /* setup isec */
1242         memset(&isec, 0, sizeof(isec));
1243         isec.labda= 1e10f;
1244
1245         add_v3_v3v3(isec.start, co1, epsilon);
1246         add_v3_v3v3(end, co2, epsilon);
1247         sub_v3_v3v3(isec.vec, end, isec.start);
1248
1249         if(meshdeform_intersect(mdb, &isec)) {
1250                 len= isec.labda;
1251                 mface=(MFace*)isec.face;
1252
1253                 /* create MDefBoundIsect */
1254                 isect= BLI_memarena_alloc(mdb->memarena, sizeof(*isect));
1255
1256                 /* compute intersection coordinate */
1257                 isect->co[0]= co1[0] + isec.vec[0]*len;
1258                 isect->co[1]= co1[1] + isec.vec[1]*len;
1259                 isect->co[2]= co1[2] + isec.vec[2]*len;
1260
1261                 isect->len= len_v3v3(co1, isect->co);
1262                 if(isect->len < MESHDEFORM_LEN_THRESHOLD)
1263                         isect->len= MESHDEFORM_LEN_THRESHOLD;
1264
1265                 isect->v[0]= mface->v1;
1266                 isect->v[1]= mface->v2;
1267                 isect->v[2]= mface->v3;
1268                 isect->v[3]= mface->v4;
1269                 isect->nvert= (mface->v4)? 4: 3;
1270
1271                 isect->facing= isec.isect;
1272
1273                 /* compute mean value coordinates for interpolation */
1274                 cagecos= mdb->cagecos;
1275                 copy_v3_v3(vert[0], cagecos[mface->v1]);
1276                 copy_v3_v3(vert[1], cagecos[mface->v2]);
1277                 copy_v3_v3(vert[2], cagecos[mface->v3]);
1278                 if(mface->v4) copy_v3_v3(vert[3], cagecos[mface->v4]);
1279                 interp_weights_poly_v3( isect->uvw,vert, isect->nvert, isect->co);
1280
1281                 return isect;
1282         }
1283
1284         return NULL;
1285 }
1286
1287 static int meshdeform_inside_cage(MeshDeformBind *mdb, float *co)
1288 {
1289         MDefBoundIsect *isect;
1290         float outside[3], start[3], dir[3];
1291         int i;
1292
1293         for(i=1; i<=6; i++) {
1294                 outside[0] = co[0] + (mdb->max[0] - mdb->min[0] + 1.0f)*MESHDEFORM_OFFSET[i][0];
1295                 outside[1] = co[1] + (mdb->max[1] - mdb->min[1] + 1.0f)*MESHDEFORM_OFFSET[i][1];
1296                 outside[2] = co[2] + (mdb->max[2] - mdb->min[2] + 1.0f)*MESHDEFORM_OFFSET[i][2];
1297
1298                 copy_v3_v3(start, co);
1299                 sub_v3_v3v3(dir, outside, start);
1300                 normalize_v3(dir);
1301                 
1302                 isect = meshdeform_ray_tree_intersect(mdb, start, outside);
1303                 if(isect && !isect->facing)
1304                         return 1;
1305         }
1306
1307         return 0;
1308 }
1309
1310 /* solving */
1311
1312 static int meshdeform_index(MeshDeformBind *mdb, int x, int y, int z, int n)
1313 {
1314         int size= mdb->size;
1315         
1316         x += MESHDEFORM_OFFSET[n][0];
1317         y += MESHDEFORM_OFFSET[n][1];
1318         z += MESHDEFORM_OFFSET[n][2];
1319
1320         if(x < 0 || x >= mdb->size)
1321                 return -1;
1322         if(y < 0 || y >= mdb->size)
1323                 return -1;
1324         if(z < 0 || z >= mdb->size)
1325                 return -1;
1326
1327         return x + y*size + z*size*size;
1328 }
1329
1330 static void meshdeform_cell_center(MeshDeformBind *mdb, int x, int y, int z, int n, float *center)
1331 {
1332         x += MESHDEFORM_OFFSET[n][0];
1333         y += MESHDEFORM_OFFSET[n][1];
1334         z += MESHDEFORM_OFFSET[n][2];
1335
1336         center[0]= mdb->min[0] + x*mdb->width[0] + mdb->halfwidth[0];
1337         center[1]= mdb->min[1] + y*mdb->width[1] + mdb->halfwidth[1];
1338         center[2]= mdb->min[2] + z*mdb->width[2] + mdb->halfwidth[2];
1339 }
1340
1341 static void meshdeform_add_intersections(MeshDeformBind *mdb, int x, int y, int z)
1342 {
1343         MDefBoundIsect *isect;
1344         float center[3], ncenter[3];
1345         int i, a;
1346
1347         a= meshdeform_index(mdb, x, y, z, 0);
1348         meshdeform_cell_center(mdb, x, y, z, 0, center);
1349
1350         /* check each outgoing edge for intersection */
1351         for(i=1; i<=6; i++) {
1352                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1353                         continue;
1354
1355                 meshdeform_cell_center(mdb, x, y, z, i, ncenter);
1356
1357                 isect= meshdeform_ray_tree_intersect(mdb, center, ncenter);
1358                 if(isect) {
1359                         mdb->boundisect[a][i-1]= isect;
1360                         mdb->tag[a]= MESHDEFORM_TAG_BOUNDARY;
1361                 }
1362         }
1363 }
1364
1365 static void meshdeform_bind_floodfill(MeshDeformBind *mdb)
1366 {
1367         int *stack, *tag= mdb->tag;
1368         int a, b, i, xyz[3], stacksize, size= mdb->size;
1369
1370         stack= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformBindStack");
1371
1372         /* we know lower left corner is EXTERIOR because of padding */
1373         tag[0]= MESHDEFORM_TAG_EXTERIOR;
1374         stack[0]= 0;
1375         stacksize= 1;
1376
1377         /* floodfill exterior tag */
1378         while(stacksize > 0) {
1379                 a= stack[--stacksize];
1380
1381                 xyz[2]= a/(size*size);
1382                 xyz[1]= (a - xyz[2]*size*size)/size;
1383                 xyz[0]= a - xyz[1]*size - xyz[2]*size*size;
1384
1385                 for(i=1; i<=6; i++) {
1386                         b= meshdeform_index(mdb, xyz[0], xyz[1], xyz[2], i);
1387
1388                         if(b != -1) {
1389                                 if(tag[b] == MESHDEFORM_TAG_UNTYPED ||
1390                                    (tag[b] == MESHDEFORM_TAG_BOUNDARY && !mdb->boundisect[a][i-1])) {
1391                                         tag[b]= MESHDEFORM_TAG_EXTERIOR;
1392                                         stack[stacksize++]= b;
1393                                 }
1394                         }
1395                 }
1396         }
1397
1398         /* other cells are interior */
1399         for(a=0; a<size*size*size; a++)
1400                 if(tag[a]==MESHDEFORM_TAG_UNTYPED)
1401                         tag[a]= MESHDEFORM_TAG_INTERIOR;
1402
1403 #if 0
1404         {
1405                 int tb, ti, te, ts;
1406                 tb= ti= te= ts= 0;
1407                 for(a=0; a<size*size*size; a++)
1408                         if(tag[a]==MESHDEFORM_TAG_BOUNDARY)
1409                                 tb++;
1410                         else if(tag[a]==MESHDEFORM_TAG_INTERIOR)
1411                                 ti++;
1412                         else if(tag[a]==MESHDEFORM_TAG_EXTERIOR) {
1413                                 te++;
1414
1415                                 if(mdb->semibound[a])
1416                                         ts++;
1417                         }
1418                 
1419                 printf("interior %d exterior %d boundary %d semi-boundary %d\n", ti, te, tb, ts);
1420         }
1421 #endif
1422
1423         MEM_freeN(stack);
1424 }
1425
1426 static float meshdeform_boundary_phi(MeshDeformBind *UNUSED(mdb), MDefBoundIsect *isect, int cagevert)
1427 {
1428         int a;
1429
1430         for(a=0; a<isect->nvert; a++)
1431                 if(isect->v[a] == cagevert)
1432                         return isect->uvw[a];
1433         
1434         return 0.0f;
1435 }
1436
1437 static float meshdeform_interp_w(MeshDeformBind *mdb, float *gridvec, float *UNUSED(vec), int UNUSED(cagevert))
1438 {
1439         float dvec[3], ivec[3], wx, wy, wz, result=0.0f;
1440         float weight, totweight= 0.0f;
1441         int i, a, x, y, z;
1442
1443         for(i=0; i<3; i++) {
1444                 ivec[i]= (int)gridvec[i];
1445                 dvec[i]= gridvec[i] - ivec[i];
1446         }
1447
1448         for(i=0; i<8; i++) {
1449                 if(i & 1) { x= ivec[0]+1; wx= dvec[0]; }
1450                 else { x= ivec[0]; wx= 1.0f-dvec[0]; } 
1451
1452                 if(i & 2) { y= ivec[1]+1; wy= dvec[1]; }
1453                 else { y= ivec[1]; wy= 1.0f-dvec[1]; } 
1454
1455                 if(i & 4) { z= ivec[2]+1; wz= dvec[2]; }
1456                 else { z= ivec[2]; wz= 1.0f-dvec[2]; } 
1457
1458                 CLAMP(x, 0, mdb->size-1);
1459                 CLAMP(y, 0, mdb->size-1);
1460                 CLAMP(z, 0, mdb->size-1);
1461
1462                 a= meshdeform_index(mdb, x, y, z, 0);
1463                 weight= wx*wy*wz;
1464                 result += weight*mdb->phi[a];
1465                 totweight += weight;
1466         }
1467
1468         if(totweight > 0.0f)
1469                 result /= totweight;
1470
1471         return result;
1472 }
1473
1474 static void meshdeform_check_semibound(MeshDeformBind *mdb, int x, int y, int z)
1475 {
1476         int i, a;
1477
1478         a= meshdeform_index(mdb, x, y, z, 0);
1479         if(mdb->tag[a] != MESHDEFORM_TAG_EXTERIOR)
1480                 return;
1481
1482         for(i=1; i<=6; i++)
1483                 if(mdb->boundisect[a][i-1]) 
1484                         mdb->semibound[a]= 1;
1485 }
1486
1487 static float meshdeform_boundary_total_weight(MeshDeformBind *mdb, int x, int y, int z)
1488 {
1489         float weight, totweight= 0.0f;
1490         int i, a;
1491
1492         a= meshdeform_index(mdb, x, y, z, 0);
1493
1494         /* count weight for neighbour cells */
1495         for(i=1; i<=6; i++) {
1496                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1497                         continue;
1498
1499                 if(mdb->boundisect[a][i-1])
1500                         weight= 1.0f/mdb->boundisect[a][i-1]->len;
1501                 else if(!mdb->semibound[a])
1502                         weight= 1.0f/mdb->width[0];
1503                 else
1504                         weight= 0.0f;
1505
1506                 totweight += weight;
1507         }
1508
1509         return totweight;
1510 }
1511
1512 static void meshdeform_matrix_add_cell(MeshDeformBind *mdb, int x, int y, int z)
1513 {
1514         MDefBoundIsect *isect;
1515         float weight, totweight;
1516         int i, a, acenter;
1517
1518         acenter= meshdeform_index(mdb, x, y, z, 0);
1519         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1520                 return;
1521
1522         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[acenter], 1.0f);
1523         
1524         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1525         for(i=1; i<=6; i++) {
1526                 a= meshdeform_index(mdb, x, y, z, i);
1527                 if(a == -1 || mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)
1528                         continue;
1529
1530                 isect= mdb->boundisect[acenter][i-1];
1531                 if (!isect) {
1532                         weight= (1.0f/mdb->width[0])/totweight;
1533                         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[a], -weight);
1534                 }
1535         }
1536 }
1537
1538 static void meshdeform_matrix_add_rhs(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1539 {
1540         MDefBoundIsect *isect;
1541         float rhs, weight, totweight;
1542         int i, a, acenter;
1543
1544         acenter= meshdeform_index(mdb, x, y, z, 0);
1545         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1546                 return;
1547
1548         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1549         for(i=1; i<=6; i++) {
1550                 a= meshdeform_index(mdb, x, y, z, i);
1551                 if(a == -1)
1552                         continue;
1553
1554                 isect= mdb->boundisect[acenter][i-1];
1555
1556                 if (isect) {
1557                         weight= (1.0f/isect->len)/totweight;
1558                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1559                         nlRightHandSideAdd(0, mdb->varidx[acenter], rhs);
1560                 }
1561         }
1562 }
1563
1564 static void meshdeform_matrix_add_semibound_phi(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1565 {
1566         MDefBoundIsect *isect;
1567         float rhs, weight, totweight;
1568         int i, a;
1569
1570         a= meshdeform_index(mdb, x, y, z, 0);
1571         if(!mdb->semibound[a])
1572                 return;
1573         
1574         mdb->phi[a]= 0.0f;
1575
1576         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1577         for(i=1; i<=6; i++) {
1578                 isect= mdb->boundisect[a][i-1];
1579
1580                 if (isect) {
1581                         weight= (1.0f/isect->len)/totweight;
1582                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1583                         mdb->phi[a] += rhs;
1584                 }
1585         }
1586 }
1587
1588 static void meshdeform_matrix_add_exterior_phi(MeshDeformBind *mdb, int x, int y, int z, int UNUSED(cagevert))
1589 {
1590         float phi, totweight;
1591         int i, a, acenter;
1592
1593         acenter= meshdeform_index(mdb, x, y, z, 0);
1594         if(mdb->tag[acenter] != MESHDEFORM_TAG_EXTERIOR || mdb->semibound[acenter])
1595                 return;
1596
1597         phi= 0.0f;
1598         totweight= 0.0f;
1599         for(i=1; i<=6; i++) {
1600                 a= meshdeform_index(mdb, x, y, z, i);
1601
1602                 if(a != -1 && mdb->semibound[a]) {
1603                         phi += mdb->phi[a];
1604                         totweight += 1.0f;
1605                 }
1606         }
1607
1608         if(totweight != 0.0f)
1609                 mdb->phi[acenter]= phi/totweight;
1610 }
1611
1612 static void meshdeform_matrix_solve(MeshDeformModifierData *mmd, MeshDeformBind *mdb)
1613 {
1614         NLContext *context;
1615         float vec[3], gridvec[3];
1616         int a, b, x, y, z, totvar;
1617         char message[256];
1618
1619         /* setup variable indices */
1620         mdb->varidx= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformDSvaridx");
1621         for(a=0, totvar=0; a<mdb->size3; a++)
1622                 mdb->varidx[a]= (mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)? -1: totvar++;
1623
1624         if(totvar == 0) {
1625                 MEM_freeN(mdb->varidx);
1626                 return;
1627         }
1628
1629         progress_bar(0, "Starting mesh deform solve");
1630
1631         /* setup opennl solver */
1632         nlNewContext();
1633         context= nlGetCurrent();
1634
1635         nlSolverParameteri(NL_NB_VARIABLES, totvar);
1636         nlSolverParameteri(NL_NB_ROWS, totvar);
1637         nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 1);
1638
1639         nlBegin(NL_SYSTEM);
1640         nlBegin(NL_MATRIX);
1641
1642         /* build matrix */
1643         for(z=0; z<mdb->size; z++)
1644                 for(y=0; y<mdb->size; y++)
1645                         for(x=0; x<mdb->size; x++)
1646                                 meshdeform_matrix_add_cell(mdb, x, y, z);
1647
1648         /* solve for each cage vert */
1649         for(a=0; a<mdb->totcagevert; a++) {
1650                 if(a != 0) {
1651                         nlBegin(NL_SYSTEM);
1652                         nlBegin(NL_MATRIX);
1653                 }
1654
1655                 /* fill in right hand side and solve */
1656                 for(z=0; z<mdb->size; z++)
1657                         for(y=0; y<mdb->size; y++)
1658                                 for(x=0; x<mdb->size; x++)
1659                                         meshdeform_matrix_add_rhs(mdb, x, y, z, a);
1660
1661                 nlEnd(NL_MATRIX);
1662                 nlEnd(NL_SYSTEM);
1663
1664 #if 0
1665                 nlPrintMatrix();
1666 #endif
1667
1668                 if(nlSolveAdvanced(NULL, NL_TRUE)) {
1669                         for(z=0; z<mdb->size; z++)
1670                                 for(y=0; y<mdb->size; y++)
1671                                         for(x=0; x<mdb->size; x++)
1672                                                 meshdeform_matrix_add_semibound_phi(mdb, x, y, z, a);
1673
1674                         for(z=0; z<mdb->size; z++)
1675                                 for(y=0; y<mdb->size; y++)
1676                                         for(x=0; x<mdb->size; x++)
1677                                                 meshdeform_matrix_add_exterior_phi(mdb, x, y, z, a);
1678
1679                         for(b=0; b<mdb->size3; b++) {
1680                                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1681                                         mdb->phi[b]= nlGetVariable(0, mdb->varidx[b]);
1682                                 mdb->totalphi[b] += mdb->phi[b];
1683                         }
1684
1685                         if(mdb->weights) {
1686                                 /* static bind : compute weights for each vertex */
1687                                 for(b=0; b<mdb->totvert; b++) {
1688                                         if(mdb->inside[b]) {
1689                                                 copy_v3_v3(vec, mdb->vertexcos[b]);
1690                                                 gridvec[0]= (vec[0] - mdb->min[0] - mdb->halfwidth[0])/mdb->width[0];
1691                                                 gridvec[1]= (vec[1] - mdb->min[1] - mdb->halfwidth[1])/mdb->width[1];
1692                                                 gridvec[2]= (vec[2] - mdb->min[2] - mdb->halfwidth[2])/mdb->width[2];
1693
1694                                                 mdb->weights[b*mdb->totcagevert + a]= meshdeform_interp_w(mdb, gridvec, vec, a);
1695                                         }
1696                                 }
1697                         }
1698                         else {
1699                                 MDefBindInfluence *inf;
1700
1701                                 /* dynamic bind */
1702                                 for(b=0; b<mdb->size3; b++) {
1703                                         if(mdb->phi[b] >= MESHDEFORM_MIN_INFLUENCE) {
1704                                                 inf= BLI_memarena_alloc(mdb->memarena, sizeof(*inf));
1705                                                 inf->vertex= a;
1706                                                 inf->weight= mdb->phi[b];
1707                                                 inf->next= mdb->dyngrid[b];
1708                                                 mdb->dyngrid[b]= inf;
1709                                         }
1710                                 }
1711                         }
1712                 }
1713                 else {
1714                         modifier_setError(&mmd->modifier, "Failed to find bind solution (increase precision?).");
1715                         error("Mesh Deform: failed to find bind solution.");
1716                         break;
1717                 }
1718
1719                 BLI_snprintf(message, sizeof(message), "Mesh deform solve %d / %d       |||", a+1, mdb->totcagevert);
1720                 progress_bar((float)(a+1)/(float)(mdb->totcagevert), message);
1721         }
1722
1723 #if 0
1724         /* sanity check */
1725         for(b=0; b<mdb->size3; b++)
1726                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1727                         if(fabs(mdb->totalphi[b] - 1.0f) > 1e-4)
1728                                 printf("totalphi deficiency [%s|%d] %d: %.10f\n",
1729                                         (mdb->tag[b] == MESHDEFORM_TAG_INTERIOR)? "interior": "boundary", mdb->semibound[b], mdb->varidx[b], mdb->totalphi[b]);
1730 #endif
1731         
1732         /* free */
1733         MEM_freeN(mdb->varidx);
1734
1735         nlDeleteContext(context);
1736 }
1737
1738 static void harmonic_coordinates_bind(Scene *UNUSED(scene), MeshDeformModifierData *mmd, MeshDeformBind *mdb)
1739 {
1740         MDefBindInfluence *inf;
1741         MDefInfluence *mdinf;
1742         MDefCell *cell;
1743         float center[3], vec[3], maxwidth, totweight;
1744         int a, b, x, y, z, totinside, offset;
1745
1746         /* compute bounding box of the cage mesh */
1747         INIT_MINMAX(mdb->min, mdb->max);
1748
1749         for(a=0; a<mdb->totcagevert; a++)
1750                 DO_MINMAX(mdb->cagecos[a], mdb->min, mdb->max);
1751
1752         /* allocate memory */
1753         mdb->size= (2<<(mmd->gridsize-1)) + 2;
1754         mdb->size3= mdb->size*mdb->size*mdb->size;
1755         mdb->tag= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformBindTag");
1756         mdb->phi= MEM_callocN(sizeof(float)*mdb->size3, "MeshDeformBindPhi");
1757         mdb->totalphi= MEM_callocN(sizeof(float)*mdb->size3, "MeshDeformBindTotalPhi");
1758         mdb->boundisect= MEM_callocN(sizeof(*mdb->boundisect)*mdb->size3, "MDefBoundIsect");
1759         mdb->semibound= MEM_callocN(sizeof(int)*mdb->size3, "MDefSemiBound");
1760
1761         mdb->inside= MEM_callocN(sizeof(int)*mdb->totvert, "MDefInside");
1762
1763         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND)
1764                 mdb->dyngrid= MEM_callocN(sizeof(MDefBindInfluence*)*mdb->size3, "MDefDynGrid");
1765         else
1766                 mdb->weights= MEM_callocN(sizeof(float)*mdb->totvert*mdb->totcagevert, "MDefWeights");
1767
1768         mdb->memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "harmonic coords arena");
1769         BLI_memarena_use_calloc(mdb->memarena);
1770
1771         /* make bounding box equal size in all directions, add padding, and compute
1772          * width of the cells */
1773         maxwidth = -1.0f;
1774         for(a=0; a<3; a++)
1775                 if(mdb->max[a]-mdb->min[a] > maxwidth)
1776                         maxwidth= mdb->max[a]-mdb->min[a];
1777
1778         for(a=0; a<3; a++) {
1779                 center[a]= (mdb->min[a]+mdb->max[a])*0.5f;
1780                 mdb->min[a]= center[a] - maxwidth*0.5f;
1781                 mdb->max[a]= center[a] + maxwidth*0.5f;
1782
1783                 mdb->width[a]= (mdb->max[a]-mdb->min[a])/(mdb->size-4);
1784                 mdb->min[a] -= 2.1f*mdb->width[a];
1785                 mdb->max[a] += 2.1f*mdb->width[a];
1786
1787                 mdb->width[a]= (mdb->max[a]-mdb->min[a])/mdb->size;
1788                 mdb->halfwidth[a]= mdb->width[a]*0.5f;
1789         }
1790
1791         progress_bar(0, "Setting up mesh deform system");
1792
1793         totinside= 0;
1794         for(a=0; a<mdb->totvert; a++) {
1795                 copy_v3_v3(vec, mdb->vertexcos[a]);
1796                 mdb->inside[a]= meshdeform_inside_cage(mdb, vec);
1797                 if(mdb->inside[a])
1798                         totinside++;
1799         }
1800
1801         /* free temporary MDefBoundIsects */
1802         BLI_memarena_free(mdb->memarena);
1803         mdb->memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "harmonic coords arena");
1804
1805         /* start with all cells untyped */
1806         for(a=0; a<mdb->size3; a++)
1807                 mdb->tag[a]= MESHDEFORM_TAG_UNTYPED;
1808         
1809         /* detect intersections and tag boundary cells */
1810         for(z=0; z<mdb->size; z++)
1811                 for(y=0; y<mdb->size; y++)
1812                         for(x=0; x<mdb->size; x++)
1813                                 meshdeform_add_intersections(mdb, x, y, z);
1814
1815         /* compute exterior and interior tags */
1816         meshdeform_bind_floodfill(mdb);
1817
1818         for(z=0; z<mdb->size; z++)
1819                 for(y=0; y<mdb->size; y++)
1820                         for(x=0; x<mdb->size; x++)
1821                                 meshdeform_check_semibound(mdb, x, y, z);
1822
1823         /* solve */
1824         meshdeform_matrix_solve(mmd, mdb);
1825
1826         /* assign results */
1827         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND) {
1828                 mmd->totinfluence= 0;
1829                 for(a=0; a<mdb->size3; a++)
1830                         for(inf=mdb->dyngrid[a]; inf; inf=inf->next)
1831                                 mmd->totinfluence++;
1832
1833                 /* convert MDefBindInfluences to smaller MDefInfluences */
1834                 mmd->dyngrid= MEM_callocN(sizeof(MDefCell)*mdb->size3, "MDefDynGrid");
1835                 mmd->dyninfluences= MEM_callocN(sizeof(MDefInfluence)*mmd->totinfluence, "MDefInfluence");
1836                 offset= 0;
1837                 for(a=0; a<mdb->size3; a++) {
1838                         cell= &mmd->dyngrid[a];
1839                         cell->offset= offset;
1840
1841                         totweight= 0.0f;
1842                         mdinf= mmd->dyninfluences + cell->offset;
1843                         for(inf=mdb->dyngrid[a]; inf; inf=inf->next, mdinf++) {
1844                                 mdinf->weight= inf->weight;
1845                                 mdinf->vertex= inf->vertex;
1846                                 totweight += mdinf->weight;
1847                                 cell->totinfluence++;
1848                         }
1849
1850                         if(totweight > 0.0f) {
1851                                 mdinf= mmd->dyninfluences + cell->offset;
1852                                 for(b=0; b<cell->totinfluence; b++, mdinf++)
1853                                         mdinf->weight /= totweight;
1854                         }
1855
1856                         offset += cell->totinfluence;
1857                 }
1858
1859                 mmd->dynverts= mdb->inside;
1860                 mmd->dyngridsize= mdb->size;
1861                 copy_v3_v3(mmd->dyncellmin, mdb->min);
1862                 mmd->dyncellwidth= mdb->width[0];
1863                 MEM_freeN(mdb->dyngrid);
1864         }
1865         else {
1866                 mmd->bindweights= mdb->weights;
1867                 MEM_freeN(mdb->inside);
1868         }
1869
1870         MEM_freeN(mdb->tag);
1871         MEM_freeN(mdb->phi);
1872         MEM_freeN(mdb->totalphi);
1873         MEM_freeN(mdb->boundisect);
1874         MEM_freeN(mdb->semibound);
1875         BLI_memarena_free(mdb->memarena);
1876 }
1877
1878 #if 0
1879 static void heat_weighting_bind(Scene *scene, DerivedMesh *dm, MeshDeformModifierData *mmd, MeshDeformBind *mdb)
1880 {
1881         LaplacianSystem *sys;
1882         MFace *mface= dm->getFaceArray(dm), *mf;
1883         int totvert= dm->getNumVerts(dm);
1884         int totface= dm->getNumFaces(dm);
1885         float solution, weight;
1886         int a, tottri, j, thrownerror = 0;
1887
1888         mdb->weights= MEM_callocN(sizeof(float)*mdb->totvert*mdb->totcagevert, "MDefWeights");
1889
1890         /* count triangles */
1891         for(tottri=0, a=0, mf=mface; a<totface; a++, mf++) {
1892                 tottri++;
1893                 if(mf->v4) tottri++;
1894         }
1895
1896         /* create laplacian */
1897         sys = laplacian_system_construct_begin(totvert, tottri, 1);
1898
1899         sys->heat.mface= mface;
1900         sys->heat.totface= totface;
1901         sys->heat.totvert= totvert;
1902         sys->heat.verts= mdb->vertexcos;
1903         sys->heat.source = mdb->cagecos;
1904         sys->heat.numsource= mdb->totcagevert;
1905
1906         heat_ray_tree_create(sys);
1907         heat_laplacian_create(sys);
1908
1909         laplacian_system_construct_end(sys);
1910
1911         /* compute weights per bone */
1912         for(j=0; j<mdb->totcagevert; j++) {
1913                 /* fill right hand side */
1914                 laplacian_begin_solve(sys, -1);
1915
1916                 for(a=0; a<totvert; a++)
1917                         if(heat_source_closest(sys, a, j))
1918                                 laplacian_add_right_hand_side(sys, a,
1919                                         sys->heat.H[a]*sys->heat.p[a]);
1920
1921                 /* solve */
1922                 if(laplacian_system_solve(sys)) {
1923                         /* load solution into vertex groups */
1924                         for(a=0; a<totvert; a++) {
1925                                 solution= laplacian_system_get_solution(a);
1926                                 
1927                                 weight= heat_limit_weight(solution);
1928                                 if(weight > 0.0f)
1929                                         mdb->weights[a*mdb->totcagevert + j] = weight;
1930                         }
1931                 }
1932                 else if(!thrownerror) {
1933                         error("Mesh Deform Heat Weighting:"
1934                                 " failed to find solution for one or more vertices");
1935                         thrownerror= 1;
1936                         break;
1937                 }
1938         }
1939
1940         /* free */
1941         heat_system_free(sys);
1942         laplacian_system_delete(sys);
1943
1944         mmd->bindweights= mdb->weights;
1945 }
1946 #endif
1947
1948 void mesh_deform_bind(Scene *scene, MeshDeformModifierData *mmd, float *vertexcos, int totvert, float cagemat[][4])
1949 {
1950         MeshDeformBind mdb;
1951         MVert *mvert;
1952         int a;
1953
1954         waitcursor(1);
1955         start_progress_bar();
1956
1957         memset(&mdb, 0, sizeof(MeshDeformBind));
1958
1959         /* get mesh and cage mesh */
1960         mdb.vertexcos= MEM_callocN(sizeof(float)*3*totvert, "MeshDeformCos");
1961         mdb.totvert= totvert;
1962         
1963         mdb.cagedm= mesh_create_derived_no_deform(scene, mmd->object, NULL, CD_MASK_BAREMESH);
1964         mdb.totcagevert= mdb.cagedm->getNumVerts(mdb.cagedm);
1965         mdb.cagecos= MEM_callocN(sizeof(*mdb.cagecos)*mdb.totcagevert, "MeshDeformBindCos");
1966         copy_m4_m4(mdb.cagemat, cagemat);
1967
1968         mvert= mdb.cagedm->getVertArray(mdb.cagedm);
1969         for(a=0; a<mdb.totcagevert; a++)
1970                 copy_v3_v3(mdb.cagecos[a], mvert[a].co);
1971         for(a=0; a<mdb.totvert; a++)
1972                 mul_v3_m4v3(mdb.vertexcos[a], mdb.cagemat, vertexcos + a*3);
1973
1974         /* solve */
1975 #if 0
1976         if(mmd->mode == MOD_MDEF_VOLUME)
1977                 harmonic_coordinates_bind(scene, mmd, &mdb);
1978         else
1979                 heat_weighting_bind(scene, dm, mmd, &mdb);
1980 #else
1981         harmonic_coordinates_bind(scene, mmd, &mdb);
1982 #endif
1983
1984         /* assign bind variables */
1985         mmd->bindcagecos= (float*)mdb.cagecos;
1986         mmd->totvert= mdb.totvert;
1987         mmd->totcagevert= mdb.totcagevert;
1988         copy_m4_m4(mmd->bindmat, mmd->object->obmat);
1989
1990         /* transform bindcagecos to world space */
1991         for(a=0; a<mdb.totcagevert; a++)
1992                 mul_m4_v3(mmd->object->obmat, mmd->bindcagecos+a*3);
1993
1994         /* free */
1995         mdb.cagedm->release(mdb.cagedm);
1996         MEM_freeN(mdb.vertexcos);
1997
1998         /* compact weights */
1999         modifier_mdef_compact_influences((ModifierData*)mmd);
2000
2001         end_progress_bar();
2002         waitcursor(0);
2003 }
2004