2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) Blender Foundation.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): Andr Pinto
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/shrinkwrap.c
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"
47 #include "BLI_utildefines.h"
49 #include "BKE_shrinkwrap.h"
50 #include "BKE_DerivedMesh.h"
51 #include "BKE_lattice.h"
53 #include "BKE_deform.h"
55 #include "BKE_subsurf.h"
57 #include "BKE_tessmesh.h"
60 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
62 /* Benchmark macros */
63 #if !defined(_WIN32) && 0
70 struct timeval _tstart, _tend; \
71 clock_t _clock_init = clock(); \
72 gettimeofday ( &_tstart, NULL); \
74 gettimeofday ( &_tend, NULL); \
75 _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \
76 _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \
77 printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
86 typedef void (*Shrinkwrap_ForeachVertexCallback)(DerivedMesh *target, float *co, float *normal);
88 /* get derived mesh */
89 //TODO is anyfunction that does this? returning the derivedFinal without we caring if its in edit mode or not?
90 DerivedMesh *object_get_derived_final(Object *ob)
93 BMEditMesh *em = me->edit_btmesh;
96 DerivedMesh *dm = em->derivedFinal;
100 return ob->derivedFinal;
103 /* Space transform */
104 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
107 invert_m4_m4(itarget, target);
108 mul_serie_m4(data->local2target, itarget, local, NULL, NULL, NULL, NULL, NULL, NULL);
109 invert_m4_m4(data->target2local, data->local2target);
112 void space_transform_apply(const SpaceTransform *data, float *co)
114 mul_v3_m4v3(co, ((SpaceTransform *)data)->local2target, co);
117 void space_transform_invert(const SpaceTransform *data, float *co)
119 mul_v3_m4v3(co, ((SpaceTransform *)data)->target2local, co);
122 static void space_transform_apply_normal(const SpaceTransform *data, float *no)
124 mul_mat3_m4_v3(((SpaceTransform *)data)->local2target, no);
125 normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
128 static void space_transform_invert_normal(const SpaceTransform *data, float *no)
130 mul_mat3_m4_v3(((SpaceTransform *)data)->target2local, no);
131 normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
135 * Shrinkwrap to the nearest vertex
137 * it builds a kdtree of vertexs we can attach to and then
138 * for each vertex performs a nearest vertex search on the tree
140 static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
144 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
145 BVHTreeNearest nearest = NULL_BVHTreeNearest;
148 BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
149 if (treeData.tree == NULL) {
156 nearest.dist = FLT_MAX;
158 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
160 for (i = 0; i < calc->numVerts; ++i) {
161 float *co = calc->vertexCos[i];
163 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
164 if (weight == 0.0f) continue;
167 //Convert the vertex to tree coordinates
169 copy_v3_v3(tmp_co, calc->vert[i].co);
172 copy_v3_v3(tmp_co, co);
174 space_transform_apply(&calc->local2target, tmp_co);
176 //Use local proximity heuristics (to reduce the nearest search)
178 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
179 //so we can initiate the "nearest.dist" with the expected value to that last hit.
180 //This will lead in prunning of the search tree.
181 if (nearest.index != -1)
182 nearest.dist = len_squared_v3v3(tmp_co, nearest.co);
184 nearest.dist = FLT_MAX;
186 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
189 //Found the nearest vertex
190 if (nearest.index != -1) {
191 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
192 float dist = sasqrt(nearest.dist);
193 if (dist > FLT_EPSILON) weight *= (dist - calc->keepDist) / dist;
195 //Convert the coordinates back to mesh coordinates
196 copy_v3_v3(tmp_co, nearest.co);
197 space_transform_invert(&calc->local2target, tmp_co);
199 interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
203 free_bvhtree_from_mesh(&treeData);
207 * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
208 * Returns TRUE if "hit" was updated.
209 * Opts control whether an hit is valid or not
210 * Supported options are:
211 * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
212 * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
214 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)
216 float tmp_co[3], tmp_no[3];
217 const float *co, *no;
218 BVHTreeRayHit hit_tmp;
220 //Copy from hit (we need to convert hit rays from one space coordinates to the other
221 memcpy(&hit_tmp, hit, sizeof(hit_tmp));
223 //Apply space transform (TODO readjust dist)
225 copy_v3_v3(tmp_co, vert);
226 space_transform_apply(transf, tmp_co);
229 copy_v3_v3(tmp_no, dir);
230 space_transform_apply_normal(transf, tmp_no);
233 hit_tmp.dist *= mat4_to_scale(((SpaceTransform *)transf)->local2target);
242 BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
244 if (hit_tmp.index != -1) {
245 /* invert the normal first so face culling works on rotated objects */
247 space_transform_invert_normal(transf, hit_tmp.no);
250 if (options & (MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE | MOD_SHRINKWRAP_CULL_TARGET_BACKFACE)) {
252 const float dot = dot_v3v3(dir, hit_tmp.no);
253 if (((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) ||
254 ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
256 return FALSE; /* Ignore hit */
261 /* Inverting space transform (TODO make coeherent with the initial dist readjust) */
262 space_transform_invert(transf, hit_tmp.co);
263 hit_tmp.dist = len_v3v3((float *)vert, hit_tmp.co);
266 memcpy(hit, &hit_tmp, sizeof(hit_tmp));
273 static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
277 //Options about projection direction
278 const char use_normal = calc->smd->shrinkOpts;
279 float proj_axis[3] = {0.0f, 0.0f, 0.0f};
281 //Raycast and tree stuff
283 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
286 DerivedMesh *auxMesh = NULL;
287 BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh;
288 SpaceTransform local2aux;
290 //If the user doesn't allows to project in any direction of projection axis
291 //then theres nothing todo.
292 if ((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
296 //Prepare data to retrieve the direction in which we should project each vertex
297 if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
298 if (calc->vert == NULL) return;
301 //The code supports any axis that is a combination of X,Y,Z
302 //although currently UI only allows to set the 3 different axis
303 if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
304 if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
305 if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
307 normalize_v3(proj_axis);
309 //Invalid projection direction
310 if (dot_v3v3(proj_axis, proj_axis) < FLT_EPSILON)
314 if (calc->smd->auxTarget) {
315 auxMesh = object_get_derived_final(calc->smd->auxTarget);
318 space_transform_setup(&local2aux, calc->ob, calc->smd->auxTarget);
321 //After sucessufuly build the trees, start projection vertexs
322 if (bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 4, 6) &&
323 (auxMesh == NULL || bvhtree_from_mesh_faces(&auxData, auxMesh, 0.0, 4, 6)))
327 #pragma omp parallel for private(i,hit) schedule(static)
329 for (i = 0; i < calc->numVerts; ++i) {
330 float *co = calc->vertexCos[i];
331 float tmp_co[3], tmp_no[3];
332 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
334 if (weight == 0.0f) continue;
337 /* calc->vert contains verts from derivedMesh */
338 /* this coordinated are deformed by vertexCos only for normal projection (to get correct normals) */
339 /* for other cases calc->varts contains undeformed coordinates and vertexCos should be used */
340 if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
341 copy_v3_v3(tmp_co, calc->vert[i].co);
342 normal_short_to_float_v3(tmp_no, calc->vert[i].no);
345 copy_v3_v3(tmp_co, co);
346 copy_v3_v3(tmp_no, proj_axis);
350 copy_v3_v3(tmp_co, co);
351 copy_v3_v3(tmp_no, proj_axis);
356 hit.dist = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that
358 //Project over positive direction of axis
359 if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR) {
362 normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
364 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
367 //Project over negative direction of axis
368 if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR && hit.index == -1) {
370 negate_v3_v3(inv_no, tmp_no);
373 normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
375 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
379 if (hit.index != -1) {
380 madd_v3_v3v3fl(hit.co, hit.co, tmp_no, calc->keepDist);
381 interp_v3_v3v3(co, co, hit.co, weight);
386 //free data structures
387 free_bvhtree_from_mesh(&treeData);
388 free_bvhtree_from_mesh(&auxData);
392 * Shrinkwrap moving vertexs to the nearest surface point on the target
394 * it builds a BVHTree from the target mesh and then performs a
395 * NN matches for each vertex
397 static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
401 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
402 BVHTreeNearest nearest = NULL_BVHTreeNearest;
404 //Create a bvh-tree of the given target
405 BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 2, 6));
406 if (treeData.tree == NULL) {
413 nearest.dist = FLT_MAX;
416 //Find the nearest vertex
418 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
420 for (i = 0; i < calc->numVerts; ++i) {
421 float *co = calc->vertexCos[i];
423 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
424 if (weight == 0.0f) continue;
426 //Convert the vertex to tree coordinates
428 copy_v3_v3(tmp_co, calc->vert[i].co);
431 copy_v3_v3(tmp_co, co);
433 space_transform_apply(&calc->local2target, tmp_co);
435 //Use local proximity heuristics (to reduce the nearest search)
437 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
438 //so we can initiate the "nearest.dist" with the expected value to that last hit.
439 //This will lead in prunning of the search tree.
440 if (nearest.index != -1)
441 nearest.dist = len_squared_v3v3(tmp_co, nearest.co);
443 nearest.dist = FLT_MAX;
445 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
447 //Found the nearest vertex
448 if (nearest.index != -1) {
449 if (calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE) {
450 //Make the vertex stay on the front side of the face
451 madd_v3_v3v3fl(tmp_co, nearest.co, nearest.no, calc->keepDist);
454 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
455 float dist = sasqrt(nearest.dist);
456 if (dist > FLT_EPSILON)
457 interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist); //linear interpolation
459 copy_v3_v3(tmp_co, nearest.co);
462 //Convert the coordinates back to mesh coordinates
463 space_transform_invert(&calc->local2target, tmp_co);
464 interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
468 free_bvhtree_from_mesh(&treeData);
471 /* Main shrinkwrap function */
472 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
475 DerivedMesh *ss_mesh = NULL;
476 ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
478 //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
479 if (smd->target == ob) smd->target = NULL;
480 if (smd->auxTarget == ob) smd->auxTarget = NULL;
483 //Configure Shrinkwrap calc data
486 calc.numVerts = numVerts;
487 calc.vertexCos = vertexCos;
490 calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name);
492 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
494 else if (calc.ob->type == OB_LATTICE) {
495 calc.dvert = BKE_lattice_deform_verts_get(calc.ob);
500 calc.target = object_get_derived_final(smd->target);
502 //TODO there might be several "bugs" on non-uniform scales matrixs
503 //because it will no longer be nearest surface, not sphere projection
504 //because space has been deformed
505 space_transform_setup(&calc.local2target, ob, smd->target);
507 //TODO: smd->keepDist is in global units.. must change to local
508 calc.keepDist = smd->keepDist;
513 calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name);
515 if (dm != NULL && smd->shrinkType == MOD_SHRINKWRAP_PROJECT) {
516 //Setup arrays to get vertexs positions, normals and deform weights
517 calc.vert = dm->getVertDataArray(dm, CD_MVERT);
518 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
520 //Using vertexs positions/normals as if a subsurface was applied
521 if (smd->subsurfLevels) {
522 SubsurfModifierData ssmd = {{NULL}};
523 ssmd.subdivType = ME_CC_SUBSURF; //catmull clark
524 ssmd.levels = smd->subsurfLevels; //levels
526 ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, NULL, (ob->mode & OB_MODE_EDIT) ? SUBSURF_IN_EDIT_MODE : 0);
529 calc.vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
531 /* TRICKY: this code assumes subsurface will have the transformed original vertices
532 * in their original order at the end of the vert array. */
533 calc.vert = calc.vert + ss_mesh->getNumVerts(ss_mesh) - dm->getNumVerts(dm);
537 //Just to make sure we are not leaving any memory behind
538 assert(ssmd.emCache == NULL);
539 assert(ssmd.mCache == NULL);
543 //Projecting target defined - lets work!
545 switch (smd->shrinkType) {
546 case MOD_SHRINKWRAP_NEAREST_SURFACE:
547 BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
550 case MOD_SHRINKWRAP_PROJECT:
551 BENCH(shrinkwrap_calc_normal_projection(&calc));
554 case MOD_SHRINKWRAP_NEAREST_VERTEX:
555 BENCH(shrinkwrap_calc_nearest_vertex(&calc));
562 ss_mesh->release(ss_mesh);