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