Patch from Timothy Baldridge
[blender.git] / source / blender / blenkernel / intern / shrinkwrap.c
1 /**
2  * shrinkwrap.c
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): AndrĂ© Pinto
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29 #include <string.h>
30 #include <float.h>
31 #include <math.h>
32 #include <memory.h>
33 #include <stdio.h>
34 #include <time.h>
35 #include <assert.h>
36
37 #include "DNA_object_types.h"
38 #include "DNA_modifier_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_mesh_types.h"
41
42 #include "BKE_shrinkwrap.h"
43 #include "BKE_DerivedMesh.h"
44 #include "BKE_utildefines.h"
45 #include "BKE_deform.h"
46 #include "BKE_cdderivedmesh.h"
47 #include "BKE_displist.h"
48 #include "BKE_global.h"
49 #include "BKE_subsurf.h"
50
51 #include "BLI_arithb.h"
52 #include "BLI_kdtree.h"
53 #include "BLI_kdopbvh.h"
54
55 #include "RE_raytrace.h"
56 #include "MEM_guardedalloc.h"
57
58
59 /* Util macros */
60 #define TO_STR(a)       #a
61 #define JOIN(a,b)       a##b
62
63 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
64
65 /* Benchmark macros */
66 #if !defined(_WIN32) && 0
67
68 #include <sys/time.h>
69
70 #define BENCH(a)        \
71         do {                    \
72                 double _t1, _t2;                                \
73                 struct timeval _tstart, _tend;  \
74                 clock_t _clock_init = clock();  \
75                 gettimeofday ( &_tstart, NULL); \
76                 (a);                                                    \
77                 gettimeofday ( &_tend, NULL);   \
78                 _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );    \
79                 _t2 = ( double )   _tend.tv_sec + ( double )   _tend.tv_usec/ ( 1000*1000 );    \
80                 printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
81         } while(0)
82
83 #else
84
85 #define BENCH(a)        (a)
86
87 #endif
88
89 typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
90
91 /* get derived mesh */
92 //TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
93 DerivedMesh *object_get_derived_final(Object *ob, CustomDataMask dataMask)
94 {
95         if (ob==G.obedit)
96         {
97                 DerivedMesh *final = NULL;
98                 editmesh_get_derived_cage_and_final(&final, dataMask);
99                 return final;
100         }
101         else
102                 return mesh_get_derived_final(ob, dataMask);
103 }
104
105 /* Space transform */
106 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
107 {
108         float itarget[4][4];
109         Mat4Invert(itarget, target);
110         Mat4MulSerie(data->local2target, itarget, local, 0, 0, 0, 0, 0, 0);
111         Mat4Invert(data->target2local, data->local2target);
112 }
113
114 void space_transform_apply(const SpaceTransform *data, float *co)
115 {
116         VecMat4MulVecfl(co, ((SpaceTransform*)data)->local2target, co);
117 }
118
119 void space_transform_invert(const SpaceTransform *data, float *co)
120 {
121         VecMat4MulVecfl(co, ((SpaceTransform*)data)->target2local, co);
122 }
123
124 void space_transform_apply_normal(const SpaceTransform *data, float *no)
125 {
126         Mat4Mul3Vecfl( ((SpaceTransform*)data)->local2target, no);
127         Normalize(no); // TODO: could we just determine de scale value from the matrix?
128 }
129
130 void space_transform_invert_normal(const SpaceTransform *data, float *no)
131 {
132         Mat4Mul3Vecfl(((SpaceTransform*)data)->target2local, no);
133         Normalize(no); // TODO: could we just determine de scale value from the matrix?
134 }
135
136 /*
137  * Returns the squared distance between two given points
138  */
139 static float squared_dist(const float *a, const float *b)
140 {
141         float tmp[3];
142         VECSUB(tmp, a, b);
143         return INPR(tmp, tmp);
144 }
145
146 /* Main shrinkwrap function */
147 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
148 {
149
150         ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
151
152         //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
153         if(smd->target == ob) smd->target = NULL;
154         if(smd->auxTarget == ob) smd->auxTarget = NULL;
155
156
157         //Configure Shrinkwrap calc data
158         calc.smd = smd;
159         calc.ob = ob;
160         calc.original = dm;
161         calc.numVerts = numVerts;
162         calc.vertexCos = vertexCos;
163
164         if(smd->target)
165         {
166                 //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
167                 calc.target = CDDM_copy( object_get_derived_final(smd->target, CD_MASK_BAREMESH) );
168
169                 //TODO there might be several "bugs" on non-uniform scales matrixs.. because it will no longer be nearest surface, not sphere projection
170                 //because space has been deformed
171                 space_transform_setup(&calc.local2target, ob, smd->target);
172
173                 calc.keepDist = smd->keepDist;  //TODO: smd->keepDist is in global units.. must change to local
174         }
175
176
177         //Projecting target defined - lets work!
178         if(calc.target)
179         {
180                 switch(smd->shrinkType)
181                 {
182                         case MOD_SHRINKWRAP_NEAREST_SURFACE:
183                                 BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
184                         break;
185
186                         case MOD_SHRINKWRAP_PROJECT:
187                                 BENCH(shrinkwrap_calc_normal_projection(&calc));
188                         break;
189
190                         case MOD_SHRINKWRAP_NEAREST_VERTEX:
191                                 BENCH(shrinkwrap_calc_nearest_vertex(&calc));
192                         break;
193                 }
194         }
195
196         //free memory
197         if(calc.target)
198                 calc.target->release( calc.target );
199 }
200
201 /*
202  * Shrinkwrap to the nearest vertex
203  *
204  * it builds a kdtree of vertexs we can attach to and then
205  * for each vertex performs a nearest vertex search on the tree
206  */
207 void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
208 {
209         int i;
210         const int vgroup                 = get_named_vertexgroup_num(calc->ob, calc->smd->vgroup_name);
211         MDeformVert *const dvert = calc->original ? calc->original->getVertDataArray(calc->original, CD_MDEFORMVERT) : NULL;
212
213         BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
214         BVHTreeNearest  nearest  = NULL_BVHTreeNearest;
215
216
217         BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
218         if(treeData.tree == NULL)
219         {
220                 OUT_OF_MEMORY();
221                 return;
222         }
223
224         //Setup nearest
225         nearest.index = -1;
226         nearest.dist = FLT_MAX;
227
228 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
229         for(i = 0; i<calc->numVerts; ++i)
230         {
231                 float *co = calc->vertexCos[i];
232                 float tmp_co[3];
233                 float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
234                 if(weight == 0.0f) continue;
235
236                 VECCOPY(tmp_co, co);
237                 space_transform_apply(&calc->local2target, tmp_co); //Convert the coordinates to the tree coordinates
238
239                 //Use local proximity heuristics (to reduce the nearest search)
240                 //
241                 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
242                 //so we can initiate the "nearest.dist" with the expected value to that last hit.
243                 //This will lead in prunning of the search tree.
244                 if(nearest.index != -1)
245                         nearest.dist = squared_dist(tmp_co, nearest.co);
246                 else
247                         nearest.dist = FLT_MAX;
248
249                 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
250
251
252                 //Found the nearest vertex
253                 if(nearest.index != -1)
254                 {
255                         //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
256                         float dist = sasqrt(nearest.dist);
257                         if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
258
259                         //Convert the coordinates back to mesh coordinates
260                         VECCOPY(tmp_co, nearest.co);
261                         space_transform_invert(&calc->local2target, tmp_co);
262
263                         VecLerpf(co, co, tmp_co, weight);       //linear interpolation
264                 }
265         }
266
267         free_bvhtree_from_mesh(&treeData);
268 }
269
270 /*
271  * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
272  * Returns TRUE if "hit" was updated.
273  * Opts control whether an hit is valid or not
274  * Supported options are:
275  *      MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
276  *      MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
277  */
278 int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
279 {
280         float tmp_co[3], tmp_no[3];
281         const float *co, *no;
282         BVHTreeRayHit hit_tmp;
283
284         //Copy from hit (we need to convert hit rays from one space coordinates to the other
285         memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
286
287         //Apply space transform (TODO readjust dist)
288         if(transf)
289         {
290                 VECCOPY( tmp_co, vert );
291                 space_transform_apply( transf, tmp_co );
292                 co = tmp_co;
293
294                 VECCOPY( tmp_no, dir );
295                 space_transform_apply_normal( transf, tmp_no );
296                 no = tmp_no;
297
298                 hit_tmp.dist *= Mat4ToScalef( ((SpaceTransform*)transf)->local2target );
299         }
300         else
301         {
302                 co = vert;
303                 no = dir;
304         }
305
306         hit_tmp.index = -1;
307
308         BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
309
310         if(hit_tmp.index != -1)
311         {
312                 float dot = INPR( dir, hit_tmp.no);
313
314                 if(((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f)
315                 || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
316                         return FALSE; //Ignore hit
317
318
319                 //Inverting space transform (TODO make coeherent with the initial dist readjust)
320                 if(transf)
321                 {
322                         space_transform_invert( transf, hit_tmp.co );
323                         space_transform_invert_normal( transf, hit_tmp.no );
324
325                         hit_tmp.dist = VecLenf( (float*)vert, hit_tmp.co );
326                 }
327
328                 memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
329                 return TRUE;
330         }
331         return FALSE;
332 }
333
334
335 void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
336 {
337         int i;
338
339         //Options about projection direction
340         const char use_normal    = calc->smd->shrinkOpts;
341         float proj_axis[3] = {0.0f, 0.0f, 0.0f};
342         MVert *vert  = NULL; //Needed in case of vertex normal
343         DerivedMesh* ss_mesh = NULL;
344
345         //Vertex group data
346         const int vgroup                   = get_named_vertexgroup_num(calc->ob, calc->smd->vgroup_name);
347         const MDeformVert *dvert = calc->original ? calc->original->getVertDataArray(calc->original, CD_MDEFORMVERT) : NULL;
348
349
350         //Raycast and tree stuff
351         BVHTreeRayHit hit;
352         BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;        //target
353
354         //auxiliar target
355         DerivedMesh * aux_mesh = NULL;
356         BVHTreeFromMesh auxData= NULL_BVHTreeFromMesh;
357         SpaceTransform local2aux;
358
359 do
360 {
361
362         //Prepare data to retrieve the direction in which we should project each vertex
363         if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
364         {
365                 //No Mvert information: jump to "free memory and return" part
366                 if(calc->original == NULL) break;
367
368                 if(calc->smd->subsurfLevels)
369                 {
370                         SubsurfModifierData smd;
371                         memset(&smd, 0, sizeof(smd));
372                         smd.subdivType = ME_CC_SUBSURF;                 //catmull clark
373                         smd.levels = calc->smd->subsurfLevels;  //levels
374
375                         ss_mesh = subsurf_make_derived_from_derived(calc->original, &smd, FALSE, NULL, 0, 0);
376
377                         if(ss_mesh)
378                         {
379                                 vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
380                                 if(vert)
381                                 {
382                                         //TRICKY: this code assumes subsurface will have the transformed original vertices
383                                         //in their original order at the end of the vert array.
384                                         vert = vert
385                                                  + ss_mesh->getNumVerts(ss_mesh)
386                                                  - calc->original->getNumVerts(calc->original);
387                                 }
388                         }
389
390                         //To make sure we are not letting any memory behind
391                         assert(smd.emCache == NULL);
392                         assert(smd.mCache == NULL);
393                 }
394                 else
395                         vert = calc->original->getVertDataArray(calc->original, CD_MVERT);
396
397                 //Not able to get vert information: jump to "free memory and return" part
398                 if(vert == NULL) break;
399         }
400         else
401         {
402                 //The code supports any axis that is a combination of X,Y,Z.. altought currently UI only allows to set the 3 diferent axis
403                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
404                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
405                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
406
407                 Normalize(proj_axis);
408
409                 //Invalid projection direction: jump to "free memory and return" part
410                 if(INPR(proj_axis, proj_axis) < FLT_EPSILON) break; 
411         }
412
413         //If the user doesn't allows to project in any direction of projection axis... then theres nothing todo.
414         if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
415                 break; //jump to "free memory and return" part
416
417
418         //Build target tree
419         BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, calc->keepDist, 4, 6));
420         if(treeData.tree == NULL)
421                 break; //jump to "free memory and return" part
422
423
424         //Build auxiliar target
425         if(calc->smd->auxTarget)
426         {
427                 space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
428
429                 aux_mesh = CDDM_copy( object_get_derived_final(calc->smd->auxTarget, CD_MASK_BAREMESH) );               //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
430                 if(aux_mesh)
431                         BENCH(bvhtree_from_mesh_faces(&auxData, aux_mesh, 0.0, 4, 6));
432                 else
433                         printf("Auxiliar target finalDerived mesh is null\n");
434         }
435
436
437         //Now, everything is ready to project the vertexs!
438 #pragma omp parallel for private(i,hit) schedule(static)
439         for(i = 0; i<calc->numVerts; ++i)
440         {
441                 float *co = calc->vertexCos[i];
442                 float tmp_co[3], tmp_no[3];
443                 float lim = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
444                 float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
445
446                 if(weight == 0.0f) continue;
447
448                 if(ss_mesh)
449                 {
450                         VECCOPY(tmp_co, vert[i].co);
451                 }
452                 else
453                 {
454                         VECCOPY(tmp_co, co);
455                 }
456
457
458                 if(vert)
459                         NormalShortToFloat(tmp_no, vert[i].no);
460                 else
461                         VECCOPY( tmp_no, proj_axis );
462
463
464                 hit.index = -1;
465                 hit.dist = lim;
466
467
468                 //Project over positive direction of axis
469                 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
470                 {
471
472                         if(auxData.tree)
473                                 normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
474
475                         normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
476                 }
477
478                 //Project over negative direction of axis
479                 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)
480                 {
481                         float inv_no[3] = { -tmp_no[0], -tmp_no[1], -tmp_no[2] };
482
483
484                         if(auxData.tree)
485                                 normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
486
487                         normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
488                 }
489
490
491                 if(hit.index != -1)
492                 {
493                         VecLerpf(co, co, hit.co, weight);
494                 }
495         }
496
497
498 //Simple do{} while(0) structure to allow to easily jump to the "free memory and return" part
499 } while(0);
500
501         //free data structures
502
503         free_bvhtree_from_mesh(&treeData);
504         free_bvhtree_from_mesh(&auxData);
505
506         if(aux_mesh)
507                 aux_mesh->release(aux_mesh);
508
509         if(ss_mesh)
510                 ss_mesh->release(ss_mesh);
511 }
512
513 /*
514  * Shrinkwrap moving vertexs to the nearest surface point on the target
515  *
516  * it builds a BVHTree from the target mesh and then performs a
517  * NN matchs for each vertex
518  */
519 void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
520 {
521         int i;
522
523         const int vgroup = get_named_vertexgroup_num(calc->ob, calc->smd->vgroup_name);
524         const MDeformVert *const dvert = calc->original ? calc->original->getVertDataArray(calc->original, CD_MDEFORMVERT) : NULL;
525
526         BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
527         BVHTreeNearest  nearest  = NULL_BVHTreeNearest;
528
529
530
531         //Create a bvh-tree of the given target
532         BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
533         if(treeData.tree == NULL)
534         {
535                 OUT_OF_MEMORY();
536                 return;
537         }
538
539         //Setup nearest
540         nearest.index = -1;
541         nearest.dist = FLT_MAX;
542
543
544         //Find the nearest vertex
545 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
546         for(i = 0; i<calc->numVerts; ++i)
547         {
548                 float *co = calc->vertexCos[i];
549                 float tmp_co[3];
550                 float weight = vertexgroup_get_vertex_weight(dvert, i, vgroup);
551                 if(weight == 0.0f) continue;
552
553                 //Convert the vertex to tree coordinates
554                 VECCOPY(tmp_co, co);
555                 space_transform_apply(&calc->local2target, tmp_co);
556
557                 //Use local proximity heuristics (to reduce the nearest search)
558                 //
559                 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
560                 //so we can initiate the "nearest.dist" with the expected value to that last hit.
561                 //This will lead in prunning of the search tree.
562                 if(nearest.index != -1)
563                         nearest.dist = squared_dist(tmp_co, nearest.co);
564                 else
565                         nearest.dist = FLT_MAX;
566
567                 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
568
569                 //Found the nearest vertex
570                 if(nearest.index != -1)
571                 {
572                         if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
573                         {
574                                 //Make the vertex stay on the front side of the face
575                                 VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
576                         }
577                         else
578                         {
579                                 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
580                                 float dist = sasqrt( nearest.dist );
581                                 if(dist > FLT_EPSILON)
582                                         VecLerpf(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist);     //linear interpolation
583                                 else
584                                         VECCOPY( tmp_co, nearest.co );
585                         }
586
587                         //Convert the coordinates back to mesh coordinates
588                         space_transform_invert(&calc->local2target, tmp_co);
589                         VecLerpf(co, co, tmp_co, weight);       //linear interpolation
590                 }
591         }
592
593
594         free_bvhtree_from_mesh(&treeData);
595 }
596