4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * The Original Code is Copyright (C) Blender Foundation.
21 * All rights reserved.
23 * The Original Code is: all of this file.
25 * Contributor(s): Andr Pinto
27 * ***** END GPL LICENSE BLOCK *****
30 /** \file blender/blenkernel/intern/shrinkwrap.c
42 #include "DNA_object_types.h"
43 #include "DNA_modifier_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_scene_types.h"
48 #include "BLI_editVert.h"
50 #include "BLI_utildefines.h"
52 #include "BKE_shrinkwrap.h"
53 #include "BKE_DerivedMesh.h"
54 #include "BKE_lattice.h"
56 #include "BKE_deform.h"
58 #include "BKE_subsurf.h"
61 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
63 /* Benchmark macros */
64 #if !defined(_WIN32) && 0
71 struct timeval _tstart, _tend; \
72 clock_t _clock_init = clock(); \
73 gettimeofday ( &_tstart, NULL); \
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);\
87 typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
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)
94 EditMesh *em = BKE_mesh_get_editmesh(me);
97 DerivedMesh *dm = em->derivedFinal;
98 BKE_mesh_end_editmesh(me, em);
102 return ob->derivedFinal;
105 /* Space transform */
106 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[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);
114 void space_transform_apply(const SpaceTransform *data, float *co)
116 mul_v3_m4v3(co, ((SpaceTransform*)data)->local2target, co);
119 void space_transform_invert(const SpaceTransform *data, float *co)
121 mul_v3_m4v3(co, ((SpaceTransform*)data)->target2local, co);
124 static void space_transform_apply_normal(const SpaceTransform *data, float *no)
126 mul_mat3_m4_v3( ((SpaceTransform*)data)->local2target, no);
127 normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
130 static void space_transform_invert_normal(const SpaceTransform *data, float *no)
132 mul_mat3_m4_v3(((SpaceTransform*)data)->target2local, no);
133 normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
137 * Returns the squared distance between two given points
139 static float squared_dist(const float *a, const float *b)
143 return INPR(tmp, tmp);
147 * Shrinkwrap to the nearest vertex
149 * it builds a kdtree of vertexs we can attach to and then
150 * for each vertex performs a nearest vertex search on the tree
152 static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
156 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
157 BVHTreeNearest nearest = NULL_BVHTreeNearest;
160 BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
161 if(treeData.tree == NULL)
169 nearest.dist = FLT_MAX;
171 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
173 for(i = 0; i<calc->numVerts; ++i)
175 float *co = calc->vertexCos[i];
177 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
178 if(weight == 0.0f) continue;
181 //Convert the vertex to tree coordinates
184 VECCOPY(tmp_co, calc->vert[i].co);
190 space_transform_apply(&calc->local2target, tmp_co);
192 //Use local proximity heuristics (to reduce the nearest search)
194 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
195 //so we can initiate the "nearest.dist" with the expected value to that last hit.
196 //This will lead in prunning of the search tree.
197 if(nearest.index != -1)
198 nearest.dist = squared_dist(tmp_co, nearest.co);
200 nearest.dist = FLT_MAX;
202 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
205 //Found the nearest vertex
206 if(nearest.index != -1)
208 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
209 float dist = sasqrt(nearest.dist);
210 if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
212 //Convert the coordinates back to mesh coordinates
213 VECCOPY(tmp_co, nearest.co);
214 space_transform_invert(&calc->local2target, tmp_co);
216 interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
220 free_bvhtree_from_mesh(&treeData);
224 * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
225 * Returns TRUE if "hit" was updated.
226 * Opts control whether an hit is valid or not
227 * Supported options are:
228 * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
229 * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
231 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)
233 float tmp_co[3], tmp_no[3];
234 const float *co, *no;
235 BVHTreeRayHit hit_tmp;
237 //Copy from hit (we need to convert hit rays from one space coordinates to the other
238 memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
240 //Apply space transform (TODO readjust dist)
243 VECCOPY( tmp_co, vert );
244 space_transform_apply( transf, tmp_co );
247 VECCOPY( tmp_no, dir );
248 space_transform_apply_normal( transf, tmp_no );
251 hit_tmp.dist *= mat4_to_scale( ((SpaceTransform*)transf)->local2target );
261 BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
263 if(hit_tmp.index != -1) {
264 /* invert the normal first so face culling works on rotated objects */
266 space_transform_invert_normal(transf, hit_tmp.no);
269 if (options & (MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE|MOD_SHRINKWRAP_CULL_TARGET_BACKFACE)) {
271 const float dot= dot_v3v3(dir, hit_tmp.no);
272 if( ((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) ||
273 ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f)
275 return FALSE; /* Ignore hit */
280 /* Inverting space transform (TODO make coeherent with the initial dist readjust) */
281 space_transform_invert(transf, hit_tmp.co);
282 hit_tmp.dist = len_v3v3((float *)vert, hit_tmp.co);
285 memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
292 static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
296 //Options about projection direction
297 const char use_normal = calc->smd->shrinkOpts;
298 float proj_axis[3] = {0.0f, 0.0f, 0.0f};
300 //Raycast and tree stuff
302 BVHTreeFromMesh treeData= NULL_BVHTreeFromMesh;
305 DerivedMesh *auxMesh = NULL;
306 BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh;
307 SpaceTransform local2aux;
309 //If the user doesn't allows to project in any direction of projection axis
310 //then theres nothing todo.
311 if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
315 //Prepare data to retrieve the direction in which we should project each vertex
316 if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
318 if(calc->vert == NULL) return;
322 //The code supports any axis that is a combination of X,Y,Z
323 //altought currently UI only allows to set the 3 diferent axis
324 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
325 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
326 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
328 normalize_v3(proj_axis);
330 //Invalid projection direction
331 if(INPR(proj_axis, proj_axis) < FLT_EPSILON)
335 if(calc->smd->auxTarget)
337 auxMesh = object_get_derived_final(calc->smd->auxTarget);
340 space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
343 //After sucessufuly build the trees, start projection vertexs
344 if( bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 4, 6)
345 && (auxMesh == NULL || bvhtree_from_mesh_faces(&auxData, auxMesh, 0.0, 4, 6)))
349 #pragma omp parallel for private(i,hit) schedule(static)
351 for(i = 0; i<calc->numVerts; ++i)
353 float *co = calc->vertexCos[i];
354 float tmp_co[3], tmp_no[3];
355 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
357 if(weight == 0.0f) continue;
361 /* calc->vert contains verts from derivedMesh */
362 /* this coordinated are deformed by vertexCos only for normal projection (to get correct normals) */
363 /* for other cases calc->varts contains undeformed coordinates and vertexCos should be used */
364 if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
365 VECCOPY(tmp_co, calc->vert[i].co);
366 normal_short_to_float_v3(tmp_no, calc->vert[i].no);
369 VECCOPY(tmp_no, proj_axis);
375 VECCOPY(tmp_no, proj_axis);
380 hit.dist = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
382 //Project over positive direction of axis
383 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
387 normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
389 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
392 //Project over negative direction of axis
393 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR && hit.index == -1)
396 negate_v3_v3(inv_no, tmp_no);
399 normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
401 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
407 madd_v3_v3v3fl(hit.co, hit.co, tmp_no, calc->keepDist);
408 interp_v3_v3v3(co, co, hit.co, weight);
413 //free data structures
414 free_bvhtree_from_mesh(&treeData);
415 free_bvhtree_from_mesh(&auxData);
419 * Shrinkwrap moving vertexs to the nearest surface point on the target
421 * it builds a BVHTree from the target mesh and then performs a
422 * NN matchs for each vertex
424 static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
428 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
429 BVHTreeNearest nearest = NULL_BVHTreeNearest;
431 //Create a bvh-tree of the given target
432 BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
433 if(treeData.tree == NULL)
441 nearest.dist = FLT_MAX;
444 //Find the nearest vertex
446 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
448 for(i = 0; i<calc->numVerts; ++i)
450 float *co = calc->vertexCos[i];
452 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
453 if(weight == 0.0f) continue;
455 //Convert the vertex to tree coordinates
458 VECCOPY(tmp_co, calc->vert[i].co);
464 space_transform_apply(&calc->local2target, tmp_co);
466 //Use local proximity heuristics (to reduce the nearest search)
468 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
469 //so we can initiate the "nearest.dist" with the expected value to that last hit.
470 //This will lead in prunning of the search tree.
471 if(nearest.index != -1)
472 nearest.dist = squared_dist(tmp_co, nearest.co);
474 nearest.dist = FLT_MAX;
476 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
478 //Found the nearest vertex
479 if(nearest.index != -1)
481 if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
483 //Make the vertex stay on the front side of the face
484 VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
488 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
489 float dist = sasqrt( nearest.dist );
490 if(dist > FLT_EPSILON)
491 interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist); //linear interpolation
493 VECCOPY( tmp_co, nearest.co );
496 //Convert the coordinates back to mesh coordinates
497 space_transform_invert(&calc->local2target, tmp_co);
498 interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
502 free_bvhtree_from_mesh(&treeData);
505 /* Main shrinkwrap function */
506 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
509 DerivedMesh *ss_mesh = NULL;
510 ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
512 //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
513 if(smd->target == ob) smd->target = NULL;
514 if(smd->auxTarget == ob) smd->auxTarget = NULL;
517 //Configure Shrinkwrap calc data
520 calc.numVerts = numVerts;
521 calc.vertexCos = vertexCos;
524 calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name);
527 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
529 else if(calc.ob->type == OB_LATTICE)
531 calc.dvert = lattice_get_deform_verts(calc.ob);
537 calc.target = object_get_derived_final(smd->target);
539 //TODO there might be several "bugs" on non-uniform scales matrixs
540 //because it will no longer be nearest surface, not sphere projection
541 //because space has been deformed
542 space_transform_setup(&calc.local2target, ob, smd->target);
544 //TODO: smd->keepDist is in global units.. must change to local
545 calc.keepDist = smd->keepDist;
550 calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name);
552 if(dm != NULL && smd->shrinkType == MOD_SHRINKWRAP_PROJECT)
554 //Setup arrays to get vertexs positions, normals and deform weights
555 calc.vert = dm->getVertDataArray(dm, CD_MVERT);
556 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
558 //Using vertexs positions/normals as if a subsurface was applied
559 if(smd->subsurfLevels)
561 SubsurfModifierData ssmd= {{NULL}};
562 ssmd.subdivType = ME_CC_SUBSURF; //catmull clark
563 ssmd.levels = smd->subsurfLevels; //levels
565 ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, FALSE, NULL, 0, 0, (ob->mode & OB_MODE_EDIT));
569 calc.vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
572 //TRICKY: this code assumes subsurface will have the transformed original vertices
573 //in their original order at the end of the vert array.
574 calc.vert = calc.vert + ss_mesh->getNumVerts(ss_mesh) - dm->getNumVerts(dm);
578 //Just to make sure we are not leaving any memory behind
579 assert(ssmd.emCache == NULL);
580 assert(ssmd.mCache == NULL);
584 //Projecting target defined - lets work!
587 switch(smd->shrinkType)
589 case MOD_SHRINKWRAP_NEAREST_SURFACE:
590 BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
593 case MOD_SHRINKWRAP_PROJECT:
594 BENCH(shrinkwrap_calc_normal_projection(&calc));
597 case MOD_SHRINKWRAP_NEAREST_VERTEX:
598 BENCH(shrinkwrap_calc_nearest_vertex(&calc));
605 ss_mesh->release(ss_mesh);