Merge branch 'blender2.7'
[blender.git] / source / blender / blenkernel / intern / mesh_remap.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file \ingroup bke
18  *
19  * Functions for mapping data between meshes.
20  */
21
22 #include <limits.h>
23
24 #include "CLG_log.h"
25
26 #include "MEM_guardedalloc.h"
27
28 #include "DNA_mesh_types.h"
29 #include "DNA_meshdata_types.h"
30
31 #include "BLI_utildefines.h"
32 #include "BLI_alloca.h"
33 #include "BLI_astar.h"
34 #include "BLI_bitmap.h"
35 #include "BLI_math.h"
36 #include "BLI_memarena.h"
37 #include "BLI_polyfill_2d.h"
38 #include "BLI_rand.h"
39
40 #include "BKE_bvhutils.h"
41 #include "BKE_customdata.h"
42 #include "BKE_mesh.h"
43 #include "BKE_mesh_mapping.h"
44 #include "BKE_mesh_remap.h"  /* own include */
45 #include "BKE_mesh_runtime.h"
46
47 #include "BLI_strict_flags.h"
48
49 static CLG_LogRef LOG = {"bke.mesh"};
50
51 /* -------------------------------------------------------------------- */
52 /** \name Some generic helpers.
53  * \{ */
54
55 static bool mesh_remap_bvhtree_query_nearest(
56         BVHTreeFromMesh *treedata, BVHTreeNearest *nearest,
57         const float co[3], const float max_dist_sq, float *r_hit_dist)
58 {
59         /* Use local proximity heuristics (to reduce the nearest search). */
60         if (nearest->index != -1) {
61                 nearest->dist_sq = min_ff(len_squared_v3v3(co, nearest->co), max_dist_sq);
62         }
63         else {
64                 nearest->dist_sq = max_dist_sq;
65         }
66         /* Compute and store result. If invalid (-1 index), keep FLT_MAX dist. */
67         BLI_bvhtree_find_nearest(treedata->tree, co, nearest, treedata->nearest_callback, treedata);
68
69         if ((nearest->index != -1) && (nearest->dist_sq <= max_dist_sq)) {
70                 *r_hit_dist = sqrtf(nearest->dist_sq);
71                 return true;
72         }
73         else {
74                 return false;
75         }
76 }
77
78 static bool mesh_remap_bvhtree_query_raycast(
79         BVHTreeFromMesh *treedata, BVHTreeRayHit *rayhit,
80         const float co[3], const float no[3], const float radius, const float max_dist, float *r_hit_dist)
81 {
82         BVHTreeRayHit rayhit_tmp;
83         float inv_no[3];
84
85         rayhit->index = -1;
86         rayhit->dist = max_dist;
87         BLI_bvhtree_ray_cast(treedata->tree, co, no, radius, rayhit, treedata->raycast_callback, treedata);
88
89         /* Also cast in the other direction! */
90         rayhit_tmp = *rayhit;
91         negate_v3_v3(inv_no, no);
92         BLI_bvhtree_ray_cast(treedata->tree, co, inv_no, radius, &rayhit_tmp, treedata->raycast_callback, treedata);
93         if (rayhit_tmp.dist < rayhit->dist) {
94                 *rayhit = rayhit_tmp;
95         }
96
97         if ((rayhit->index != -1) && (rayhit->dist <= max_dist)) {
98                 *r_hit_dist = rayhit->dist;
99                 return true;
100         }
101         else {
102                 return false;
103         }
104 }
105
106 /** \} */
107
108 /**
109  * \name Auto-match.
110  *
111  * Find transform of a mesh to get best match with another.
112  * \{ */
113
114 /**
115  * Compute a value of the difference between both given meshes.
116  * The smaller the result, the better the match.
117  *
118  * We return the inverse of the average of the inversed shortest distance from each dst vertex to src ones.
119  * In other words, beyond a certain (relatively small) distance, all differences have more or less the same weight
120  * in final result, which allows to reduce influence of a few high differences, in favor of a global good matching.
121  */
122 float BKE_mesh_remap_calc_difference_from_mesh(
123         const SpaceTransform *space_transform, const MVert *verts_dst, const int numverts_dst, Mesh *me_src)
124 {
125         BVHTreeFromMesh treedata = {NULL};
126         BVHTreeNearest nearest = {0};
127         float hit_dist;
128
129         float result = 0.0f;
130         int i;
131
132         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_VERTS, 2);
133         nearest.index = -1;
134
135         for (i = 0; i < numverts_dst; i++) {
136                 float tmp_co[3];
137
138                 copy_v3_v3(tmp_co, verts_dst[i].co);
139
140                 /* Convert the vertex to tree coordinates, if needed. */
141                 if (space_transform) {
142                         BLI_space_transform_apply(space_transform, tmp_co);
143                 }
144
145                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, FLT_MAX, &hit_dist)) {
146                         result += 1.0f / (hit_dist + 1.0f);
147                 }
148                 else {
149                         /* No source for this dest vertex! */
150                         result += 1e-18f;
151                 }
152         }
153
154         result = ((float)numverts_dst / result) - 1.0f;
155
156 //      printf("%s: Computed difference between meshes (the lower the better): %f\n", __func__, result);
157
158         return result;
159 }
160
161 /* This helper computes the eigen values & vectors for covariance matrix of all given vertices coordinates.
162  *
163  * Those vectors define the 'average ellipsoid' of the mesh (i.e. the 'best fitting' ellipsoid
164  * containing 50% of the vertices).
165  *
166  * Note that it will not perform fantastic in case two or more eigen values are equal (e.g. a cylinder or
167  * parallelepiped with a square section give two identical eigenvalues, a sphere or tetrahedron give
168  * three identical ones, etc.), since you cannot really define all axes in those cases. We default to dummy
169  * generated orthogonal vectors in this case, instead of using eigen vectors.
170  */
171 static void mesh_calc_eigen_matrix(
172         const MVert *verts, const float (*vcos)[3], const int numverts, float r_mat[4][4])
173 {
174         float center[3], covmat[3][3];
175         float eigen_val[3], eigen_vec[3][3];
176         float (*cos)[3] = NULL;
177
178         bool eigen_success;
179         int i;
180
181         if (verts) {
182                 const MVert *mv;
183                 float (*co)[3];
184
185                 cos = MEM_mallocN(sizeof(*cos) * (size_t)numverts, __func__);
186                 for (i = 0, co = cos, mv = verts; i < numverts; i++, co++, mv++) {
187                         copy_v3_v3(*co, mv->co);
188                 }
189                 /* TODO(sergey): For until we officially drop all compilers which
190                  * doesn't handle casting correct we use workaround to avoid explicit
191                  * cast here.
192                  */
193                 vcos = (void *)cos;
194         }
195         unit_m4(r_mat);
196
197         /* Note: here we apply sample correction to covariance matrix, since we consider the vertices as a sample
198          *       of the whole 'surface' population of our mesh... */
199         BLI_covariance_m3_v3n(vcos, numverts, true, covmat, center);
200
201         if (cos) {
202                 MEM_freeN(cos);
203         }
204
205         eigen_success = BLI_eigen_solve_selfadjoint_m3((const float (*)[3])covmat, eigen_val, eigen_vec);
206         BLI_assert(eigen_success);
207         UNUSED_VARS_NDEBUG(eigen_success);
208
209         /* Special handling of cases where some eigen values are (nearly) identical. */
210         if (compare_ff_relative(eigen_val[0], eigen_val[1], FLT_EPSILON, 64)) {
211                 if (compare_ff_relative(eigen_val[0], eigen_val[2], FLT_EPSILON, 64)) {
212                         /* No preferred direction, that set of vertices has a spherical average,
213                          * so we simply returned scaled/translated identity matrix (with no rotation). */
214                         unit_m3(eigen_vec);
215                 }
216                 else {
217                         /* Ellipsoid defined by eigen values/vectors has a spherical section,
218                          * we can only define one axis from eigen_vec[2] (two others computed eigen vecs
219                          * are not so nice for us here, they tend to 'randomly' rotate around valid one).
220                          * Note that eigen vectors as returned by BLI_eigen_solve_selfadjoint_m3() are normalized. */
221                         ortho_basis_v3v3_v3(eigen_vec[0], eigen_vec[1], eigen_vec[2]);
222                 }
223         }
224         else if (compare_ff_relative(eigen_val[0], eigen_val[2], FLT_EPSILON, 64)) {
225                 /* Same as above, but with eigen_vec[1] as valid axis. */
226                 ortho_basis_v3v3_v3(eigen_vec[2], eigen_vec[0], eigen_vec[1]);
227         }
228         else if (compare_ff_relative(eigen_val[1], eigen_val[2], FLT_EPSILON, 64)) {
229                 /* Same as above, but with eigen_vec[0] as valid axis. */
230                 ortho_basis_v3v3_v3(eigen_vec[1], eigen_vec[2], eigen_vec[0]);
231         }
232
233         for (i = 0; i < 3; i++) {
234                 float evi = eigen_val[i];
235
236                 /* Protect against 1D/2D degenerated cases! */
237                 /* Note: not sure why we need square root of eigen values here (which are equivalent to singular values,
238                  * as far as I have understood), but it seems to heavily reduce (if not completely nullify)
239                  * the error due to non-uniform scalings... */
240                 evi = (evi < 1e-6f && evi > -1e-6f) ? ((evi < 0.0f) ? -1e-3f : 1e-3f) : sqrtf_signed(evi);
241                 mul_v3_fl(eigen_vec[i], evi);
242         }
243
244         copy_m4_m3(r_mat, eigen_vec);
245         copy_v3_v3(r_mat[3], center);
246 }
247
248 /**
249  * Set r_space_transform so that best bbox of dst matches best bbox of src.
250  */
251 void BKE_mesh_remap_find_best_match_from_mesh(
252         const MVert *verts_dst, const int numverts_dst, Mesh *me_src, SpaceTransform *r_space_transform)
253 {
254         /* Note that those are done so that we successively get actual mirror matrix (by multiplication of columns)... */
255         const float mirrors[][3] = {
256             {-1.0f,  1.0f,  1.0f},  /* -> -1,  1,  1 */
257             { 1.0f, -1.0f,  1.0f},  /* -> -1, -1,  1 */
258             { 1.0f,  1.0f, -1.0f},  /* -> -1, -1, -1 */
259             { 1.0f, -1.0f,  1.0f},  /* -> -1,  1, -1 */
260             {-1.0f,  1.0f,  1.0f},  /* ->  1,  1, -1 */
261             { 1.0f, -1.0f,  1.0f},  /* ->  1, -1, -1 */
262             { 1.0f,  1.0f, -1.0f},  /* ->  1, -1,  1 */
263             {0.0f, 0.0f, 0.0f},
264         };
265         const float (*mirr)[3];
266
267         float mat_src[4][4], mat_dst[4][4], best_mat_dst[4][4];
268         float best_match = FLT_MAX, match;
269
270         const int numverts_src = me_src->totvert;
271         float (*vcos_src)[3] = BKE_mesh_vertexCos_get(me_src, NULL);
272
273         mesh_calc_eigen_matrix(NULL, (const float (*)[3])vcos_src, numverts_src, mat_src);
274         mesh_calc_eigen_matrix(verts_dst, NULL, numverts_dst, mat_dst);
275
276         BLI_space_transform_global_from_matrices(r_space_transform, mat_dst, mat_src);
277         match = BKE_mesh_remap_calc_difference_from_mesh(r_space_transform, verts_dst, numverts_dst, me_src);
278         best_match = match;
279         copy_m4_m4(best_mat_dst, mat_dst);
280
281         /* And now, we have to check the other sixth possible mirrored versions... */
282         for (mirr = mirrors; (*mirr)[0]; mirr++) {
283                 mul_v3_fl(mat_dst[0], (*mirr)[0]);
284                 mul_v3_fl(mat_dst[1], (*mirr)[1]);
285                 mul_v3_fl(mat_dst[2], (*mirr)[2]);
286
287                 BLI_space_transform_global_from_matrices(r_space_transform, mat_dst, mat_src);
288                 match = BKE_mesh_remap_calc_difference_from_mesh(r_space_transform, verts_dst, numverts_dst, me_src);
289                 if (match < best_match) {
290                         best_match = match;
291                         copy_m4_m4(best_mat_dst, mat_dst);
292                 }
293         }
294
295         BLI_space_transform_global_from_matrices(r_space_transform, best_mat_dst, mat_src);
296
297         MEM_freeN(vcos_src);
298 }
299
300 /** \} */
301
302 /** \name Mesh to mesh mapping
303  * \{ */
304
305 void BKE_mesh_remap_init(MeshPairRemap *map, const int items_num)
306 {
307         MemArena *mem = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
308
309         BKE_mesh_remap_free(map);
310
311         map->items = BLI_memarena_alloc(mem, sizeof(*map->items) * (size_t)items_num);
312         map->items_num = items_num;
313
314         map->mem = mem;
315 }
316
317 void BKE_mesh_remap_free(MeshPairRemap *map)
318 {
319         if (map->mem) {
320                 BLI_memarena_free((MemArena *)map->mem);
321         }
322
323         map->items_num = 0;
324         map->items = NULL;
325         map->mem = NULL;
326 }
327
328 static void mesh_remap_item_define(
329         MeshPairRemap *map, const int index, const float UNUSED(hit_dist), const int island,
330         const int sources_num, const int *indices_src, const float *weights_src)
331 {
332         MeshPairRemapItem *mapit = &map->items[index];
333         MemArena *mem = map->mem;
334
335         if (sources_num) {
336                 mapit->sources_num = sources_num;
337                 mapit->indices_src = BLI_memarena_alloc(mem, sizeof(*mapit->indices_src) * (size_t)sources_num);
338                 memcpy(mapit->indices_src, indices_src, sizeof(*mapit->indices_src) * (size_t)sources_num);
339                 mapit->weights_src = BLI_memarena_alloc(mem, sizeof(*mapit->weights_src) * (size_t)sources_num);
340                 memcpy(mapit->weights_src, weights_src, sizeof(*mapit->weights_src) * (size_t)sources_num);
341         }
342         else {
343                 mapit->sources_num = 0;
344                 mapit->indices_src = NULL;
345                 mapit->weights_src = NULL;
346         }
347         /* UNUSED */
348         // mapit->hit_dist = hit_dist;
349         mapit->island = island;
350 }
351
352 void BKE_mesh_remap_item_define_invalid(MeshPairRemap *map, const int index)
353 {
354         mesh_remap_item_define(map, index, FLT_MAX, 0, 0, NULL, NULL);
355 }
356
357 static int mesh_remap_interp_poly_data_get(
358         const MPoly *mp, MLoop *mloops, const float (*vcos_src)[3], const float point[3],
359         size_t *buff_size, float (**vcos)[3], const bool use_loops, int **indices, float **weights,
360         const bool do_weights, int *r_closest_index)
361 {
362         MLoop *ml;
363         float (*vco)[3];
364         float ref_dist_sq = FLT_MAX;
365         int *index;
366         const int sources_num = mp->totloop;
367         int i;
368
369         if ((size_t)sources_num > *buff_size) {
370                 *buff_size = (size_t)sources_num;
371                 *vcos = MEM_reallocN(*vcos, sizeof(**vcos) * *buff_size);
372                 *indices = MEM_reallocN(*indices, sizeof(**indices) * *buff_size);
373                 if (do_weights) {
374                         *weights = MEM_reallocN(*weights, sizeof(**weights) * *buff_size);
375                 }
376         }
377
378         for (i = 0, ml = &mloops[mp->loopstart], vco = *vcos, index = *indices; i < sources_num; i++, ml++, vco++, index++) {
379                 *index = use_loops ? (int)mp->loopstart + i : (int)ml->v;
380                 copy_v3_v3(*vco, vcos_src[ml->v]);
381                 if (r_closest_index) {
382                         /* Find closest vert/loop in this case. */
383                         const float dist_sq = len_squared_v3v3(point, *vco);
384                         if (dist_sq < ref_dist_sq) {
385                                 ref_dist_sq = dist_sq;
386                                 *r_closest_index = *index;
387                         }
388                 }
389         }
390
391         if (do_weights) {
392                 interp_weights_poly_v3(*weights, *vcos, sources_num, point);
393         }
394
395         return sources_num;
396 }
397
398 /* Little helper when dealing with source islands */
399 typedef struct IslandResult {
400         float factor;           /* A factor, based on which best island for a given set of elements will be selected. */
401         int   index_src;        /* Index of the source. */
402         float hit_dist;         /* The actual hit distance. */
403         float hit_point[3];     /* The hit point, if relevant. */
404 } IslandResult;
405
406 /* Note about all bvh/raycasting stuff below:
407  *      * We must use our ray radius as BVH epsilon too, else rays not hitting anything but 'passing near' an item
408  *        would be missed (since BVH handling would not detect them, 'refining' callbacks won't be executed,
409  *        even though they would return a valid hit).
410  *      * However, in 'islands' case where each hit gets a weight, 'precise' hits should have a better weight than
411  *        'approximate' hits. To address that, we simplify things with:
412  *        ** A first raycast with default, given rayradius;
413  *        ** If first one fails, we do more raycasting with bigger radius, but if hit is found
414  *           it will get smaller weight.
415  *        This only concerns loops, currently (because of islands), and 'sampled' edges/polys norproj.
416  */
417
418 /* At most n raycasts per 'real' ray. */
419 #define MREMAP_RAYCAST_APPROXIMATE_NR 3
420 /* Each approximated raycasts will have n times bigger radius than previous one. */
421 #define MREMAP_RAYCAST_APPROXIMATE_FAC 5.0f
422
423 /* min 16 rays/face, max 400. */
424 #define MREMAP_RAYCAST_TRI_SAMPLES_MIN 4
425 #define MREMAP_RAYCAST_TRI_SAMPLES_MAX 20
426
427 /* Will be enough in 99% of cases. */
428 #define MREMAP_DEFAULT_BUFSIZE 32
429
430 void BKE_mesh_remap_calc_verts_from_mesh(
431         const int mode, const SpaceTransform *space_transform, const float max_dist, const float ray_radius,
432         const MVert *verts_dst, const int numverts_dst, const bool UNUSED(dirty_nors_dst), Mesh *me_src,
433         MeshPairRemap *r_map)
434 {
435         const float full_weight = 1.0f;
436         const float max_dist_sq = max_dist * max_dist;
437         int i;
438
439         BLI_assert(mode & MREMAP_MODE_VERT);
440
441         BKE_mesh_remap_init(r_map, numverts_dst);
442
443         if (mode == MREMAP_MODE_TOPOLOGY) {
444                 BLI_assert(numverts_dst == me_src->totvert);
445                 for (i = 0; i < numverts_dst; i++) {
446                         mesh_remap_item_define(r_map, i, FLT_MAX, 0, 1, &i, &full_weight);
447                 }
448         }
449         else {
450                 BVHTreeFromMesh treedata = {NULL};
451                 BVHTreeNearest nearest = {0};
452                 BVHTreeRayHit rayhit = {0};
453                 float hit_dist;
454                 float tmp_co[3], tmp_no[3];
455
456                 if (mode == MREMAP_MODE_VERT_NEAREST) {
457                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_VERTS, 2);
458                         nearest.index = -1;
459
460                         for (i = 0; i < numverts_dst; i++) {
461                                 copy_v3_v3(tmp_co, verts_dst[i].co);
462
463                                 /* Convert the vertex to tree coordinates, if needed. */
464                                 if (space_transform) {
465                                         BLI_space_transform_apply(space_transform, tmp_co);
466                                 }
467
468                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
469                                         mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &nearest.index, &full_weight);
470                                 }
471                                 else {
472                                         /* No source for this dest vertex! */
473                                         BKE_mesh_remap_item_define_invalid(r_map, i);
474                                 }
475                         }
476                 }
477                 else if (ELEM(mode, MREMAP_MODE_VERT_EDGE_NEAREST, MREMAP_MODE_VERT_EDGEINTERP_NEAREST)) {
478                         MEdge *edges_src = me_src->medge;
479                         float (*vcos_src)[3] = BKE_mesh_vertexCos_get(me_src, NULL);
480
481                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_EDGES, 2);
482                         nearest.index = -1;
483
484                         for (i = 0; i < numverts_dst; i++) {
485                                 copy_v3_v3(tmp_co, verts_dst[i].co);
486
487                                 /* Convert the vertex to tree coordinates, if needed. */
488                                 if (space_transform) {
489                                         BLI_space_transform_apply(space_transform, tmp_co);
490                                 }
491
492                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
493                                         MEdge *me = &edges_src[nearest.index];
494                                         const float *v1cos = vcos_src[me->v1];
495                                         const float *v2cos = vcos_src[me->v2];
496
497                                         if (mode == MREMAP_MODE_VERT_EDGE_NEAREST) {
498                                                 const float dist_v1 = len_squared_v3v3(tmp_co, v1cos);
499                                                 const float dist_v2 = len_squared_v3v3(tmp_co, v2cos);
500                                                 const int index = (int)((dist_v1 > dist_v2) ? me->v2 : me->v1);
501                                                 mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &index, &full_weight);
502                                         }
503                                         else if (mode == MREMAP_MODE_VERT_EDGEINTERP_NEAREST) {
504                                                 int indices[2];
505                                                 float weights[2];
506
507                                                 indices[0] = (int)me->v1;
508                                                 indices[1] = (int)me->v2;
509
510                                                 /* Weight is inverse of point factor here... */
511                                                 weights[0] = line_point_factor_v3(tmp_co, v2cos, v1cos);
512                                                 CLAMP(weights[0], 0.0f, 1.0f);
513                                                 weights[1] = 1.0f - weights[0];
514
515                                                 mesh_remap_item_define(r_map, i, hit_dist, 0, 2, indices, weights);
516                                         }
517                                 }
518                                 else {
519                                         /* No source for this dest vertex! */
520                                         BKE_mesh_remap_item_define_invalid(r_map, i);
521                                 }
522                         }
523
524                         MEM_freeN(vcos_src);
525                 }
526                 else if (ELEM(mode, MREMAP_MODE_VERT_POLY_NEAREST, MREMAP_MODE_VERT_POLYINTERP_NEAREST,
527                                     MREMAP_MODE_VERT_POLYINTERP_VNORPROJ))
528                 {
529                         MPoly *polys_src = me_src->mpoly;
530                         MLoop *loops_src = me_src->mloop;
531                         float (*vcos_src)[3] = BKE_mesh_vertexCos_get(me_src, NULL);
532
533                         size_t tmp_buff_size = MREMAP_DEFAULT_BUFSIZE;
534                         float (*vcos)[3] = MEM_mallocN(sizeof(*vcos) * tmp_buff_size, __func__);
535                         int *indices = MEM_mallocN(sizeof(*indices) * tmp_buff_size, __func__);
536                         float *weights = MEM_mallocN(sizeof(*weights) * tmp_buff_size, __func__);
537
538                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_LOOPTRI, 2);
539
540                         if (mode == MREMAP_MODE_VERT_POLYINTERP_VNORPROJ) {
541                                 for (i = 0; i < numverts_dst; i++) {
542                                         copy_v3_v3(tmp_co, verts_dst[i].co);
543                                         normal_short_to_float_v3(tmp_no, verts_dst[i].no);
544
545                                         /* Convert the vertex to tree coordinates, if needed. */
546                                         if (space_transform) {
547                                                 BLI_space_transform_apply(space_transform, tmp_co);
548                                                 BLI_space_transform_apply_normal(space_transform, tmp_no);
549                                         }
550
551                                         if (mesh_remap_bvhtree_query_raycast(
552                                                 &treedata, &rayhit, tmp_co, tmp_no, ray_radius, max_dist, &hit_dist))
553                                         {
554                                                 const MLoopTri *lt = &treedata.looptri[rayhit.index];
555                                                 MPoly *mp_src = &polys_src[lt->poly];
556                                                 const int sources_num = mesh_remap_interp_poly_data_get(
557                                                         mp_src, loops_src, (const float (*)[3])vcos_src, rayhit.co,
558                                                         &tmp_buff_size, &vcos, false, &indices, &weights, true, NULL);
559
560                                                 mesh_remap_item_define(r_map, i, hit_dist, 0, sources_num, indices, weights);
561                                         }
562                                         else {
563                                                 /* No source for this dest vertex! */
564                                                 BKE_mesh_remap_item_define_invalid(r_map, i);
565                                         }
566                                 }
567                         }
568                         else {
569                                 nearest.index = -1;
570
571                                 for (i = 0; i < numverts_dst; i++) {
572                                         copy_v3_v3(tmp_co, verts_dst[i].co);
573
574                                         /* Convert the vertex to tree coordinates, if needed. */
575                                         if (space_transform) {
576                                                 BLI_space_transform_apply(space_transform, tmp_co);
577                                         }
578
579                                         if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
580                                                 const MLoopTri *lt = &treedata.looptri[nearest.index];
581                                                 MPoly *mp = &polys_src[lt->poly];
582
583                                                 if (mode == MREMAP_MODE_VERT_POLY_NEAREST) {
584                                                         int index;
585                                                         mesh_remap_interp_poly_data_get(
586                                                                 mp, loops_src, (const float (*)[3])vcos_src, nearest.co,
587                                                                 &tmp_buff_size, &vcos, false, &indices, &weights, false,
588                                                                 &index);
589
590                                                         mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &index, &full_weight);
591                                                 }
592                                                 else if (mode == MREMAP_MODE_VERT_POLYINTERP_NEAREST) {
593                                                         const int sources_num = mesh_remap_interp_poly_data_get(
594                                                                 mp, loops_src, (const float (*)[3])vcos_src, nearest.co,
595                                                                 &tmp_buff_size, &vcos, false, &indices, &weights, true,
596                                                                 NULL);
597
598                                                         mesh_remap_item_define(r_map, i, hit_dist, 0, sources_num, indices, weights);
599                                                 }
600                                         }
601                                         else {
602                                                 /* No source for this dest vertex! */
603                                                 BKE_mesh_remap_item_define_invalid(r_map, i);
604                                         }
605                                 }
606                         }
607
608                         MEM_freeN(vcos_src);
609                         MEM_freeN(vcos);
610                         MEM_freeN(indices);
611                         MEM_freeN(weights);
612                 }
613                 else {
614                         CLOG_WARN(&LOG, "Unsupported mesh-to-mesh vertex mapping mode (%d)!", mode);
615                         memset(r_map->items, 0, sizeof(*r_map->items) * (size_t)numverts_dst);
616                 }
617
618                 free_bvhtree_from_mesh(&treedata);
619         }
620 }
621
622 void BKE_mesh_remap_calc_edges_from_mesh(
623         const int mode, const SpaceTransform *space_transform, const float max_dist, const float ray_radius,
624         const MVert *verts_dst, const int numverts_dst, const MEdge *edges_dst, const int numedges_dst,
625         const bool UNUSED(dirty_nors_dst), Mesh *me_src, MeshPairRemap *r_map)
626 {
627         const float full_weight = 1.0f;
628         const float max_dist_sq = max_dist * max_dist;
629         int i;
630
631         BLI_assert(mode & MREMAP_MODE_EDGE);
632
633         BKE_mesh_remap_init(r_map, numedges_dst);
634
635         if (mode == MREMAP_MODE_TOPOLOGY) {
636                 BLI_assert(numedges_dst == me_src->totedge);
637                 for (i = 0; i < numedges_dst; i++) {
638                         mesh_remap_item_define(r_map, i, FLT_MAX, 0, 1, &i, &full_weight);
639                 }
640         }
641         else {
642                 BVHTreeFromMesh treedata = {NULL};
643                 BVHTreeNearest nearest = {0};
644                 BVHTreeRayHit rayhit = {0};
645                 float hit_dist;
646                 float tmp_co[3], tmp_no[3];
647
648                 if (mode == MREMAP_MODE_EDGE_VERT_NEAREST) {
649                         const int num_verts_src = me_src->totvert;
650                         const int num_edges_src = me_src->totedge;
651                         MEdge *edges_src = me_src->medge;
652                         float (*vcos_src)[3] = BKE_mesh_vertexCos_get(me_src, NULL);
653
654                         MeshElemMap *vert_to_edge_src_map;
655                         int         *vert_to_edge_src_map_mem;
656
657                         struct {
658                                 float hit_dist;
659                                 int   index;
660                         } *v_dst_to_src_map = MEM_mallocN(sizeof(*v_dst_to_src_map) * (size_t)numverts_dst, __func__);
661
662                         for (i = 0; i < numverts_dst; i++) {
663                                 v_dst_to_src_map[i].hit_dist = -1.0f;
664                         }
665
666                         BKE_mesh_vert_edge_map_create(
667                                 &vert_to_edge_src_map, &vert_to_edge_src_map_mem,
668                                 edges_src, num_verts_src, num_edges_src);
669
670                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_VERTS, 2);
671                         nearest.index = -1;
672
673                         for (i = 0; i < numedges_dst; i++) {
674                                 const MEdge *e_dst = &edges_dst[i];
675                                 float best_totdist = FLT_MAX;
676                                 int best_eidx_src = -1;
677                                 int j = 2;
678
679                                 while (j--) {
680                                         const unsigned int vidx_dst = j ? e_dst->v1 : e_dst->v2;
681
682                                         /* Compute closest verts only once! */
683                                         if (v_dst_to_src_map[vidx_dst].hit_dist == -1.0f) {
684                                                 copy_v3_v3(tmp_co, verts_dst[vidx_dst].co);
685
686                                                 /* Convert the vertex to tree coordinates, if needed. */
687                                                 if (space_transform) {
688                                                         BLI_space_transform_apply(space_transform, tmp_co);
689                                                 }
690
691                                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
692                                                         v_dst_to_src_map[vidx_dst].hit_dist = hit_dist;
693                                                         v_dst_to_src_map[vidx_dst].index = nearest.index;
694                                                 }
695                                                 else {
696                                                         /* No source for this dest vert! */
697                                                         v_dst_to_src_map[vidx_dst].hit_dist = FLT_MAX;
698                                                 }
699                                         }
700                                 }
701
702                                 /* Now, check all source edges of closest sources vertices, and select the one giving the smallest
703                                  * total verts-to-verts distance. */
704                                 for (j = 2; j--;) {
705                                         const unsigned int vidx_dst = j ? e_dst->v1 : e_dst->v2;
706                                         const float first_dist = v_dst_to_src_map[vidx_dst].hit_dist;
707                                         const int vidx_src = v_dst_to_src_map[vidx_dst].index;
708                                         int *eidx_src, k;
709
710                                         if (vidx_src < 0) {
711                                                 continue;
712                                         }
713
714                                         eidx_src = vert_to_edge_src_map[vidx_src].indices;
715                                         k = vert_to_edge_src_map[vidx_src].count;
716
717                                         for (; k--; eidx_src++) {
718                                                 MEdge *e_src = &edges_src[*eidx_src];
719                                                 const float *other_co_src = vcos_src[BKE_mesh_edge_other_vert(e_src, vidx_src)];
720                                                 const float *other_co_dst = verts_dst[BKE_mesh_edge_other_vert(e_dst, (int)vidx_dst)].co;
721                                                 const float totdist = first_dist + len_v3v3(other_co_src, other_co_dst);
722
723                                                 if (totdist < best_totdist) {
724                                                         best_totdist = totdist;
725                                                         best_eidx_src = *eidx_src;
726                                                 }
727                                         }
728                                 }
729
730                                 if (best_eidx_src >= 0) {
731                                         const float *co1_src = vcos_src[edges_src[best_eidx_src].v1];
732                                         const float *co2_src = vcos_src[edges_src[best_eidx_src].v2];
733                                         const float *co1_dst = verts_dst[e_dst->v1].co;
734                                         const float *co2_dst = verts_dst[e_dst->v2].co;
735                                         float co_src[3], co_dst[3];
736
737                                         /* TODO: would need an isect_seg_seg_v3(), actually! */
738                                         const int isect_type = isect_line_line_v3(co1_src, co2_src, co1_dst, co2_dst, co_src, co_dst);
739                                         if (isect_type != 0) {
740                                                 const float fac_src = line_point_factor_v3(co_src, co1_src, co2_src);
741                                                 const float fac_dst = line_point_factor_v3(co_dst, co1_dst, co2_dst);
742                                                 if (fac_src < 0.0f) {
743                                                         copy_v3_v3(co_src, co1_src);
744                                                 }
745                                                 else if (fac_src > 1.0f) {
746                                                         copy_v3_v3(co_src, co2_src);
747                                                 }
748                                                 if (fac_dst < 0.0f) {
749                                                         copy_v3_v3(co_dst, co1_dst);
750                                                 }
751                                                 else if (fac_dst > 1.0f) {
752                                                         copy_v3_v3(co_dst, co2_dst);
753                                                 }
754                                         }
755                                         hit_dist = len_v3v3(co_dst, co_src);
756                                         mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &best_eidx_src, &full_weight);
757                                 }
758                                 else {
759                                         /* No source for this dest edge! */
760                                         BKE_mesh_remap_item_define_invalid(r_map, i);
761                                 }
762                         }
763
764                         MEM_freeN(vcos_src);
765                         MEM_freeN(v_dst_to_src_map);
766                         MEM_freeN(vert_to_edge_src_map);
767                         MEM_freeN(vert_to_edge_src_map_mem);
768                 }
769                 else if (mode == MREMAP_MODE_EDGE_NEAREST) {
770                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_EDGES, 2);
771                         nearest.index = -1;
772
773                         for (i = 0; i < numedges_dst; i++) {
774                                 interp_v3_v3v3(tmp_co, verts_dst[edges_dst[i].v1].co, verts_dst[edges_dst[i].v2].co, 0.5f);
775
776                                 /* Convert the vertex to tree coordinates, if needed. */
777                                 if (space_transform) {
778                                         BLI_space_transform_apply(space_transform, tmp_co);
779                                 }
780
781                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
782                                         mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &nearest.index, &full_weight);
783                                 }
784                                 else {
785                                         /* No source for this dest edge! */
786                                         BKE_mesh_remap_item_define_invalid(r_map, i);
787                                 }
788                         }
789                 }
790                 else if (mode == MREMAP_MODE_EDGE_POLY_NEAREST) {
791                         MEdge *edges_src = me_src->medge;
792                         MPoly *polys_src = me_src->mpoly;
793                         MLoop *loops_src = me_src->mloop;
794                         float (*vcos_src)[3] = BKE_mesh_vertexCos_get(me_src, NULL);
795
796                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_LOOPTRI, 2);
797
798                         for (i = 0; i < numedges_dst; i++) {
799                                 interp_v3_v3v3(tmp_co, verts_dst[edges_dst[i].v1].co, verts_dst[edges_dst[i].v2].co, 0.5f);
800
801                                 /* Convert the vertex to tree coordinates, if needed. */
802                                 if (space_transform) {
803                                         BLI_space_transform_apply(space_transform, tmp_co);
804                                 }
805
806                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
807                                         const MLoopTri *lt = &treedata.looptri[nearest.index];
808                                         MPoly *mp_src = &polys_src[lt->poly];
809                                         MLoop *ml_src = &loops_src[mp_src->loopstart];
810                                         int nloops = mp_src->totloop;
811                                         float best_dist_sq = FLT_MAX;
812                                         int best_eidx_src = -1;
813
814                                         for (; nloops--; ml_src++) {
815                                                 MEdge *med_src = &edges_src[ml_src->e];
816                                                 float *co1_src = vcos_src[med_src->v1];
817                                                 float *co2_src = vcos_src[med_src->v2];
818                                                 float co_src[3];
819                                                 float dist_sq;
820
821                                                 interp_v3_v3v3(co_src, co1_src, co2_src, 0.5f);
822                                                 dist_sq = len_squared_v3v3(tmp_co, co_src);
823                                                 if (dist_sq < best_dist_sq) {
824                                                         best_dist_sq = dist_sq;
825                                                         best_eidx_src = (int)ml_src->e;
826                                                 }
827                                         }
828                                         if (best_eidx_src >= 0) {
829                                                 mesh_remap_item_define(r_map, i, hit_dist, 0, 1, &best_eidx_src, &full_weight);
830                                         }
831                                 }
832                                 else {
833                                         /* No source for this dest edge! */
834                                         BKE_mesh_remap_item_define_invalid(r_map, i);
835                                 }
836                         }
837
838                         MEM_freeN(vcos_src);
839                 }
840                 else if (mode == MREMAP_MODE_EDGE_EDGEINTERP_VNORPROJ) {
841                         const int num_rays_min = 5, num_rays_max = 100;
842                         const int numedges_src = me_src->totedge;
843
844                         /* Subtleness - this one we can allocate only max number of cast rays per edges! */
845                         int *indices = MEM_mallocN(sizeof(*indices) * (size_t)min_ii(numedges_src, num_rays_max), __func__);
846                         /* Here it's simpler to just allocate for all edges :/ */
847                         float *weights = MEM_mallocN(sizeof(*weights) * (size_t)numedges_src, __func__);
848
849                         BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_EDGES, 2);
850
851                         for (i = 0; i < numedges_dst; i++) {
852                                 /* For each dst edge, we sample some rays from it (interpolated from its vertices)
853                                  * and use their hits to interpolate from source edges. */
854                                 const MEdge *me = &edges_dst[i];
855                                 float v1_co[3], v2_co[3];
856                                 float v1_no[3], v2_no[3];
857
858                                 int grid_size;
859                                 float edge_dst_len;
860                                 float grid_step;
861
862                                 float totweights = 0.0f;
863                                 float hit_dist_accum = 0.0f;
864                                 int sources_num = 0;
865                                 int j;
866
867                                 copy_v3_v3(v1_co, verts_dst[me->v1].co);
868                                 copy_v3_v3(v2_co, verts_dst[me->v2].co);
869
870                                 normal_short_to_float_v3(v1_no, verts_dst[me->v1].no);
871                                 normal_short_to_float_v3(v2_no, verts_dst[me->v2].no);
872
873                                 /* We do our transform here, allows to interpolate from normals already in src space. */
874                                 if (space_transform) {
875                                         BLI_space_transform_apply(space_transform, v1_co);
876                                         BLI_space_transform_apply(space_transform, v2_co);
877                                         BLI_space_transform_apply_normal(space_transform, v1_no);
878                                         BLI_space_transform_apply_normal(space_transform, v2_no);
879                                 }
880
881                                 copy_vn_fl(weights, (int)numedges_src, 0.0f);
882
883                                 /* We adjust our ray-casting grid to ray_radius (the smaller, the more rays are cast),
884                                  * with lower/upper bounds. */
885                                 edge_dst_len = len_v3v3(v1_co, v2_co);
886
887                                 grid_size = (int)((edge_dst_len / ray_radius) + 0.5f);
888                                 CLAMP(grid_size, num_rays_min, num_rays_max);  /* min 5 rays/edge, max 100. */
889
890                                 grid_step = 1.0f / (float)grid_size;  /* Not actual distance here, rather an interp fac... */
891
892                                 /* And now we can cast all our rays, and see what we get! */
893                                 for (j = 0; j < grid_size; j++) {
894                                         const float fac = grid_step * (float)j;
895
896                                         int n = (ray_radius > 0.0f) ? MREMAP_RAYCAST_APPROXIMATE_NR : 1;
897                                         float w = 1.0f;
898
899                                         interp_v3_v3v3(tmp_co, v1_co, v2_co, fac);
900                                         interp_v3_v3v3_slerp_safe(tmp_no, v1_no, v2_no, fac);
901
902                                         while (n--) {
903                                                 if (mesh_remap_bvhtree_query_raycast(
904                                                         &treedata, &rayhit, tmp_co, tmp_no, ray_radius / w, max_dist, &hit_dist))
905                                                 {
906                                                         weights[rayhit.index] += w;
907                                                         totweights += w;
908                                                         hit_dist_accum += hit_dist;
909                                                         break;
910                                                 }
911                                                 /* Next iteration will get bigger radius but smaller weight! */
912                                                 w /= MREMAP_RAYCAST_APPROXIMATE_FAC;
913                                         }
914                                 }
915                                 /* A sampling is valid (as in, its result can be considered as valid sources) only if at least
916                                  * half of the rays found a source! */
917                                 if (totweights > ((float)grid_size / 2.0f)) {
918                                         for (j = 0; j < (int)numedges_src; j++) {
919                                                 if (!weights[j]) {
920                                                         continue;
921                                                 }
922                                                 /* Note: sources_num is always <= j! */
923                                                 weights[sources_num] = weights[j] / totweights;
924                                                 indices[sources_num] = j;
925                                                 sources_num++;
926                                         }
927                                         mesh_remap_item_define(
928                                                 r_map, i, hit_dist_accum / totweights, 0,
929                                                 sources_num, indices, weights);
930                                 }
931                                 else {
932                                         /* No source for this dest edge! */
933                                         BKE_mesh_remap_item_define_invalid(r_map, i);
934                                 }
935                         }
936
937                         MEM_freeN(indices);
938                         MEM_freeN(weights);
939                 }
940                 else {
941                         CLOG_WARN(&LOG, "Unsupported mesh-to-mesh edge mapping mode (%d)!", mode);
942                         memset(r_map->items, 0, sizeof(*r_map->items) * (size_t)numedges_dst);
943                 }
944
945                 free_bvhtree_from_mesh(&treedata);
946         }
947 }
948
949 #define POLY_UNSET       0
950 #define POLY_CENTER_INIT 1
951 #define POLY_COMPLETE    2
952
953 static void mesh_island_to_astar_graph_edge_process(
954         MeshIslandStore *islands, const int island_index, BLI_AStarGraph *as_graph,
955         MVert *verts, MPoly *polys, MLoop *loops,
956         const int edge_idx, BLI_bitmap *done_edges, MeshElemMap *edge_to_poly_map, const bool is_edge_innercut,
957         int *poly_island_index_map, float (*poly_centers)[3], unsigned char *poly_status)
958 {
959         int *poly_island_indices = BLI_array_alloca(poly_island_indices, (size_t)edge_to_poly_map[edge_idx].count);
960         int i, j;
961
962         for (i = 0; i < edge_to_poly_map[edge_idx].count; i++) {
963                 const int pidx = edge_to_poly_map[edge_idx].indices[i];
964                 MPoly *mp = &polys[pidx];
965                 const int pidx_isld = islands ? poly_island_index_map[pidx] : pidx;
966                 void *custom_data = is_edge_innercut ? POINTER_FROM_INT(edge_idx) : POINTER_FROM_INT(-1);
967
968                 if (UNLIKELY(islands && (islands->items_to_islands[mp->loopstart] != island_index))) {
969                         /* poly not in current island, happens with border edges... */
970                         poly_island_indices[i] = -1;
971                         continue;
972                 }
973
974                 if (poly_status[pidx_isld] == POLY_COMPLETE) {
975                         poly_island_indices[i] = pidx_isld;
976                         continue;
977                 }
978
979                 if (poly_status[pidx_isld] == POLY_UNSET) {
980                         BKE_mesh_calc_poly_center(mp, &loops[mp->loopstart], verts, poly_centers[pidx_isld]);
981                         BLI_astar_node_init(as_graph, pidx_isld, poly_centers[pidx_isld]);
982                         poly_status[pidx_isld] = POLY_CENTER_INIT;
983                 }
984
985                 for (j = i; j--;) {
986                         float dist_cost;
987                         const int pidx_isld_other = poly_island_indices[j];
988
989                         if (pidx_isld_other == -1 || poly_status[pidx_isld_other] == POLY_COMPLETE) {
990                                 /* If the other poly is complete, that link has already been added! */
991                                 continue;
992                         }
993                         dist_cost = len_v3v3(poly_centers[pidx_isld_other], poly_centers[pidx_isld]);
994                         BLI_astar_node_link_add(as_graph, pidx_isld_other, pidx_isld, dist_cost, custom_data);
995                 }
996
997                 poly_island_indices[i] = pidx_isld;
998         }
999
1000         BLI_BITMAP_ENABLE(done_edges, edge_idx);
1001 }
1002
1003 static void mesh_island_to_astar_graph(
1004         MeshIslandStore *islands, const int island_index,
1005         MVert *verts, MeshElemMap *edge_to_poly_map, const int numedges, MLoop *loops, MPoly *polys, const int numpolys,
1006         BLI_AStarGraph *r_as_graph)
1007 {
1008         MeshElemMap *island_poly_map = islands ? islands->islands[island_index] : NULL;
1009         MeshElemMap *island_einnercut_map = islands ? islands->innercuts[island_index] : NULL;
1010
1011         int *poly_island_index_map = NULL;
1012         BLI_bitmap *done_edges = BLI_BITMAP_NEW(numedges, __func__);
1013
1014         const int node_num = islands ? island_poly_map->count : numpolys;
1015         unsigned char *poly_status = MEM_callocN(sizeof(*poly_status) * (size_t)node_num, __func__);
1016         float (*poly_centers)[3];
1017
1018         int pidx_isld;
1019         int i;
1020
1021         BLI_astar_graph_init(r_as_graph, node_num, NULL);
1022         /* poly_centers is owned by graph memarena. */
1023         poly_centers = BLI_memarena_calloc(r_as_graph->mem, sizeof(*poly_centers) * (size_t)node_num);
1024
1025         if (islands) {
1026                 /* poly_island_index_map is owned by graph memarena. */
1027                 poly_island_index_map = BLI_memarena_calloc(r_as_graph->mem, sizeof(*poly_island_index_map) * (size_t)numpolys);
1028                 for (i = island_poly_map->count; i--;) {
1029                         poly_island_index_map[island_poly_map->indices[i]] = i;
1030                 }
1031
1032                 r_as_graph->custom_data = poly_island_index_map;
1033
1034                 for (i = island_einnercut_map->count; i--;) {
1035                         mesh_island_to_astar_graph_edge_process(
1036                                 islands, island_index, r_as_graph, verts, polys, loops,
1037                                 island_einnercut_map->indices[i], done_edges, edge_to_poly_map, true,
1038                                 poly_island_index_map, poly_centers, poly_status);
1039                 }
1040         }
1041
1042         for (pidx_isld = node_num; pidx_isld--;) {
1043                 const int pidx = islands ? island_poly_map->indices[pidx_isld] : pidx_isld;
1044                 MPoly *mp = &polys[pidx];
1045                 int pl_idx, l_idx;
1046
1047                 if (poly_status[pidx_isld] == POLY_COMPLETE) {
1048                         continue;
1049                 }
1050
1051                 for (pl_idx = 0, l_idx = mp->loopstart; pl_idx < mp->totloop; pl_idx++, l_idx++) {
1052                         MLoop *ml = &loops[l_idx];
1053
1054                         if (BLI_BITMAP_TEST(done_edges, ml->e)) {
1055                                 continue;
1056                         }
1057
1058                         mesh_island_to_astar_graph_edge_process(
1059                                 islands, island_index, r_as_graph, verts, polys, loops,
1060                                 (int)ml->e, done_edges, edge_to_poly_map, false,
1061                                 poly_island_index_map, poly_centers, poly_status);
1062                 }
1063                 poly_status[pidx_isld] = POLY_COMPLETE;
1064         }
1065
1066         MEM_freeN(done_edges);
1067         MEM_freeN(poly_status);
1068 }
1069
1070 #undef POLY_UNSET
1071 #undef POLY_CENTER_INIT
1072 #undef POLY_COMPLETE
1073
1074 /* Our 'f_cost' callback func, to find shortest poly-path between two remapped-loops.
1075  * Note we do not want to make innercuts 'walls' here, just detect when the shortest path goes by those. */
1076 static float mesh_remap_calc_loops_astar_f_cost(
1077         BLI_AStarGraph *as_graph, BLI_AStarSolution *as_solution, BLI_AStarGNLink *link,
1078         const int node_idx_curr, const int node_idx_next, const int node_idx_dst)
1079 {
1080         float *co_next, *co_dest;
1081
1082         if (link && (POINTER_AS_INT(link->custom_data) != -1)) {
1083                 /* An innercut edge... We tag our solution as potentially crossing innercuts.
1084                  * Note it might not be the case in the end (AStar will explore around optimal path), but helps
1085                  * trimming off some processing later... */
1086                 if (!POINTER_AS_INT(as_solution->custom_data)) {
1087                         as_solution->custom_data = POINTER_FROM_INT(true);
1088                 }
1089         }
1090
1091         /* Our heuristic part of current f_cost is distance from next node to destination one.
1092          * It is guaranteed to be less than (or equal to) actual shortest poly-path between next node and destination one.
1093          */
1094         co_next = (float *)as_graph->nodes[node_idx_next].custom_data;
1095         co_dest = (float *)as_graph->nodes[node_idx_dst].custom_data;
1096         return (link ? (as_solution->g_costs[node_idx_curr] + link->cost) : 0.0f) + len_v3v3(co_next, co_dest);
1097 }
1098
1099 #define ASTAR_STEPS_MAX 64
1100
1101
1102 void BKE_mesh_remap_calc_loops_from_mesh(
1103         const int mode, const SpaceTransform *space_transform, const float max_dist, const float ray_radius,
1104         MVert *verts_dst, const int numverts_dst, MEdge *edges_dst, const int numedges_dst,
1105         MLoop *loops_dst, const int numloops_dst, MPoly *polys_dst, const int numpolys_dst,
1106         CustomData *ldata_dst, CustomData *pdata_dst,
1107         const bool use_split_nors_dst, const float split_angle_dst, const bool dirty_nors_dst,
1108         Mesh *me_src,
1109         MeshRemapIslandsCalc gen_islands_src, const float islands_precision_src, MeshPairRemap *r_map)
1110 {
1111         const float full_weight = 1.0f;
1112         const float max_dist_sq = max_dist * max_dist;
1113
1114         int i;
1115
1116         BLI_assert(mode & MREMAP_MODE_LOOP);
1117         BLI_assert((islands_precision_src >= 0.0f) && (islands_precision_src <= 1.0f));
1118
1119         BKE_mesh_remap_init(r_map, numloops_dst);
1120
1121         if (mode == MREMAP_MODE_TOPOLOGY) {
1122                 /* In topology mapping, we assume meshes are identical, islands included! */
1123                 BLI_assert(numloops_dst == me_src->totloop);
1124                 for (i = 0; i < numloops_dst; i++) {
1125                         mesh_remap_item_define(r_map, i, FLT_MAX, 0, 1, &i, &full_weight);
1126                 }
1127         }
1128         else {
1129                 BVHTreeFromMesh *treedata = NULL;
1130                 BVHTreeNearest nearest = {0};
1131                 BVHTreeRayHit rayhit = {0};
1132                 int num_trees = 0;
1133                 float hit_dist;
1134                 float tmp_co[3], tmp_no[3];
1135
1136                 const bool use_from_vert = (mode & MREMAP_USE_VERT);
1137
1138                 MeshIslandStore island_store = {0};
1139                 bool use_islands = false;
1140
1141                 BLI_AStarGraph *as_graphdata = NULL;
1142                 BLI_AStarSolution as_solution = {0};
1143                 const int isld_steps_src = (
1144                         islands_precision_src ?
1145                         max_ii((int)(ASTAR_STEPS_MAX * islands_precision_src + 0.499f), 1) : 0);
1146
1147                 float (*poly_nors_src)[3] = NULL;
1148                 float (*loop_nors_src)[3] = NULL;
1149                 float (*poly_nors_dst)[3] = NULL;
1150                 float (*loop_nors_dst)[3] = NULL;
1151
1152                 float (*poly_cents_src)[3] = NULL;
1153
1154                 MeshElemMap *vert_to_loop_map_src = NULL;
1155                 int *vert_to_loop_map_src_buff = NULL;
1156                 MeshElemMap *vert_to_poly_map_src = NULL;
1157                 int *vert_to_poly_map_src_buff = NULL;
1158                 MeshElemMap *edge_to_poly_map_src = NULL;
1159                 int *edge_to_poly_map_src_buff = NULL;
1160                 MeshElemMap *poly_to_looptri_map_src = NULL;
1161                 int *poly_to_looptri_map_src_buff = NULL;
1162
1163                 /* Unlike above, those are one-to-one mappings, simpler! */
1164                 int *loop_to_poly_map_src = NULL;
1165
1166                 MVert *verts_src = me_src->mvert;
1167                 const int num_verts_src = me_src->totvert;
1168                 float (*vcos_src)[3] = NULL;
1169                 MEdge *edges_src = me_src->medge;
1170                 const int num_edges_src = me_src->totedge;
1171                 MLoop *loops_src = me_src->mloop;
1172                 const int num_loops_src = me_src->totloop;
1173                 MPoly *polys_src = me_src->mpoly;
1174                 const int num_polys_src = me_src->totpoly;
1175                 const MLoopTri *looptri_src = NULL;
1176                 int num_looptri_src = 0;
1177
1178                 size_t buff_size_interp = MREMAP_DEFAULT_BUFSIZE;
1179                 float (*vcos_interp)[3] = NULL;
1180                 int *indices_interp = NULL;
1181                 float *weights_interp = NULL;
1182
1183                 MLoop *ml_src, *ml_dst;
1184                 MPoly *mp_src, *mp_dst;
1185                 int tindex, pidx_dst, lidx_dst, plidx_dst, pidx_src, lidx_src, plidx_src;
1186
1187                 IslandResult **islands_res;
1188                 size_t islands_res_buff_size = MREMAP_DEFAULT_BUFSIZE;
1189
1190                 if (!use_from_vert) {
1191                         vcos_src = BKE_mesh_vertexCos_get(me_src, NULL);
1192
1193                         vcos_interp = MEM_mallocN(sizeof(*vcos_interp) * buff_size_interp, __func__);
1194                         indices_interp = MEM_mallocN(sizeof(*indices_interp) * buff_size_interp, __func__);
1195                         weights_interp = MEM_mallocN(sizeof(*weights_interp) * buff_size_interp, __func__);
1196                 }
1197
1198                 {
1199                         const bool need_lnors_src = (mode & MREMAP_USE_LOOP) && (mode & MREMAP_USE_NORMAL);
1200                         const bool need_lnors_dst = need_lnors_src || (mode & MREMAP_USE_NORPROJ);
1201                         const bool need_pnors_src = need_lnors_src || ((mode & MREMAP_USE_POLY) && (mode & MREMAP_USE_NORMAL));
1202                         const bool need_pnors_dst = need_lnors_dst || need_pnors_src;
1203
1204                         if (need_pnors_dst) {
1205                                 /* Cache poly nors into a temp CDLayer. */
1206                                 poly_nors_dst = CustomData_get_layer(pdata_dst, CD_NORMAL);
1207                                 const bool do_poly_nors_dst = (poly_nors_dst == NULL);
1208                                 if (!poly_nors_dst) {
1209                                         poly_nors_dst = CustomData_add_layer(pdata_dst, CD_NORMAL, CD_CALLOC, NULL, numpolys_dst);
1210                                         CustomData_set_layer_flag(pdata_dst, CD_NORMAL, CD_FLAG_TEMPORARY);
1211                                 }
1212                                 if (dirty_nors_dst || do_poly_nors_dst) {
1213                                         BKE_mesh_calc_normals_poly(
1214                                                 verts_dst, NULL, numverts_dst, loops_dst, polys_dst,
1215                                                 numloops_dst, numpolys_dst, poly_nors_dst, true);
1216                                 }
1217                         }
1218                         if (need_lnors_dst) {
1219                                 short (*custom_nors_dst)[2] = CustomData_get_layer(ldata_dst, CD_CUSTOMLOOPNORMAL);
1220
1221                                 /* Cache poly nors into a temp CDLayer. */
1222                                 loop_nors_dst = CustomData_get_layer(ldata_dst, CD_NORMAL);
1223                                 const bool do_loop_nors_dst = (loop_nors_dst == NULL);
1224                                 if (!loop_nors_dst) {
1225                                         loop_nors_dst = CustomData_add_layer(ldata_dst, CD_NORMAL, CD_CALLOC, NULL, numloops_dst);
1226                                         CustomData_set_layer_flag(ldata_dst, CD_NORMAL, CD_FLAG_TEMPORARY);
1227                                 }
1228                                 if (dirty_nors_dst || do_loop_nors_dst) {
1229                                         BKE_mesh_normals_loop_split(
1230                                                 verts_dst, numverts_dst, edges_dst, numedges_dst,
1231                                                 loops_dst, loop_nors_dst, numloops_dst,
1232                                                 polys_dst, (const float (*)[3])poly_nors_dst, numpolys_dst,
1233                                                 use_split_nors_dst, split_angle_dst, NULL, custom_nors_dst, NULL);
1234                                 }
1235                         }
1236                         if (need_pnors_src || need_lnors_src) {
1237                                 /* Simpler for now, calcNormals never stores pnors :( */
1238                                 if (!CustomData_has_layer(&me_src->pdata, CD_NORMAL)) {
1239                                         CustomData_add_layer(&me_src->pdata, CD_NORMAL, CD_CALLOC, NULL, me_src->totpoly);
1240                                         CustomData_set_layer_flag(&me_src->pdata, CD_NORMAL, CD_FLAG_TEMPORARY);
1241                                 }
1242                                 BKE_mesh_calc_normals_split(me_src);
1243
1244                                 if (need_pnors_src) {
1245                                         poly_nors_src = CustomData_get_layer(&me_src->pdata, CD_NORMAL);
1246                                 }
1247                                 if (need_lnors_src) {
1248                                         loop_nors_src = CustomData_get_layer(&me_src->ldata, CD_NORMAL);
1249                                 }
1250                         }
1251                 }
1252
1253                 if (use_from_vert) {
1254                         BKE_mesh_vert_loop_map_create(
1255                                 &vert_to_loop_map_src, &vert_to_loop_map_src_buff,
1256                                 polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src);
1257                         if (mode & MREMAP_USE_POLY) {
1258                                 BKE_mesh_vert_poly_map_create(
1259                                         &vert_to_poly_map_src, &vert_to_poly_map_src_buff,
1260                                         polys_src, loops_src, num_verts_src, num_polys_src, num_loops_src);
1261                         }
1262                 }
1263
1264                 /* Needed for islands (or plain mesh) to AStar graph conversion. */
1265                 BKE_mesh_edge_poly_map_create(
1266                         &edge_to_poly_map_src, &edge_to_poly_map_src_buff,
1267                         edges_src, num_edges_src, polys_src, num_polys_src, loops_src, num_loops_src);
1268                 if (use_from_vert) {
1269                         loop_to_poly_map_src = MEM_mallocN(sizeof(*loop_to_poly_map_src) * (size_t)num_loops_src, __func__);
1270                         poly_cents_src = MEM_mallocN(sizeof(*poly_cents_src) * (size_t)num_polys_src, __func__);
1271                         for (pidx_src = 0, mp_src = polys_src; pidx_src < num_polys_src; pidx_src++, mp_src++) {
1272                                 ml_src = &loops_src[mp_src->loopstart];
1273                                 for (plidx_src = 0, lidx_src = mp_src->loopstart; plidx_src < mp_src->totloop; plidx_src++, lidx_src++) {
1274                                         loop_to_poly_map_src[lidx_src] = pidx_src;
1275                                 }
1276                                 BKE_mesh_calc_poly_center(mp_src, ml_src, verts_src, poly_cents_src[pidx_src]);
1277                         }
1278                 }
1279
1280                 /* Island makes things slightly more complex here.
1281                  * Basically, we:
1282                  *     * Make one treedata for each island's elements.
1283                  *     * Check all loops of a same dest poly against all treedata.
1284                  *     * Choose the island's elements giving the best results.
1285                  */
1286
1287                 /* First, generate the islands, if possible. */
1288                 if (gen_islands_src) {
1289                         use_islands = gen_islands_src(
1290                                 verts_src, num_verts_src,
1291                                 edges_src, num_edges_src,
1292                                 polys_src, num_polys_src,
1293                                 loops_src, num_loops_src,
1294                                 &island_store);
1295
1296                         num_trees = use_islands ? island_store.islands_num : 1;
1297                         treedata = MEM_callocN(sizeof(*treedata) * (size_t)num_trees, __func__);
1298                         if (isld_steps_src) {
1299                                 as_graphdata = MEM_callocN(sizeof(*as_graphdata) * (size_t)num_trees, __func__);
1300                         }
1301
1302                         if (use_islands) {
1303                                 /* We expect our islands to contain poly indices, with edge indices of 'inner cuts',
1304                                  * and a mapping loops -> islands indices.
1305                                  * This implies all loops of a same poly are in the same island. */
1306                                 BLI_assert((island_store.item_type == MISLAND_TYPE_LOOP) &&
1307                                            (island_store.island_type == MISLAND_TYPE_POLY) &&
1308                                            (island_store.innercut_type == MISLAND_TYPE_EDGE));
1309                         }
1310                 }
1311                 else {
1312                         num_trees = 1;
1313                         treedata = MEM_callocN(sizeof(*treedata), __func__);
1314                         if (isld_steps_src) {
1315                                 as_graphdata = MEM_callocN(sizeof(*as_graphdata), __func__);
1316                         }
1317                 }
1318
1319                 /* Build our AStar graphs. */
1320                 if (isld_steps_src) {
1321                         for (tindex = 0; tindex < num_trees; tindex++) {
1322                                 mesh_island_to_astar_graph(
1323                                         use_islands ? &island_store : NULL, tindex, verts_src, edge_to_poly_map_src, num_edges_src,
1324                                         loops_src, polys_src, num_polys_src, &as_graphdata[tindex]);
1325                         }
1326                 }
1327
1328                 /* Build our BVHtrees, either from verts or tessfaces. */
1329                 if (use_from_vert) {
1330                         if (use_islands) {
1331                                 BLI_bitmap *verts_active = BLI_BITMAP_NEW((size_t)num_verts_src, __func__);
1332
1333                                 for (tindex = 0; tindex < num_trees; tindex++) {
1334                                         MeshElemMap *isld = island_store.islands[tindex];
1335                                         int num_verts_active = 0;
1336                                         BLI_bitmap_set_all(verts_active, false, (size_t)num_verts_src);
1337                                         for (i = 0; i < isld->count; i++) {
1338                                                 mp_src = &polys_src[isld->indices[i]];
1339                                                 for (lidx_src = mp_src->loopstart; lidx_src < mp_src->loopstart + mp_src->totloop; lidx_src++) {
1340                                                         const unsigned int vidx_src = loops_src[lidx_src].v;
1341                                                         if (!BLI_BITMAP_TEST(verts_active, vidx_src)) {
1342                                                                 BLI_BITMAP_ENABLE(verts_active, loops_src[lidx_src].v);
1343                                                                 num_verts_active++;
1344                                                         }
1345                                                 }
1346                                         }
1347                                         bvhtree_from_mesh_verts_ex(
1348                                                 &treedata[tindex], verts_src, num_verts_src, false,
1349                                                 verts_active, num_verts_active, 0.0, 2, 6);
1350                                 }
1351
1352                                 MEM_freeN(verts_active);
1353                         }
1354                         else {
1355                                 BLI_assert(num_trees == 1);
1356                                 BKE_bvhtree_from_mesh_get(&treedata[0], me_src, BVHTREE_FROM_VERTS, 2);
1357                         }
1358                 }
1359                 else {  /* We use polygons. */
1360                         if (use_islands) {
1361                                 /* bvhtree here uses looptri faces... */
1362                                 BLI_bitmap *looptri_active;
1363
1364                                 looptri_src = BKE_mesh_runtime_looptri_ensure(me_src);
1365                                 num_looptri_src = me_src->runtime.looptris.len;
1366                                 looptri_active = BLI_BITMAP_NEW((size_t)num_looptri_src, __func__);
1367
1368                                 for (tindex = 0; tindex < num_trees; tindex++) {
1369                                         int num_looptri_active = 0;
1370                                         BLI_bitmap_set_all(looptri_active, false, (size_t)num_looptri_src);
1371                                         for (i = 0; i < num_looptri_src; i++) {
1372                                                 mp_src = &polys_src[looptri_src[i].poly];
1373                                                 if (island_store.items_to_islands[mp_src->loopstart] == tindex) {
1374                                                         BLI_BITMAP_ENABLE(looptri_active, i);
1375                                                         num_looptri_active++;
1376                                                 }
1377                                         }
1378                                         bvhtree_from_mesh_looptri_ex(
1379                                                 &treedata[tindex],
1380                                                 verts_src, false,
1381                                                 loops_src, false,
1382                                                 looptri_src, num_looptri_src, false,
1383                                                 looptri_active, num_looptri_active, 0.0, 2, 6);
1384                                 }
1385
1386                                 MEM_freeN(looptri_active);
1387                         }
1388                         else {
1389                                 BLI_assert(num_trees == 1);
1390                                 BKE_bvhtree_from_mesh_get(&treedata[0], me_src, BVHTREE_FROM_LOOPTRI, 2);
1391                         }
1392                 }
1393
1394                 /* And check each dest poly! */
1395                 islands_res = MEM_mallocN(sizeof(*islands_res) * (size_t)num_trees, __func__);
1396                 for (tindex = 0; tindex < num_trees; tindex++) {
1397                         islands_res[tindex] = MEM_mallocN(sizeof(**islands_res) * islands_res_buff_size, __func__);
1398                 }
1399
1400                 for (pidx_dst = 0, mp_dst = polys_dst; pidx_dst < numpolys_dst; pidx_dst++, mp_dst++) {
1401                         float pnor_dst[3];
1402
1403                         /* Only in use_from_vert case, we may need polys' centers as fallback in case we cannot decide which
1404                          * corner to use from normals only. */
1405                         float pcent_dst[3];
1406                         bool pcent_dst_valid = false;
1407
1408                         if (mode == MREMAP_MODE_LOOP_NEAREST_POLYNOR) {
1409                                 copy_v3_v3(pnor_dst, poly_nors_dst[pidx_dst]);
1410                                 if (space_transform) {
1411                                         BLI_space_transform_apply_normal(space_transform, pnor_dst);
1412                                 }
1413                         }
1414
1415                         if ((size_t)mp_dst->totloop > islands_res_buff_size) {
1416                                 islands_res_buff_size = (size_t)mp_dst->totloop + MREMAP_DEFAULT_BUFSIZE;
1417                                 for (tindex = 0; tindex < num_trees; tindex++) {
1418                                         islands_res[tindex] = MEM_reallocN(islands_res[tindex], sizeof(**islands_res) * islands_res_buff_size);
1419                                 }
1420                         }
1421
1422                         for (tindex = 0; tindex < num_trees; tindex++) {
1423                                 BVHTreeFromMesh *tdata = &treedata[tindex];
1424
1425                                 ml_dst = &loops_dst[mp_dst->loopstart];
1426                                 for (plidx_dst = 0; plidx_dst < mp_dst->totloop; plidx_dst++, ml_dst++) {
1427                                         if (use_from_vert) {
1428                                                 MeshElemMap *vert_to_refelem_map_src = NULL;
1429
1430                                                 copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1431                                                 nearest.index = -1;
1432
1433                                                 /* Convert the vertex to tree coordinates, if needed. */
1434                                                 if (space_transform) {
1435                                                         BLI_space_transform_apply(space_transform, tmp_co);
1436                                                 }
1437
1438                                                 if (mesh_remap_bvhtree_query_nearest(tdata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
1439                                                         float (*nor_dst)[3];
1440                                                         float (*nors_src)[3];
1441                                                         float best_nor_dot = -2.0f;
1442                                                         float best_sqdist_fallback = FLT_MAX;
1443                                                         int best_index_src = -1;
1444
1445                                                         if (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) {
1446                                                                 copy_v3_v3(tmp_no, loop_nors_dst[plidx_dst + mp_dst->loopstart]);
1447                                                                 if (space_transform) {
1448                                                                         BLI_space_transform_apply_normal(space_transform, tmp_no);
1449                                                                 }
1450                                                                 nor_dst = &tmp_no;
1451                                                                 nors_src = loop_nors_src;
1452                                                                 vert_to_refelem_map_src = vert_to_loop_map_src;
1453                                                         }
1454                                                         else {  /* if (mode == MREMAP_MODE_LOOP_NEAREST_POLYNOR) { */
1455                                                                 nor_dst = &pnor_dst;
1456                                                                 nors_src = poly_nors_src;
1457                                                                 vert_to_refelem_map_src = vert_to_poly_map_src;
1458                                                         }
1459
1460                                                         for (i = vert_to_refelem_map_src[nearest.index].count; i--;) {
1461                                                                 const int index_src = vert_to_refelem_map_src[nearest.index].indices[i];
1462                                                                 BLI_assert(index_src != -1);
1463                                                                 const float dot = dot_v3v3(nors_src[index_src], *nor_dst);
1464
1465                                                                 pidx_src = (
1466                                                                         (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ?
1467                                                                         loop_to_poly_map_src[index_src] : index_src);
1468                                                                 /* WARNING! This is not the *real* lidx_src in case of POLYNOR, we only use it
1469                                                                  *          to check we stay on current island (all loops from a given poly are
1470                                                                  *          on same island!). */
1471                                                                 lidx_src = (
1472                                                                         (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ?
1473                                                                         index_src : polys_src[pidx_src].loopstart);
1474
1475                                                                 /* A same vert may be at the boundary of several islands! Hence, we have to ensure
1476                                                                  * poly/loop we are currently considering *belongs* to current island! */
1477                                                                 if (use_islands && island_store.items_to_islands[lidx_src] != tindex) {
1478                                                                         continue;
1479                                                                 }
1480
1481                                                                 if (dot > best_nor_dot - 1e-6f) {
1482                                                                         /* We need something as fallback decision in case dest normal matches several
1483                                                                          * source normals (see T44522), using distance between polys' centers here. */
1484                                                                         float *pcent_src;
1485                                                                         float sqdist;
1486
1487                                                                         mp_src = &polys_src[pidx_src];
1488                                                                         ml_src = &loops_src[mp_src->loopstart];
1489
1490                                                                         if (!pcent_dst_valid) {
1491                                                                                 BKE_mesh_calc_poly_center(
1492                                                                                         mp_dst, &loops_dst[mp_dst->loopstart], verts_dst, pcent_dst);
1493                                                                                 pcent_dst_valid = true;
1494                                                                         }
1495                                                                         pcent_src = poly_cents_src[pidx_src];
1496                                                                         sqdist = len_squared_v3v3(pcent_dst, pcent_src);
1497
1498                                                                         if ((dot > best_nor_dot + 1e-6f) || (sqdist < best_sqdist_fallback)) {
1499                                                                                 best_nor_dot = dot;
1500                                                                                 best_sqdist_fallback = sqdist;
1501                                                                                 best_index_src = index_src;
1502                                                                         }
1503                                                                 }
1504                                                         }
1505                                                         if (best_index_src == -1) {
1506                                                                 /* We found no item to map back from closest vertex... */
1507                                                                 best_nor_dot = -1.0f;
1508                                                                 hit_dist = FLT_MAX;
1509                                                         }
1510                                                         else if (mode == MREMAP_MODE_LOOP_NEAREST_POLYNOR) {
1511                                                                 /* Our best_index_src is a poly one for now!
1512                                                                  * Have to find its loop matching our closest vertex. */
1513                                                                 mp_src = &polys_src[best_index_src];
1514                                                                 ml_src = &loops_src[mp_src->loopstart];
1515                                                                 for (plidx_src = 0; plidx_src < mp_src->totloop; plidx_src++, ml_src++) {
1516                                                                         if ((int)ml_src->v == nearest.index) {
1517                                                                                 best_index_src = plidx_src + mp_src->loopstart;
1518                                                                                 break;
1519                                                                         }
1520                                                                 }
1521                                                         }
1522                                                         best_nor_dot = (best_nor_dot + 1.0f) * 0.5f;
1523                                                         islands_res[tindex][plidx_dst].factor = hit_dist ? (best_nor_dot / hit_dist) : 1e18f;
1524                                                         islands_res[tindex][plidx_dst].hit_dist = hit_dist;
1525                                                         islands_res[tindex][plidx_dst].index_src = best_index_src;
1526                                                 }
1527                                                 else {
1528                                                         /* No source for this dest loop! */
1529                                                         islands_res[tindex][plidx_dst].factor = 0.0f;
1530                                                         islands_res[tindex][plidx_dst].hit_dist = FLT_MAX;
1531                                                         islands_res[tindex][plidx_dst].index_src = -1;
1532                                                 }
1533                                         }
1534                                         else if (mode & MREMAP_USE_NORPROJ) {
1535                                                 int n = (ray_radius > 0.0f) ? MREMAP_RAYCAST_APPROXIMATE_NR : 1;
1536                                                 float w = 1.0f;
1537
1538                                                 copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1539                                                 copy_v3_v3(tmp_no, loop_nors_dst[plidx_dst + mp_dst->loopstart]);
1540
1541                                                 /* We do our transform here, since we may do several raycast/nearest queries. */
1542                                                 if (space_transform) {
1543                                                         BLI_space_transform_apply(space_transform, tmp_co);
1544                                                         BLI_space_transform_apply_normal(space_transform, tmp_no);
1545                                                 }
1546
1547                                                 while (n--) {
1548                                                         if (mesh_remap_bvhtree_query_raycast(
1549                                                                 tdata, &rayhit, tmp_co, tmp_no, ray_radius / w, max_dist, &hit_dist))
1550                                                         {
1551                                                                 islands_res[tindex][plidx_dst].factor = (hit_dist ? (1.0f / hit_dist) : 1e18f) * w;
1552                                                                 islands_res[tindex][plidx_dst].hit_dist = hit_dist;
1553                                                                 islands_res[tindex][plidx_dst].index_src = (int)tdata->looptri[rayhit.index].poly;
1554                                                                 copy_v3_v3(islands_res[tindex][plidx_dst].hit_point, rayhit.co);
1555                                                                 break;
1556                                                         }
1557                                                         /* Next iteration will get bigger radius but smaller weight! */
1558                                                         w /= MREMAP_RAYCAST_APPROXIMATE_FAC;
1559                                                 }
1560                                                 if (n == -1) {
1561                                                         /* Fallback to 'nearest' hit here, loops usually comes in 'face group', not good to
1562                                                          * have only part of one dest face's loops to map to source.
1563                                                          * Note that since we give this a null weight, if whole weight for a given face
1564                                                          * is null, it means none of its loop mapped to this source island, hence we can skip it
1565                                                          * later.
1566                                                          */
1567                                                         copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1568                                                         nearest.index = -1;
1569
1570                                                         /* Convert the vertex to tree coordinates, if needed. */
1571                                                         if (space_transform) {
1572                                                                 BLI_space_transform_apply(space_transform, tmp_co);
1573                                                         }
1574
1575                                                         /* In any case, this fallback nearest hit should have no weight at all
1576                                                          * in 'best island' decision! */
1577                                                         islands_res[tindex][plidx_dst].factor = 0.0f;
1578
1579                                                         if (mesh_remap_bvhtree_query_nearest(tdata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
1580                                                                 islands_res[tindex][plidx_dst].hit_dist = hit_dist;
1581                                                                 islands_res[tindex][plidx_dst].index_src = (int)tdata->looptri[nearest.index].poly;
1582                                                                 copy_v3_v3(islands_res[tindex][plidx_dst].hit_point, nearest.co);
1583                                                         }
1584                                                         else {
1585                                                                 /* No source for this dest loop! */
1586                                                                 islands_res[tindex][plidx_dst].hit_dist = FLT_MAX;
1587                                                                 islands_res[tindex][plidx_dst].index_src = -1;
1588                                                         }
1589                                                 }
1590                                         }
1591                                         else {  /* Nearest poly either to use all its loops/verts or just closest one. */
1592                                                 copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1593                                                 nearest.index = -1;
1594
1595                                                 /* Convert the vertex to tree coordinates, if needed. */
1596                                                 if (space_transform) {
1597                                                         BLI_space_transform_apply(space_transform, tmp_co);
1598                                                 }
1599
1600                                                 if (mesh_remap_bvhtree_query_nearest(tdata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
1601                                                         islands_res[tindex][plidx_dst].factor = hit_dist ? (1.0f / hit_dist) : 1e18f;
1602                                                         islands_res[tindex][plidx_dst].hit_dist = hit_dist;
1603                                                         islands_res[tindex][plidx_dst].index_src = (int)tdata->looptri[nearest.index].poly;
1604                                                         copy_v3_v3(islands_res[tindex][plidx_dst].hit_point, nearest.co);
1605                                                 }
1606                                                 else {
1607                                                         /* No source for this dest loop! */
1608                                                         islands_res[tindex][plidx_dst].factor = 0.0f;
1609                                                         islands_res[tindex][plidx_dst].hit_dist = FLT_MAX;
1610                                                         islands_res[tindex][plidx_dst].index_src = -1;
1611                                                 }
1612                                         }
1613                                 }
1614                         }
1615
1616                         /* And now, find best island to use! */
1617                         /* We have to first select the 'best source island' for given dst poly and its loops.
1618                          * Then, we have to check that poly does not 'spread' across some island's limits
1619                          * (like inner seams for UVs, etc.).
1620                          * Note we only still partially support that kind of situation here, i.e. polys spreading over actual cracks
1621                          * (like a narrow space without faces on src, splitting a 'tube-like' geometry). That kind of situation
1622                          * should be relatively rare, though.
1623                          */
1624                         /* XXX This block in itself is big and complex enough to be a separate function but... it uses a bunch
1625                          *     of locale vars. Not worth sending all that through parameters (for now at least). */
1626                         {
1627                                 BLI_AStarGraph *as_graph = NULL;
1628                                 int *poly_island_index_map = NULL;
1629                                 int pidx_src_prev = -1;
1630
1631                                 MeshElemMap *best_island = NULL;
1632                                 float best_island_fac = 0.0f;
1633                                 int best_island_index = -1;
1634
1635                                 for (tindex = 0; tindex < num_trees; tindex++) {
1636                                         float island_fac = 0.0f;
1637
1638                                         for (plidx_dst = 0; plidx_dst < mp_dst->totloop; plidx_dst++) {
1639                                                 island_fac += islands_res[tindex][plidx_dst].factor;
1640                                         }
1641                                         island_fac /= (float)mp_dst->totloop;
1642
1643                                         if (island_fac > best_island_fac) {
1644                                                 best_island_fac = island_fac;
1645                                                 best_island_index = tindex;
1646                                         }
1647                                 }
1648
1649                                 if (best_island_index != -1 && isld_steps_src) {
1650                                         best_island = use_islands ? island_store.islands[best_island_index] : NULL;
1651                                         as_graph = &as_graphdata[best_island_index];
1652                                         poly_island_index_map = (int *)as_graph->custom_data;
1653                                         BLI_astar_solution_init(as_graph, &as_solution, NULL);
1654                                 }
1655
1656                                 for (plidx_dst = 0; plidx_dst < mp_dst->totloop; plidx_dst++) {
1657                                         IslandResult *isld_res;
1658                                         lidx_dst = plidx_dst + mp_dst->loopstart;
1659
1660                                         if (best_island_index == -1) {
1661                                                 /* No source for any loops of our dest poly in any source islands. */
1662                                                 BKE_mesh_remap_item_define_invalid(r_map, lidx_dst);
1663                                                 continue;
1664                                         }
1665
1666                                         as_solution.custom_data = POINTER_FROM_INT(false);
1667
1668                                         isld_res = &islands_res[best_island_index][plidx_dst];
1669                                         if (use_from_vert) {
1670                                                 /* Indices stored in islands_res are those of loops, one per dest loop. */
1671                                                 lidx_src = isld_res->index_src;
1672                                                 if (lidx_src >= 0) {
1673                                                         pidx_src = loop_to_poly_map_src[lidx_src];
1674                                                         /* If prev and curr poly are the same, no need to do anything more!!! */
1675                                                         if (!ELEM(pidx_src_prev, -1, pidx_src) && isld_steps_src) {
1676                                                                 int pidx_isld_src, pidx_isld_src_prev;
1677                                                                 if (poly_island_index_map) {
1678                                                                         pidx_isld_src = poly_island_index_map[pidx_src];
1679                                                                         pidx_isld_src_prev = poly_island_index_map[pidx_src_prev];
1680                                                                 }
1681                                                                 else {
1682                                                                         pidx_isld_src = pidx_src;
1683                                                                         pidx_isld_src_prev = pidx_src_prev;
1684                                                                 }
1685
1686                                                                 BLI_astar_graph_solve(
1687                                                                         as_graph, pidx_isld_src_prev, pidx_isld_src,
1688                                                                         mesh_remap_calc_loops_astar_f_cost, &as_solution, isld_steps_src);
1689                                                                 if (POINTER_AS_INT(as_solution.custom_data) && (as_solution.steps > 0)) {
1690                                                                         /* Find first 'cutting edge' on path, and bring back lidx_src on poly just
1691                                                                          * before that edge.
1692                                                                          * Note we could try to be much smarter (like e.g. storing a whole poly's indices,
1693                                                                          * and making decision (on which side of cutting edge(s!) to be) on the end,
1694                                                                          * but this is one more level of complexity, better to first see if
1695                                                                          * simple solution works!
1696                                                                          */
1697                                                                         int last_valid_pidx_isld_src = -1;
1698                                                                         /* Note we go backward here, from dest to src poly. */
1699                                                                         for (i = as_solution.steps - 1; i--;) {
1700                                                                                 BLI_AStarGNLink *as_link = as_solution.prev_links[pidx_isld_src];
1701                                                                                 const int eidx = POINTER_AS_INT(as_link->custom_data);
1702                                                                                 pidx_isld_src = as_solution.prev_nodes[pidx_isld_src];
1703                                                                                 BLI_assert(pidx_isld_src != -1);
1704                                                                                 if (eidx != -1) {
1705                                                                                         /* we are 'crossing' a cutting edge. */
1706                                                                                         last_valid_pidx_isld_src = pidx_isld_src;
1707                                                                                 }
1708                                                                         }
1709                                                                         if (last_valid_pidx_isld_src != -1) {
1710                                                                                 /* Find a new valid loop in that new poly (nearest one for now).
1711                                                                                  * Note we could be much more subtle here, again that's for later... */
1712                                                                                 int j;
1713                                                                                 float best_dist_sq = FLT_MAX;
1714
1715                                                                                 ml_dst = &loops_dst[lidx_dst];
1716                                                                                 copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1717
1718                                                                                 /* We do our transform here, since we may do several raycast/nearest queries. */
1719                                                                                 if (space_transform) {
1720                                                                                         BLI_space_transform_apply(space_transform, tmp_co);
1721                                                                                 }
1722
1723                                                                                 pidx_src = (
1724                                                                                         use_islands ? best_island->indices[last_valid_pidx_isld_src] :
1725                                                                                         last_valid_pidx_isld_src);
1726                                                                                 mp_src = &polys_src[pidx_src];
1727                                                                                 ml_src = &loops_src[mp_src->loopstart];
1728                                                                                 for (j = 0; j < mp_src->totloop; j++, ml_src++) {
1729                                                                                         const float dist_sq = len_squared_v3v3(verts_src[ml_src->v].co, tmp_co);
1730                                                                                         if (dist_sq < best_dist_sq) {
1731                                                                                                 best_dist_sq = dist_sq;
1732                                                                                                 lidx_src = mp_src->loopstart + j;
1733                                                                                         }
1734                                                                                 }
1735                                                                         }
1736                                                                 }
1737                                                         }
1738                                                         mesh_remap_item_define(
1739                                                                 r_map, lidx_dst, isld_res->hit_dist,
1740                                                                 best_island_index, 1, &lidx_src, &full_weight);
1741                                                         pidx_src_prev = pidx_src;
1742                                                 }
1743                                                 else {
1744                                                         /* No source for this loop in this island. */
1745                                                         /* TODO: would probably be better to get a source at all cost in best island anyway? */
1746                                                         mesh_remap_item_define(
1747                                                                 r_map, lidx_dst, FLT_MAX,
1748                                                                 best_island_index, 0, NULL, NULL);
1749                                                 }
1750                                         }
1751                                         else {
1752                                                 /* Else, we use source poly, indices stored in islands_res are those of polygons. */
1753                                                 pidx_src = isld_res->index_src;
1754                                                 if (pidx_src >= 0) {
1755                                                         float *hit_co = isld_res->hit_point;
1756                                                         int best_loop_index_src;
1757
1758                                                         mp_src = &polys_src[pidx_src];
1759                                                         /* If prev and curr poly are the same, no need to do anything more!!! */
1760                                                         if (!ELEM(pidx_src_prev, -1, pidx_src) && isld_steps_src) {
1761                                                                 int pidx_isld_src, pidx_isld_src_prev;
1762                                                                 if (poly_island_index_map) {
1763                                                                         pidx_isld_src = poly_island_index_map[pidx_src];
1764                                                                         pidx_isld_src_prev = poly_island_index_map[pidx_src_prev];
1765                                                                 }
1766                                                                 else {
1767                                                                         pidx_isld_src = pidx_src;
1768                                                                         pidx_isld_src_prev = pidx_src_prev;
1769                                                                 }
1770
1771                                                                 BLI_astar_graph_solve(
1772                                                                         as_graph, pidx_isld_src_prev, pidx_isld_src,
1773                                                                         mesh_remap_calc_loops_astar_f_cost, &as_solution, isld_steps_src);
1774                                                                 if (POINTER_AS_INT(as_solution.custom_data) && (as_solution.steps > 0)) {
1775                                                                         /* Find first 'cutting edge' on path, and bring back lidx_src on poly just
1776                                                                          * before that edge.
1777                                                                          * Note we could try to be much smarter (like e.g. storing a whole poly's indices,
1778                                                                          * and making decision (one which side of cutting edge(s!) to be on the end,
1779                                                                          * but this is one more level of complexity, better to first see if
1780                                                                          * simple solution works!
1781                                                                          */
1782                                                                         int last_valid_pidx_isld_src = -1;
1783                                                                         /* Note we go backward here, from dest to src poly. */
1784                                                                         for (i = as_solution.steps - 1; i--;) {
1785                                                                                 BLI_AStarGNLink *as_link = as_solution.prev_links[pidx_isld_src];
1786                                                                                 int eidx = POINTER_AS_INT(as_link->custom_data);
1787
1788                                                                                 pidx_isld_src = as_solution.prev_nodes[pidx_isld_src];
1789                                                                                 BLI_assert(pidx_isld_src != -1);
1790                                                                                 if (eidx != -1) {
1791                                                                                         /* we are 'crossing' a cutting edge. */
1792                                                                                         last_valid_pidx_isld_src = pidx_isld_src;
1793                                                                                 }
1794                                                                         }
1795                                                                         if (last_valid_pidx_isld_src != -1) {
1796                                                                                 /* Find a new valid loop in that new poly (nearest point on poly for now).
1797                                                                                  * Note we could be much more subtle here, again that's for later... */
1798                                                                                 float best_dist_sq = FLT_MAX;
1799                                                                                 int j;
1800
1801                                                                                 ml_dst = &loops_dst[lidx_dst];
1802                                                                                 copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co);
1803
1804                                                                                 /* We do our transform here, since we may do several raycast/nearest queries. */
1805                                                                                 if (space_transform) {
1806                                                                                         BLI_space_transform_apply(space_transform, tmp_co);
1807                                                                                 }
1808
1809                                                                                 pidx_src = (
1810                                                                                         use_islands ? best_island->indices[last_valid_pidx_isld_src] :
1811                                                                                         last_valid_pidx_isld_src);
1812                                                                                 mp_src = &polys_src[pidx_src];
1813
1814                                                                                 /* Create that one on demand. */
1815                                                                                 if (poly_to_looptri_map_src == NULL) {
1816                                                                                         BKE_mesh_origindex_map_create_looptri(
1817                                                                                                 &poly_to_looptri_map_src, &poly_to_looptri_map_src_buff,
1818                                                                                                 polys_src, num_polys_src,
1819                                                                                                 looptri_src, num_looptri_src);
1820                                                                                 }
1821
1822                                                                                 for (j = poly_to_looptri_map_src[pidx_src].count; j--;) {
1823                                                                                         float h[3];
1824                                                                                         const MLoopTri *lt = &looptri_src[poly_to_looptri_map_src[pidx_src].indices[j]];
1825                                                                                         float dist_sq;
1826
1827                                                                                         closest_on_tri_to_point_v3(
1828                                                                                                 h, tmp_co,
1829                                                                                                 vcos_src[loops_src[lt->tri[0]].v],
1830                                                                                                 vcos_src[loops_src[lt->tri[1]].v],
1831                                                                                                 vcos_src[loops_src[lt->tri[2]].v]);
1832                                                                                         dist_sq = len_squared_v3v3(tmp_co, h);
1833                                                                                         if (dist_sq < best_dist_sq) {
1834                                                                                                 copy_v3_v3(hit_co, h);
1835                                                                                                 best_dist_sq = dist_sq;
1836                                                                                         }
1837                                                                                 }
1838                                                                         }
1839                                                                 }
1840                                                         }
1841
1842                                                         if (mode == MREMAP_MODE_LOOP_POLY_NEAREST) {
1843                                                                 mesh_remap_interp_poly_data_get(
1844                                                                         mp_src, loops_src, (const float (*)[3])vcos_src, hit_co,
1845                                                                         &buff_size_interp, &vcos_interp, true, &indices_interp,
1846                                                                         &weights_interp, false, &best_loop_index_src);
1847
1848                                                                 mesh_remap_item_define(
1849                                                                         r_map, lidx_dst, isld_res->hit_dist,
1850                                                                         best_island_index, 1, &best_loop_index_src, &full_weight);
1851                                                         }
1852                                                         else {
1853                                                                 const int sources_num = mesh_remap_interp_poly_data_get(
1854                                                                         mp_src, loops_src, (const float (*)[3])vcos_src, hit_co,
1855                                                                         &buff_size_interp, &vcos_interp, true, &indices_interp,
1856                                                                         &weights_interp, true, NULL);
1857
1858                                                                 mesh_remap_item_define(
1859                                                                         r_map, lidx_dst,
1860                                                                         isld_res->hit_dist, best_island_index,
1861                                                                         sources_num, indices_interp, weights_interp);
1862                                                         }
1863
1864                                                         pidx_src_prev = pidx_src;
1865                                                 }
1866                                                 else {
1867                                                         /* No source for this loop in this island. */
1868                                                         /* TODO: would probably be better to get a source at all cost in best island anyway? */
1869                                                         mesh_remap_item_define(r_map, lidx_dst, FLT_MAX, best_island_index, 0, NULL, NULL);
1870                                                 }
1871                                         }
1872                                 }
1873
1874                                 BLI_astar_solution_clear(&as_solution);
1875                         }
1876                 }
1877
1878                 for (tindex = 0; tindex < num_trees; tindex++) {
1879                         MEM_freeN(islands_res[tindex]);
1880                         free_bvhtree_from_mesh(&treedata[tindex]);
1881                         if (isld_steps_src) {
1882                                 BLI_astar_graph_free(&as_graphdata[tindex]);
1883                         }
1884                 }
1885                 MEM_freeN(islands_res);
1886                 BKE_mesh_loop_islands_free(&island_store);
1887                 MEM_freeN(treedata);
1888                 if (isld_steps_src) {
1889                         MEM_freeN(as_graphdata);
1890                         BLI_astar_solution_free(&as_solution);
1891                 }
1892
1893                 if (vcos_src) {
1894                         MEM_freeN(vcos_src);
1895                 }
1896                 if (vert_to_loop_map_src) {
1897                         MEM_freeN(vert_to_loop_map_src);
1898                 }
1899                 if (vert_to_loop_map_src_buff) {
1900                         MEM_freeN(vert_to_loop_map_src_buff);
1901                 }
1902                 if (vert_to_poly_map_src) {
1903                         MEM_freeN(vert_to_poly_map_src);
1904                 }
1905                 if (vert_to_poly_map_src_buff) {
1906                         MEM_freeN(vert_to_poly_map_src_buff);
1907                 }
1908                 if (edge_to_poly_map_src) {
1909                         MEM_freeN(edge_to_poly_map_src);
1910                 }
1911                 if (edge_to_poly_map_src_buff) {
1912                         MEM_freeN(edge_to_poly_map_src_buff);
1913                 }
1914                 if (poly_to_looptri_map_src) {
1915                         MEM_freeN(poly_to_looptri_map_src);
1916                 }
1917                 if (poly_to_looptri_map_src_buff) {
1918                         MEM_freeN(poly_to_looptri_map_src_buff);
1919                 }
1920                 if (loop_to_poly_map_src) {
1921                         MEM_freeN(loop_to_poly_map_src);
1922                 }
1923                 if (poly_cents_src) {
1924                         MEM_freeN(poly_cents_src);
1925                 }
1926                 if (vcos_interp) {
1927                         MEM_freeN(vcos_interp);
1928                 }
1929                 if (indices_interp) {
1930                         MEM_freeN(indices_interp);
1931                 }
1932                 if (weights_interp) {
1933                         MEM_freeN(weights_interp);
1934                 }
1935         }
1936 }
1937
1938 void BKE_mesh_remap_calc_polys_from_mesh(
1939         const int mode, const SpaceTransform *space_transform, const float max_dist, const float ray_radius,
1940         MVert *verts_dst, const int numverts_dst, MLoop *loops_dst, const int numloops_dst,
1941         MPoly *polys_dst, const int numpolys_dst, CustomData *pdata_dst, const bool dirty_nors_dst,
1942         Mesh *me_src, MeshPairRemap *r_map)
1943 {
1944         const float full_weight = 1.0f;
1945         const float max_dist_sq = max_dist * max_dist;
1946         float (*poly_nors_dst)[3] = NULL;
1947         float tmp_co[3], tmp_no[3];
1948         int i;
1949
1950         BLI_assert(mode & MREMAP_MODE_POLY);
1951
1952         if (mode & (MREMAP_USE_NORMAL | MREMAP_USE_NORPROJ)) {
1953                 /* Cache poly nors into a temp CDLayer. */
1954                 poly_nors_dst = CustomData_get_layer(pdata_dst, CD_NORMAL);
1955                 if (!poly_nors_dst) {
1956                         poly_nors_dst = CustomData_add_layer(pdata_dst, CD_NORMAL, CD_CALLOC, NULL, numpolys_dst);
1957                         CustomData_set_layer_flag(pdata_dst, CD_NORMAL, CD_FLAG_TEMPORARY);
1958                 }
1959                 if (dirty_nors_dst) {
1960                         BKE_mesh_calc_normals_poly(
1961                                 verts_dst, NULL, numverts_dst, loops_dst, polys_dst, numloops_dst, numpolys_dst,
1962                                 poly_nors_dst, true);
1963                 }
1964         }
1965
1966         BKE_mesh_remap_init(r_map, numpolys_dst);
1967
1968         if (mode == MREMAP_MODE_TOPOLOGY) {
1969                 BLI_assert(numpolys_dst == me_src->totpoly);
1970                 for (i = 0; i < numpolys_dst; i++) {
1971                         mesh_remap_item_define(r_map, i, FLT_MAX, 0, 1, &i, &full_weight);
1972                 }
1973         }
1974         else {
1975                 BVHTreeFromMesh treedata = {NULL};
1976                 BVHTreeNearest nearest = {0};
1977                 BVHTreeRayHit rayhit = {0};
1978                 float hit_dist;
1979
1980                 BKE_bvhtree_from_mesh_get(&treedata, me_src, BVHTREE_FROM_LOOPTRI, 2);
1981
1982                 if (mode == MREMAP_MODE_POLY_NEAREST) {
1983                         nearest.index = -1;
1984
1985                         for (i = 0; i < numpolys_dst; i++) {
1986                                 MPoly *mp = &polys_dst[i];
1987
1988                                 BKE_mesh_calc_poly_center(mp, &loops_dst[mp->loopstart], verts_dst, tmp_co);
1989
1990                                 /* Convert the vertex to tree coordinates, if needed. */
1991                                 if (space_transform) {
1992                                         BLI_space_transform_apply(space_transform, tmp_co);
1993                                 }
1994
1995                                 if (mesh_remap_bvhtree_query_nearest(&treedata, &nearest, tmp_co, max_dist_sq, &hit_dist)) {
1996                                         const MLoopTri *lt = &treedata.looptri[nearest.index];
1997                                         const int poly_index = (int)lt->poly;
1998                                         mesh_remap_item_define(
1999                                                 r_map, i, hit_dist, 0,
2000                                                 1, &poly_index, &full_weight);
2001                                 }
2002                                 else {
2003                                         /* No source for this dest poly! */
2004                                         BKE_mesh_remap_item_define_invalid(r_map, i);
2005                                 }
2006                         }
2007                 }
2008                 else if (mode == MREMAP_MODE_POLY_NOR) {
2009                         BLI_assert(poly_nors_dst);
2010
2011                         for (i = 0; i < numpolys_dst; i++) {
2012                                 MPoly *mp = &polys_dst[i];
2013
2014                                 BKE_mesh_calc_poly_center(mp, &loops_dst[mp->loopstart], verts_dst, tmp_co);
2015                                 copy_v3_v3(tmp_no, poly_nors_dst[i]);
2016
2017                                 /* Convert the vertex to tree coordinates, if needed. */
2018                                 if (space_transform) {
2019                                         BLI_space_transform_apply(space_transform, tmp_co);
2020                                         BLI_space_transform_apply_normal(space_transform, tmp_no);
2021                                 }
2022
2023                                 if (mesh_remap_bvhtree_query_raycast(
2024                                         &treedata, &rayhit, tmp_co, tmp_no, ray_radius, max_dist, &hit_dist))
2025                                 {
2026                                         const MLoopTri *lt = &treedata.looptri[rayhit.index];
2027                                         const int poly_index = (int)lt->poly;
2028
2029                                         mesh_remap_item_define(
2030                                                 r_map, i, hit_dist, 0,
2031                                                 1, &poly_index, &full_weight);
2032                                 }
2033                                 else {
2034                                         /* No source for this dest poly! */
2035                                         BKE_mesh_remap_item_define_invalid(r_map, i);
2036                                 }
2037                         }
2038                 }
2039                 else if (mode == MREMAP_MODE_POLY_POLYINTERP_PNORPROJ) {
2040                         /* We cast our rays randomly, with a pseudo-even distribution (since we spread across tessellated tris,
2041                          * with additional weighting based on each tri's relative area).
2042                          */
2043                         RNG *rng = BLI_rng_new(0);
2044
2045                         const size_t numpolys_src = (size_t)me_src->totpoly;
2046
2047                         /* Here it's simpler to just allocate for all polys :/ */
2048                         int *indices = MEM_mallocN(sizeof(*indices) * numpolys_src, __func__);
2049                         float *weights = MEM_mallocN(sizeof(*weights) * numpolys_src, __func__);
2050
2051                         size_t tmp_poly_size = MREMAP_DEFAULT_BUFSIZE;
2052                         float (*poly_vcos_2d)[2] = MEM_mallocN(sizeof(*poly_vcos_2d) * tmp_poly_size, __func__);
2053                         /* Tessellated 2D poly, always (num_loops - 2) triangles. */
2054                         int (*tri_vidx_2d)[3] = MEM_mallocN(sizeof(*tri_vidx_2d) * (tmp_poly_size - 2), __func__);
2055
2056                         for (i = 0; i < numpolys_dst; i++) {
2057                                 /* For each dst poly, we sample some rays from it (2D grid in pnor space)
2058                                  * and use their hits to interpolate from source polys. */
2059                                 /* Note: dst poly is early-converted into src space! */
2060                                 MPoly *mp = &polys_dst[i];
2061
2062                                 int tot_rays, done_rays = 0;
2063                                 float poly_area_2d_inv, done_area = 0.0f;
2064
2065                                 float pcent_dst[3];
2066                                 float to_pnor_2d_mat[3][3], from_pnor_2d_mat[3][3];
2067                                 float poly_dst_2d_min[2], poly_dst_2d_max[2], poly_dst_2d_z;
2068                                 float poly_dst_2d_size[2];
2069
2070                                 float totweights = 0.0f;
2071                                 float hit_dist_accum = 0.0f;
2072                                 int sources_num = 0;
2073                                 const int tris_num = mp->totloop - 2;
2074                                 int j;
2075
2076                                 BKE_mesh_calc_poly_center(mp, &loops_dst[mp->loopstart], verts_dst, pcent_dst);
2077                                 copy_v3_v3(tmp_no, poly_nors_dst[i]);
2078
2079                                 /* We do our transform here, else it'd be redone by raycast helper for each ray, ugh! */
2080                                 if (space_transform) {
2081                                         BLI_space_transform_apply(space_transform, pcent_dst);
2082                                         BLI_space_transform_apply_normal(space_transform, tmp_no);
2083                                 }
2084
2085                                 copy_vn_fl(weights, (int)numpolys_src, 0.0f);
2086
2087                                 if (UNLIKELY((size_t)mp->totloop > tmp_poly_size)) {
2088                                         tmp_poly_size = (size_t)mp->totloop;
2089                                         poly_vcos_2d = MEM_reallocN(poly_vcos_2d, sizeof(*poly_vcos_2d) * tmp_poly_size);
2090                                         tri_vidx_2d = MEM_reallocN(tri_vidx_2d, sizeof(*tri_vidx_2d) * (tmp_poly_size - 2));
2091                                 }
2092
2093                                 axis_dominant_v3_to_m3(to_pnor_2d_mat, tmp_no);
2094                                 invert_m3_m3(from_pnor_2d_mat, to_pnor_2d_mat);
2095
2096                                 mul_m3_v3(to_pnor_2d_mat, pcent_dst);
2097                                 poly_dst_2d_z = pcent_dst[2];
2098
2099                                 /* Get (2D) bounding square of our poly. */
2100                                 INIT_MINMAX2(poly_dst_2d_min, poly_dst_2d_max);
2101
2102                                 for (j = 0; j < mp->totloop; j++) {
2103                                         MLoop *ml = &loops_dst[j + mp->loopstart];
2104                                         copy_v3_v3(tmp_co, verts_dst[ml->v].co);
2105                                         if (space_transform) {
2106                                                 BLI_space_transform_apply(space_transform, tmp_co);
2107                                         }
2108                                         mul_v2_m3v3(poly_vcos_2d[j], to_pnor_2d_mat, tmp_co);
2109                                         minmax_v2v2_v2(poly_dst_2d_min, poly_dst_2d_max, poly_vcos_2d[j]);
2110                                 }
2111
2112                                 /* We adjust our ray-casting grid to ray_radius (the smaller, the more rays are cast),
2113                                  * with lower/upper bounds. */
2114                                 sub_v2_v2v2(poly_dst_2d_size, poly_dst_2d_max, poly_dst_2d_min);
2115
2116                                 if (ray_radius) {
2117                                         tot_rays = (int)((max_ff(poly_dst_2d_size[0], poly_dst_2d_size[1]) / ray_radius) + 0.5f);
2118                                         CLAMP(tot_rays, MREMAP_RAYCAST_TRI_SAMPLES_MIN, MREMAP_RAYCAST_TRI_SAMPLES_MAX);
2119                                 }
2120                                 else {
2121                                         /* If no radius (pure rays), give max number of rays! */
2122                                         tot_rays = MREMAP_RAYCAST_TRI_SAMPLES_MIN;
2123                                 }
2124                                 tot_rays *= tot_rays;
2125
2126                                 poly_area_2d_inv = area_poly_v2((const float(*)[2])poly_vcos_2d, (unsigned int)mp->totloop);
2127                                 /* In case we have a null-area degenerated poly... */
2128                                 poly_area_2d_inv = 1.0f / max_ff(poly_area_2d_inv, 1e-9f);
2129
2130                                 /* Tessellate our poly. */
2131                                 if (mp->totloop == 3) {
2132                                         tri_vidx_2d[0][0] = 0;
2133                                         tri_vidx_2d[0][1] = 1;
2134                                         tri_vidx_2d[0][2] = 2;
2135                                 }
2136                                 if (mp->totloop == 4) {
2137                                         tri_vidx_2d[0][0] = 0;
2138                                         tri_vidx_2d[0][1] = 1;
2139                                         tri_vidx_2d[0][2] = 2;
2140                                         tri_vidx_2d[1][0] = 0;
2141                                         tri_vidx_2d[1][1] = 2;
2142                                         tri_vidx_2d[1][2] = 3;
2143                                 }
2144                                 else {
2145                                         BLI_polyfill_calc(
2146                                                 poly_vcos_2d, (unsigned int)mp->totloop, -1,
2147                                                 (unsigned int (*)[3])tri_vidx_2d);
2148                                 }
2149
2150                                 for (j = 0; j < tris_num; j++) {
2151                                         float *v1 = poly_vcos_2d[tri_vidx_2d[j][0]];
2152                                         float *v2 = poly_vcos_2d[tri_vidx_2d[j][1]];
2153                                         float *v3 = poly_vcos_2d[tri_vidx_2d[j][2]];
2154                                         int rays_num;
2155
2156                                         /* All this allows us to get 'absolute' number of rays for each tri, avoiding accumulating
2157                                          * errors over iterations, and helping better even distribution. */
2158                                         done_area += area_tri_v2(v1, v2, v3);
2159                                         rays_num = max_ii((int)((float)tot_rays * done_area * poly_area_2d_inv + 0.5f) - done_rays, 0);
2160                                         done_rays += rays_num;
2161
2162                                         while (rays_num--) {
2163                                                 int n = (ray_radius > 0.0f) ? MREMAP_RAYCAST_APPROXIMATE_NR : 1;
2164                                                 float w = 1.0f;
2165
2166                                                 BLI_rng_get_tri_sample_float_v2(rng, v1, v2, v3, tmp_co);
2167
2168                                                 tmp_co[2] = poly_dst_2d_z;
2169                                                 mul_m3_v3(from_pnor_2d_mat, tmp_co);
2170
2171                                                 /* At this point, tmp_co is a point on our poly surface, in mesh_src space! */
2172                                                 while (n--) {
2173                                                         if (mesh_remap_bvhtree_query_raycast(
2174                                                                 &treedata, &rayhit, tmp_co, tmp_no, ray_radius / w, max_dist, &hit_dist))
2175                                                         {
2176                                                                 const MLoopTri *lt = &treedata.looptri[rayhit.index];
2177
2178                                                                 weights[lt->poly] += w;
2179                                                                 totweights += w;
2180                                                                 hit_dist_accum += hit_dist;
2181                                                                 break;
2182                                                         }
2183                                                         /* Next iteration will get bigger radius but smaller weight! */
2184                                                         w /= MREMAP_RAYCAST_APPROXIMATE_FAC;
2185                                                 }
2186                                         }
2187                                 }
2188
2189                                 if (totweights > 0.0f) {
2190                                         for (j = 0; j < (int)numpolys_src; j++) {
2191                                                 if (!weights[j]) {
2192                                                         continue;
2193                                                 }
2194                                                 /* Note: sources_num is always <= j! */
2195                                                 weights[sources_num] = weights[j] / totweights;
2196                                                 indices[sources_num] = j;
2197                                                 sources_num++;
2198                                         }
2199                                         mesh_remap_item_define(r_map, i, hit_dist_accum / totweights, 0, sources_num, indices, weights);
2200                                 }
2201                                 else {
2202                                         /* No source for this dest poly! */
2203                                         BKE_mesh_remap_item_define_invalid(r_map, i);
2204                                 }
2205                         }
2206
2207                         MEM_freeN(tri_vidx_2d);
2208                         MEM_freeN(poly_vcos_2d);
2209                         MEM_freeN(indices);
2210                         MEM_freeN(weights);
2211                         BLI_rng_free(rng);
2212                 }
2213                 else {
2214                         CLOG_WARN(&LOG, "Unsupported mesh-to-mesh poly mapping mode (%d)!", mode);
2215                         memset(r_map->items, 0, sizeof(*r_map->items) * (size_t)numpolys_dst);
2216                 }
2217
2218                 free_bvhtree_from_mesh(&treedata);
2219         }
2220 }
2221
2222 #undef MREMAP_RAYCAST_APPROXIMATE_NR
2223 #undef MREMAP_RAYCAST_APPROXIMATE_FAC
2224 #undef MREMAP_RAYCAST_TRI_SAMPLES_MIN
2225 #undef MREMAP_RAYCAST_TRI_SAMPLES_MAX
2226 #undef MREMAP_DEFAULT_BUFSIZE
2227
2228 /** \} */