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