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