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