Cleanup: doxygen comments
[blender-staging.git] / source / blender / editors / transform / transform_snap_object.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/editors/transform/transform_snap_object.c
22  *  \ingroup edtransform
23  */
24
25 #include <stdlib.h>
26 #include <math.h>
27 #include <float.h>
28 #include <stdio.h>
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BLI_math.h"
33 #include "BLI_kdopbvh.h"
34 #include "BLI_memarena.h"
35 #include "BLI_ghash.h"
36 #include "BLI_linklist.h"
37 #include "BLI_listbase.h"
38 #include "BLI_utildefines.h"
39
40 #include "DNA_armature_types.h"
41 #include "DNA_curve_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_view3d_types.h"
47
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_object.h"
50 #include "BKE_anim.h"  /* for duplis */
51 #include "BKE_editmesh.h"
52 #include "BKE_main.h"
53 #include "BKE_tracking.h"
54
55 #include "ED_transform.h"
56 #include "ED_transform_snap_object_context.h"
57 #include "ED_view3d.h"
58 #include "ED_armature.h"
59
60 #include "transform.h"
61
62 /* -------------------------------------------------------------------- */
63 /** Internal Data Types
64  * \{ */
65
66 enum eViewProj {
67         VIEW_PROJ_NONE = -1,
68         VIEW_PROJ_ORTHO = 0,
69         VIEW_PROJ_PERSP = -1,
70 };
71
72 typedef struct SnapData {
73         short snap_to;
74         float mval[2];
75         float ray_origin[3];
76         float ray_start[3];
77         float ray_dir[3];
78         float pmat[4][4]; /* perspective matrix */
79         float win_half[2];/* win x and y */
80         enum eViewProj view_proj;
81         float depth_range[2];
82 } SnapData;
83
84 typedef struct SnapObjectData {
85         enum {
86                 SNAP_MESH = 1,
87                 SNAP_EDIT_MESH,
88         } type;
89 } SnapObjectData;
90
91 typedef struct SnapObjectData_Mesh {
92         SnapObjectData sd;
93         BVHTreeFromMesh *bvh_trees[3];
94         MPoly *mpoly;
95         bool poly_allocated;
96
97 } SnapObjectData_Mesh;
98
99 typedef struct SnapObjectData_EditMesh {
100         SnapObjectData sd;
101         BVHTreeFromEditMesh *bvh_trees[3];
102
103 } SnapObjectData_EditMesh;
104
105 struct SnapObjectContext {
106         Main *bmain;
107         Scene *scene;
108         int flag;
109
110         /* Optional: when performing screen-space projection.
111          * otherwise this doesn't take viewport into account. */
112         bool use_v3d;
113         struct {
114                 const struct View3D *v3d;
115                 const struct ARegion *ar;
116         } v3d_data;
117
118
119         /* Object -> SnapObjectData map */
120         struct {
121                 GHash *object_map;
122                 MemArena *mem_arena;
123         } cache;
124
125         /* Filter data, returns true to check this value */
126         struct {
127                 struct {
128                         bool (*test_vert_fn)(BMVert *, void *user_data);
129                         bool (*test_edge_fn)(BMEdge *, void *user_data);
130                         bool (*test_face_fn)(BMFace *, void *user_data);
131                         void *user_data;
132                 } edit_mesh;
133         } callbacks;
134
135 };
136
137 /** \} */
138
139 /* -------------------------------------------------------------------- */
140 /** Common Utilities
141  * \{ */
142
143
144 typedef void(*IterSnapObjsCallback)(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data);
145
146 /**
147  * Walks through all objects in the scene to create the list of objets to snap.
148  *
149  * \param sctx: Snap context to store data.
150  * \param snap_select : from enum eSnapSelect.
151  * \param obedit : Object Edited to use its coordinates of BMesh(if any) to do the snapping.
152  */
153 static void iter_snap_objects(
154         SnapObjectContext *sctx,
155         const eSnapSelect snap_select,
156         Object *obedit,
157         IterSnapObjsCallback sob_callback,
158         void *data)
159 {
160         Base *base_act = sctx->scene->basact;
161         for (Base *base = sctx->scene->base.first; base != NULL; base = base->next) {
162                 if ((BASE_VISIBLE_BGMODE(sctx->v3d_data.v3d, sctx->scene, base)) &&
163                     (base->flag & BA_SNAP_FIX_DEPS_FIASCO) == 0 &&
164                     !((snap_select == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL))) ||
165                       (snap_select == SNAP_NOT_ACTIVE && base == base_act)))
166                 {
167                         bool use_obedit;
168                         Object *obj = base->object;
169                         if (obj->transflag & OB_DUPLI) {
170                                 DupliObject *dupli_ob;
171                                 ListBase *lb = object_duplilist(sctx->bmain->eval_ctx, sctx->scene, obj);
172                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
173                                         use_obedit = obedit && dupli_ob->ob->data == obedit->data;
174                                         sob_callback(sctx, use_obedit, use_obedit ? obedit : dupli_ob->ob, dupli_ob->mat, data);
175                                 }
176                                 free_object_duplilist(lb);
177                         }
178
179                         use_obedit = obedit && obj->data == obedit->data;
180                         sob_callback(sctx, use_obedit, use_obedit ? obedit : obj, obj->obmat, data);
181                 }
182         }
183 }
184
185
186 /**
187  * Generates a struct with the immutable parameters that will be used on all objects.
188  *
189  * \param snap_to: Element to snap, Vertice, Edge or Face.
190  * \param view_proj: ORTHO or PERSP.
191  * Currently only works one at a time, but can eventually operate as flag.
192  *
193  * \param mval: Mouse coords.
194  * (When NULL, ray-casting is handled without any projection matrix correction.)
195  * \param ray_origin: ray_start before being moved toward the ray_normal at the distance from vew3d clip_min.
196  * \param ray_start: ray_origin moved for the start clipping plane (clip_min).
197  * \param ray_direction: Unit length direction of the ray.
198  * \param depth_range: distances of clipe plane min and clip plane max;
199  */
200 static void snap_data_set(
201         SnapData *snapdata,
202         const ARegion *ar, const unsigned short snap_to, const enum eViewProj view_proj,
203         const float mval[2], const float ray_origin[3], const float ray_start[3],
204         const float ray_direction[3], const float depth_range[2])
205 {
206         copy_m4_m4(snapdata->pmat, ((RegionView3D *)ar->regiondata)->persmat);
207         snapdata->win_half[0] = ar->winx / 2;
208         snapdata->win_half[1] = ar->winy / 2;
209         copy_v2_v2(snapdata->mval, mval);
210         snapdata->snap_to = snap_to;
211         copy_v3_v3(snapdata->ray_origin, ray_origin);
212         copy_v3_v3(snapdata->ray_start, ray_start);
213         copy_v3_v3(snapdata->ray_dir, ray_direction);
214         snapdata->view_proj = view_proj;
215         copy_v2_v2(snapdata->depth_range, depth_range);
216 }
217
218
219 MINLINE float depth_get(const float co[3], const float ray_start[3], const float ray_dir[3])
220 {
221         float dvec[3];
222         sub_v3_v3v3(dvec, co, ray_start);
223         return dot_v3v3(dvec, ray_dir);
224 }
225
226
227 static bool walk_parent_bvhroot_cb(const BVHTreeAxisRange *bounds, void *userdata)
228 {
229         BVHTreeRay *ray = userdata;
230         const float bbmin[3] = {bounds[0].min, bounds[1].min, bounds[2].min};
231         const float bbmax[3] = {bounds[0].max, bounds[1].max, bounds[2].max};
232         if (!isect_ray_aabb_v3_simple(ray->origin, ray->direction, bbmin, bbmax, &ray->radius, NULL)) {
233                 ray->radius = -1;
234         }
235         return false;
236 }
237
238
239 static bool isect_ray_bvhroot_v3(struct BVHTree *tree, const float ray_start[3], const float ray_dir[3], float *depth)
240 {
241         BVHTreeRay ray;
242         copy_v3_v3(ray.origin, ray_start);
243         copy_v3_v3(ray.direction, ray_dir);
244
245         BLI_bvhtree_walk_dfs(tree, walk_parent_bvhroot_cb, NULL, NULL, &ray);
246
247         if (ray.radius > 0) {
248                 *depth = ray.radius;
249                 return true;
250         }
251         else {
252                 return false;
253         }
254 }
255
256
257 static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt);
258
259 /** \} */
260
261 /* -------------------------------------------------------------------- */
262 /** \name Ray Cast Funcs
263  * \{ */
264
265 /* Store all ray-hits
266  * Support for storing all depths, not just the first (raycast 'all') */
267
268 struct RayCastAll_Data {
269         void *bvhdata;
270
271         /* internal vars for adding depths */
272         BVHTree_RayCastCallback raycast_callback;
273
274         const float(*obmat)[4];
275         const float(*timat)[3];
276
277         float len_diff;
278         float local_scale;
279
280         Object *ob;
281         unsigned int ob_uuid;
282
283         /* output data */
284         ListBase *hit_list;
285         bool retval;
286 };
287
288
289 static struct SnapObjectHitDepth *hit_depth_create(
290         const float depth, const float co[3], const float no[3], int index,
291         Object *ob, const float obmat[4][4], unsigned int ob_uuid)
292 {
293         struct SnapObjectHitDepth *hit = MEM_mallocN(sizeof(*hit), __func__);
294
295         hit->depth = depth;
296         copy_v3_v3(hit->co, co);
297         copy_v3_v3(hit->no, no);
298         hit->index = index;
299
300         hit->ob = ob;
301         copy_m4_m4(hit->obmat, (float(*)[4])obmat);
302         hit->ob_uuid = ob_uuid;
303
304         return hit;
305 }
306
307 static int hit_depth_cmp(const void *arg1, const void *arg2)
308 {
309         const struct SnapObjectHitDepth *h1 = arg1;
310         const struct SnapObjectHitDepth *h2 = arg2;
311         int val = 0;
312
313         if (h1->depth < h2->depth) {
314                 val = -1;
315         }
316         else if (h1->depth > h2->depth) {
317                 val = 1;
318         }
319
320         return val;
321 }
322
323 static void raycast_all_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
324 {
325         struct RayCastAll_Data *data = userdata;
326         data->raycast_callback(data->bvhdata, index, ray, hit);
327         if (hit->index != -1) {
328                 /* get all values in worldspace */
329                 float location[3], normal[3];
330                 float depth;
331
332                 /* worldspace location */
333                 mul_v3_m4v3(location, (float(*)[4])data->obmat, hit->co);
334                 depth = (hit->dist + data->len_diff) / data->local_scale;
335
336                 /* worldspace normal */
337                 copy_v3_v3(normal, hit->no);
338                 mul_m3_v3((float(*)[3])data->timat, normal);
339                 normalize_v3(normal);
340
341                 /* currently unused, and causes issues when looptri's haven't been calculated.
342                  * since theres some overhead in ensuring this data is valid, it may need to be optional. */
343 #if 0
344                 if (data->dm) {
345                         hit->index = dm_looptri_to_poly_index(data->dm, &data->dm_looptri[hit->index]);
346                 }
347 #endif
348
349                 struct SnapObjectHitDepth *hit_item = hit_depth_create(
350                         depth, location, normal, hit->index,
351                         data->ob, data->obmat, data->ob_uuid);
352                 BLI_addtail(data->hit_list, hit_item);
353         }
354 }
355
356
357 static bool raycastDerivedMesh(
358         SnapObjectContext *sctx,
359         const float ray_start[3], const float ray_dir[3],
360         Object *ob, DerivedMesh *dm, float obmat[4][4], const unsigned int ob_index,
361         /* read/write args */
362         float *ray_depth,
363         /* return args */
364         float r_loc[3], float r_no[3], int *r_index,
365         ListBase *r_hit_list)
366 {
367         bool retval = false;
368
369         if (dm->getNumPolys(dm) == 0) {
370                 return retval;
371         }
372
373         float imat[4][4];
374         float timat[3][3]; /* transpose inverse matrix for normals */
375         float ray_start_local[3], ray_normal_local[3];
376         float local_scale, local_depth, len_diff = 0.0f;
377
378         invert_m4_m4(imat, obmat);
379         transpose_m3_m4(timat, imat);
380
381         copy_v3_v3(ray_start_local, ray_start);
382         copy_v3_v3(ray_normal_local, ray_dir);
383
384         mul_m4_v3(imat, ray_start_local);
385         mul_mat3_m4_v3(imat, ray_normal_local);
386
387         /* local scale in normal direction */
388         local_scale = normalize_v3(ray_normal_local);
389         local_depth = *ray_depth;
390         if (local_depth != BVH_RAYCAST_DIST_MAX) {
391                 local_depth *= local_scale;
392         }
393
394         /* Test BoundBox */
395         BoundBox *bb = BKE_object_boundbox_get(ob);
396         if (bb) {
397                 /* was BKE_boundbox_ray_hit_check, see: cf6ca226fa58 */
398                 if (!isect_ray_aabb_v3_simple(
399                         ray_start_local, ray_normal_local, bb->vec[0], bb->vec[6], &len_diff, NULL))
400                 {
401                         return retval;
402                 }
403         }
404
405         SnapObjectData_Mesh *sod = NULL;
406         BVHTreeFromMesh *treedata;
407
408         void **sod_p;
409         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
410                 sod = *sod_p;
411         }
412         else {
413                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
414                 sod->sd.type = SNAP_MESH;
415         }
416
417         if (sod->bvh_trees[2] == NULL) {
418                 sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
419         }
420
421         treedata = sod->bvh_trees[2];
422
423         if (treedata) {
424                 /* the tree is owned by the DM and may have been freed since we last used! */
425                 if (treedata->tree) {
426                         if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
427                                 free_bvhtree_from_mesh(treedata);
428                         }
429                         else {
430                                 if (treedata->vert == NULL) {
431                                         treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
432                                 }
433                                 if (treedata->loop == NULL) {
434                                         treedata->loop = DM_get_loop_array(dm, &treedata->loop_allocated);
435                                 }
436                                 if (treedata->looptri == NULL) {
437                                         if (sod->mpoly == NULL) {
438                                                 sod->mpoly = DM_get_poly_array(dm, &sod->poly_allocated);
439                                         }
440                                         treedata->looptri = dm->getLoopTriArray(dm);
441                                         treedata->looptri_allocated = false;
442                                 }
443                         }
444                 }
445
446                 if (treedata->tree == NULL) {
447                         bvhtree_from_mesh_looptri(treedata, dm, 0.0f, 4, 6);
448
449                         if (treedata->tree == NULL) {
450                                 return retval;
451                         }
452                 }
453         }
454         else {
455                 return retval;
456         }
457
458         /* Only use closer ray_start in case of ortho view! In perspective one, ray_start may already
459          * been *inside* boundbox, leading to snap failures (see T38409).
460          * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
461          */
462         if (len_diff == 0.0f) {  /* do_ray_start_correction */
463                 /* We *need* a reasonably valid len_diff in this case.
464                  * Get the distance to bvhtree root */
465                 if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
466                         return retval;
467                 }
468         }
469         /* You need to make sure that ray_start is really far away,
470          * because even in the Orthografic view, in some cases,
471          * the ray can start inside the object (see T50486) */
472         if (len_diff > 400.0f) {
473                 /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
474                  * very far away ray_start values (as returned in case of ortho view3d), see T38358.
475                  */
476                 len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
477                 madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
478                 local_depth -= len_diff;
479         }
480         else {
481                 len_diff = 0.0f;
482         }
483         if (r_hit_list) {
484                 struct RayCastAll_Data data;
485
486                 data.bvhdata = treedata;
487                 data.raycast_callback = treedata->raycast_callback;
488                 data.obmat = obmat;
489                 data.timat = timat;
490                 data.len_diff = len_diff;
491                 data.local_scale = local_scale;
492                 data.ob = ob;
493                 data.ob_uuid = ob_index;
494                 data.hit_list = r_hit_list;
495                 data.retval = retval;
496
497                 BLI_bvhtree_ray_cast_all(
498                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
499                         *ray_depth, raycast_all_cb, &data);
500
501                 retval = data.retval;
502         }
503         else {
504                 BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
505
506                 if (BLI_bvhtree_ray_cast(
507                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
508                         &hit, treedata->raycast_callback, treedata) != -1)
509                 {
510                         hit.dist += len_diff;
511                         hit.dist /= local_scale;
512                         if (hit.dist <= *ray_depth) {
513                                 *ray_depth = hit.dist;
514                                 copy_v3_v3(r_loc, hit.co);
515
516                                 /* back to worldspace */
517                                 mul_m4_v3(obmat, r_loc);
518
519                                 if (r_no) {
520                                         copy_v3_v3(r_no, hit.no);
521                                         mul_m3_v3(timat, r_no);
522                                         normalize_v3(r_no);
523                                 }
524
525                                 retval = true;
526
527                                 if (r_index) {
528                                         *r_index = dm_looptri_to_poly_index(dm, &treedata->looptri[hit.index]);
529                                 }
530                         }
531                 }
532         }
533
534         return retval;
535 }
536
537 static bool raycastEditMesh(
538         SnapObjectContext *sctx,
539         const float ray_start[3], const float ray_dir[3],
540         Object *ob, BMEditMesh *em, float obmat[4][4], const unsigned int ob_index,
541         /* read/write args */
542         float *ray_depth,
543         /* return args */
544         float r_loc[3], float r_no[3], int *r_index,
545         ListBase *r_hit_list)
546 {
547         bool retval = false;
548         if (em->bm->totface == 0) {
549                 return retval;
550         }
551
552         SnapObjectData_EditMesh *sod = NULL;
553         BVHTreeFromEditMesh *treedata = NULL;
554
555         void **sod_p;
556         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
557                 sod = *sod_p;
558         }
559         else {
560                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
561                 sod->sd.type = SNAP_EDIT_MESH;
562         }
563
564         if (sod->bvh_trees[2] == NULL) {
565                 sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
566         }
567         treedata = sod->bvh_trees[2];
568
569         if (treedata) {
570                 if (treedata->tree == NULL) {
571                         BLI_bitmap *elem_mask = NULL;
572                         int looptri_num_active = -1;
573
574                         if (sctx->callbacks.edit_mesh.test_face_fn) {
575                                 elem_mask = BLI_BITMAP_NEW(em->tottri, __func__);
576                                 looptri_num_active = BM_iter_mesh_bitmap_from_filter_tessface(
577                                         em->bm, elem_mask,
578                                         sctx->callbacks.edit_mesh.test_face_fn, sctx->callbacks.edit_mesh.user_data);
579                         }
580                         bvhtree_from_editmesh_looptri_ex(treedata, em, elem_mask, looptri_num_active, 0.0f, 4, 6, NULL);
581
582                         if (elem_mask) {
583                                 MEM_freeN(elem_mask);
584                         }
585                 }
586                 if (treedata->tree == NULL) {
587                         return retval;
588                 }
589         }
590         else {
591                 return retval;
592         }
593
594         float imat[4][4];
595         float timat[3][3]; /* transpose inverse matrix for normals */
596         float ray_normal_local[3], ray_start_local[3], len_diff = 0.0f;
597
598         invert_m4_m4(imat, obmat);
599         transpose_m3_m4(timat, imat);
600
601         copy_v3_v3(ray_normal_local, ray_dir);
602         mul_mat3_m4_v3(imat, ray_normal_local);
603
604         copy_v3_v3(ray_start_local, ray_start);
605         mul_m4_v3(imat, ray_start_local);
606
607         /* local scale in normal direction */
608         float local_scale = normalize_v3(ray_normal_local);
609         float local_depth = *ray_depth;
610         if (local_depth != BVH_RAYCAST_DIST_MAX) {
611                 local_depth *= local_scale;
612         }
613
614         /* Only use closer ray_start in case of ortho view! In perspective one, ray_start
615          * may already been *inside* boundbox, leading to snap failures (see T38409).
616          * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
617          */
618         if (sctx->use_v3d && !((RegionView3D *)sctx->v3d_data.ar->regiondata)->is_persp) {  /* do_ray_start_correction */
619                 /* We *need* a reasonably valid len_diff in this case.
620                  * Get the distance to bvhtree root */
621                 if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
622                         return retval;
623                 }
624                 /* You need to make sure that ray_start is really far away,
625                  * because even in the Orthografic view, in some cases,
626                  * the ray can start inside the object (see T50486) */
627                 if (len_diff > 400.0f) {
628                         /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
629                          * very far away ray_start values (as returned in case of ortho view3d), see T38358.
630                          */
631                         len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
632                         madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
633                         local_depth -= len_diff;
634                 }
635                 else len_diff = 0.0f;
636         }
637         if (r_hit_list) {
638                 struct RayCastAll_Data data;
639
640                 data.bvhdata = treedata;
641                 data.raycast_callback = treedata->raycast_callback;
642                 data.obmat = obmat;
643                 data.timat = timat;
644                 data.len_diff = len_diff;
645                 data.local_scale = local_scale;
646                 data.ob = ob;
647                 data.ob_uuid = ob_index;
648                 data.hit_list = r_hit_list;
649                 data.retval = retval;
650
651                 BLI_bvhtree_ray_cast_all(
652                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
653                         *ray_depth, raycast_all_cb, &data);
654
655                 retval = data.retval;
656         }
657         else {
658                 BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
659
660                 if (BLI_bvhtree_ray_cast(
661                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
662                         &hit, treedata->raycast_callback, treedata) != -1)
663                 {
664                         hit.dist += len_diff;
665                         hit.dist /= local_scale;
666                         if (hit.dist <= *ray_depth) {
667                                 *ray_depth = hit.dist;
668                                 copy_v3_v3(r_loc, hit.co);
669
670                                 /* back to worldspace */
671                                 mul_m4_v3(obmat, r_loc);
672
673                                 if (r_no) {
674                                         copy_v3_v3(r_no, hit.no);
675                                         mul_m3_v3(timat, r_no);
676                                         normalize_v3(r_no);
677                                 }
678
679                                 retval = true;
680
681                                 if (r_index) {
682                                         *r_index = hit.index;
683                                 }
684                         }
685                 }
686         }
687
688         return retval;
689 }
690
691
692 /**
693  * \param use_obedit: Uses the coordinates of BMesh (if any) to do the snapping;
694  *
695  * \note Duplicate args here are documented at #snapObjectsRay
696  */
697 static bool raycastObj(
698         SnapObjectContext *sctx,
699         const float ray_start[3], const float ray_dir[3],
700         Object *ob, float obmat[4][4], const unsigned int ob_index,
701         bool use_obedit,
702         /* read/write args */
703         float *ray_depth,
704         /* return args */
705         float r_loc[3], float r_no[3], int *r_index,
706         Object **r_ob, float r_obmat[4][4],
707         ListBase *r_hit_list)
708 {
709         bool retval = false;
710
711         if (ob->type == OB_MESH) {
712                 BMEditMesh *em;
713
714                 if (use_obedit) {
715                         em = BKE_editmesh_from_object(ob);
716                         retval = raycastEditMesh(
717                                 sctx,
718                                 ray_start, ray_dir,
719                                 ob, em, obmat, ob_index,
720                                 ray_depth, r_loc, r_no, r_index, r_hit_list);
721                 }
722                 else {
723                         /* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
724                          * still set the 'em' to NULL, since we only want the 'dm'. */
725                         DerivedMesh *dm;
726                         em = BKE_editmesh_from_object(ob);
727                         if (em) {
728                                 editbmesh_get_derived_cage_and_final(sctx->scene, ob, em, CD_MASK_BAREMESH, &dm);
729                         }
730                         else {
731                                 dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
732                         }
733                         retval = raycastDerivedMesh(
734                                 sctx,
735                                 ray_start, ray_dir,
736                                 ob, dm, obmat, ob_index,
737                                 ray_depth, r_loc, r_no, r_index, r_hit_list);
738                 }
739         }
740
741         if (retval) {
742                 if (r_ob) {
743                         *r_ob = ob;
744                         copy_m4_m4(r_obmat, obmat);
745                 }
746         }
747
748         return retval;
749 }
750
751
752 struct RaycastObjUserData {
753         const float *ray_start;
754         const float *ray_dir;
755         unsigned int ob_index;
756         /* read/write args */
757         float *ray_depth;
758         /* return args */
759         float *r_loc;
760         float *r_no;
761         int *r_index;
762         Object **r_ob;
763         float (*r_obmat)[4];
764         ListBase *r_hit_list;
765         bool ret;
766 };
767
768 static void raycast_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
769 {
770         struct RaycastObjUserData *dt = data;
771         dt->ret |= raycastObj(
772                 sctx,
773                 dt->ray_start, dt->ray_dir,
774                 ob, obmat, dt->ob_index++, is_obedit,
775                 dt->ray_depth,
776                 dt->r_loc, dt->r_no, dt->r_index,
777                 dt->r_ob, dt->r_obmat,
778                 dt->r_hit_list);
779 }
780
781 /**
782  * Main RayCast Function
783  * ======================
784  *
785  * Walks through all objects in the scene to find the `hit` on object surface.
786  *
787  * \param sctx: Snap context to store data.
788  * \param snap_select : from enum eSnapSelect.
789  * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
790  * \param obj_list: List with objects to snap (created in `create_object_list`).
791  *
792  * Read/Write Args
793  * ---------------
794  *
795  * \param ray_depth: maximum depth allowed for r_co, elements deeper than this value will be ignored.
796  *
797  * Output Args
798  * -----------
799  *
800  * \param r_loc: Hit location.
801  * \param r_no: Hit normal (optional).
802  * \param r_index: Hit index or -1 when no valid index is found.
803  * (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
804  * \param r_ob: Hit object.
805  * \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
806  * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
807  *
808  */
809 static bool raycastObjects(
810         SnapObjectContext *sctx,
811         const float ray_start[3], const float ray_dir[3],
812         const eSnapSelect snap_select, const bool use_object_edit_cage,
813         /* read/write args */
814         float *ray_depth,
815         /* return args */
816         float r_loc[3], float r_no[3], int *r_index,
817         Object **r_ob, float r_obmat[4][4],
818         ListBase *r_hit_list)
819 {
820         Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
821
822         struct RaycastObjUserData data = {
823                 .ray_start = ray_start,
824                 .ray_dir = ray_dir,
825                 .ob_index = 0,
826                 .ray_depth = ray_depth,
827                 .r_loc = r_loc,
828                 .r_no = r_no,
829                 .r_index = r_index,
830                 .r_ob = r_ob,
831                 .r_obmat = r_obmat,
832                 .r_hit_list = r_hit_list,
833                 .ret = false,
834         };
835
836         iter_snap_objects(sctx, snap_select, obedit, raycast_obj_cb, &data);
837
838         return data.ret;
839 }
840
841
842 /** \} */
843
844 /* -------------------------------------------------------------------- */
845 /** Snap Nearest utilities
846  * \{ */
847
848 static void copy_dm_vert_no(const int index, float r_no[3], const BVHTreeFromMesh *data)
849 {
850         const MVert *vert = data->vert + index;
851
852         normal_short_to_float_v3(r_no, vert->no);
853 }
854
855 static void copy_bvert_no(const int index, float r_no[3], const BVHTreeFromEditMesh *data)
856 {
857         BMVert *eve = BM_vert_at_index(data->em->bm, index);
858
859         copy_v3_v3(r_no, eve->no);
860 }
861
862 static void get_dm_edge_verts(const int index, const float *v_pair[2], const BVHTreeFromMesh *data)
863 {
864         const MVert *vert = data->vert;
865         const MEdge *edge = data->edge + index;
866
867         v_pair[0] = vert[edge->v1].co;
868         v_pair[1] = vert[edge->v2].co;
869 }
870
871 static void get_bedge_verts(const int index, const float *v_pair[2], const BVHTreeFromEditMesh *data)
872 {
873         BMEdge *eed = BM_edge_at_index(data->em->bm, index);
874
875         v_pair[0] = eed->v1->co;
876         v_pair[1] = eed->v2->co;
877 }
878
879 static bool test_projected_vert_dist(
880         const float depth_range[2], const float mval[2], const float co[3],
881         float pmat[4][4], const float win_half[2], const bool is_persp,
882         float *dist_px_sq, float r_co[3])
883 {
884         float depth;
885         if (is_persp) {
886                 depth = mul_project_m4_v3_zfac(pmat, co);
887                 if (depth < depth_range[0] || depth > depth_range[1]) {
888                         return false;
889                 }
890         }
891
892         float co2d[2] = {
893                 (dot_m4_v3_row_x(pmat, co) + pmat[3][0]),
894                 (dot_m4_v3_row_y(pmat, co) + pmat[3][1]),
895         };
896
897         if (is_persp) {
898                 mul_v2_fl(co2d, 1 / depth);
899         }
900
901         co2d[0] += 1.0f;
902         co2d[1] += 1.0f;
903         co2d[0] *= win_half[0];
904         co2d[1] *= win_half[1];
905
906         const float dist_sq = len_squared_v2v2(mval, co2d);
907         if (dist_sq < *dist_px_sq) {
908                 copy_v3_v3(r_co, co);
909                 *dist_px_sq = dist_sq;
910                 return true;
911         }
912         return false;
913 }
914
915 static bool test_projected_edge_dist(
916         const float depth_range[2], const float mval[2],
917         float pmat[4][4], const float win_half[2], const bool is_persp,
918         const float ray_start[3], const float ray_dir[3],
919         const float va[3], const float vb[3],
920         float *dist_px_sq, float r_co[3])
921 {
922
923         float tmp_co[3], depth;
924         dist_squared_ray_to_seg_v3(ray_start, ray_dir, va, vb, tmp_co, &depth);
925         return test_projected_vert_dist(depth_range, mval, tmp_co, pmat, win_half, is_persp, dist_px_sq, r_co);
926 }
927 typedef struct Nearest2dPrecalc {
928         float ray_origin_local[3];
929         float ray_direction_local[3];
930         float ray_inv_dir[3];
931
932         float ray_min_dist;
933         float pmat[4][4]; /* perspective matrix multiplied by object matrix */
934         bool is_persp;
935         float win_half[2];
936
937         float mval[2];
938         bool sign[3];
939 } Nearest2dPrecalc;
940
941 /**
942  * \param lpmat: Perspective matrix multiplied by object matrix
943  */
944 static void dist_squared_to_projected_aabb_precalc(
945         struct Nearest2dPrecalc *neasrest_precalc,
946         float lpmat[4][4], bool is_persp, const float win_half[2],
947         const float ray_min_dist, const float mval[2],
948         const float ray_origin_local[3], const float ray_direction_local[3])
949 {
950         copy_m4_m4(neasrest_precalc->pmat, lpmat);
951         neasrest_precalc->is_persp = is_persp;
952         copy_v2_v2(neasrest_precalc->win_half, win_half);
953         neasrest_precalc->ray_min_dist = ray_min_dist;
954
955         copy_v3_v3(neasrest_precalc->ray_origin_local, ray_origin_local);
956         copy_v3_v3(neasrest_precalc->ray_direction_local, ray_direction_local);
957         copy_v2_v2(neasrest_precalc->mval, mval);
958
959         for (int i = 0; i < 3; i++) {
960                 neasrest_precalc->ray_inv_dir[i] =
961                         (neasrest_precalc->ray_direction_local[i] != 0.0f) ?
962                         (1.0f / neasrest_precalc->ray_direction_local[i]) : FLT_MAX;
963                 neasrest_precalc->sign[i] = (neasrest_precalc->ray_inv_dir[i] < 0.0f);
964         }
965 }
966
967 /* Returns the distance from a 2d coordinate to a BoundBox (Projected) */
968 static float dist_squared_to_projected_aabb(
969         struct Nearest2dPrecalc *data,
970         const float bbmin[3], const float bbmax[3],
971         bool r_axis_closest[3])
972 {
973         float local_bvmin[3], local_bvmax[3];
974         if (data->sign[0]) {
975                 local_bvmin[0] = bbmax[0];
976                 local_bvmax[0] = bbmin[0];
977         }
978         else {
979                 local_bvmin[0] = bbmin[0];
980                 local_bvmax[0] = bbmax[0];
981         }
982         if (data->sign[1]) {
983                 local_bvmin[1] = bbmax[1];
984                 local_bvmax[1] = bbmin[1];
985         }
986         else {
987                 local_bvmin[1] = bbmin[1];
988                 local_bvmax[1] = bbmax[1];
989         }
990         if (data->sign[2]) {
991                 local_bvmin[2] = bbmax[2];
992                 local_bvmax[2] = bbmin[2];
993         }
994         else {
995                 local_bvmin[2] = bbmin[2];
996                 local_bvmax[2] = bbmax[2];
997         }
998
999         const float tmin[3] = {
1000                 (local_bvmin[0] - data->ray_origin_local[0]) * data->ray_inv_dir[0],
1001                 (local_bvmin[1] - data->ray_origin_local[1]) * data->ray_inv_dir[1],
1002                 (local_bvmin[2] - data->ray_origin_local[2]) * data->ray_inv_dir[2],
1003         };
1004         const float tmax[3] = {
1005                 (local_bvmax[0] - data->ray_origin_local[0]) * data->ray_inv_dir[0],
1006                 (local_bvmax[1] - data->ray_origin_local[1]) * data->ray_inv_dir[1],
1007                 (local_bvmax[2] - data->ray_origin_local[2]) * data->ray_inv_dir[2],
1008         };
1009         /* `va` and `vb` are the coordinates of the AABB edge closest to the ray */
1010         float va[3], vb[3];
1011         /* `rtmin` and `rtmax` are the minimum and maximum distances of the ray hits on the AABB */
1012         float rtmin, rtmax;
1013         int main_axis;
1014
1015         if ((tmax[0] <= tmax[1]) && (tmax[0] <= tmax[2])) {
1016                 rtmax = tmax[0];
1017                 va[0] = vb[0] = local_bvmax[0];
1018                 main_axis = 3;
1019                 r_axis_closest[0] = data->sign[0];
1020         }
1021         else if ((tmax[1] <= tmax[0]) && (tmax[1] <= tmax[2])) {
1022                 rtmax = tmax[1];
1023                 va[1] = vb[1] = local_bvmax[1];
1024                 main_axis = 2;
1025                 r_axis_closest[1] = data->sign[1];
1026         }
1027         else {
1028                 rtmax = tmax[2];
1029                 va[2] = vb[2] = local_bvmax[2];
1030                 main_axis = 1;
1031                 r_axis_closest[2] = data->sign[2];
1032         }
1033
1034         if ((tmin[0] >= tmin[1]) && (tmin[0] >= tmin[2])) {
1035                 rtmin = tmin[0];
1036                 va[0] = vb[0] = local_bvmin[0];
1037                 main_axis -= 3;
1038                 r_axis_closest[0] = !data->sign[0];
1039         }
1040         else if ((tmin[1] >= tmin[0]) && (tmin[1] >= tmin[2])) {
1041                 rtmin = tmin[1];
1042                 va[1] = vb[1] = local_bvmin[1];
1043                 main_axis -= 1;
1044                 r_axis_closest[1] = !data->sign[1];
1045         }
1046         else {
1047                 rtmin = tmin[2];
1048                 va[2] = vb[2] = local_bvmin[2];
1049                 main_axis -= 2;
1050                 r_axis_closest[2] = !data->sign[2];
1051         }
1052         if (main_axis < 0) {
1053                 main_axis += 3;
1054         }
1055
1056 #define IGNORE_BEHIND_RAY
1057 #ifdef IGNORE_BEHIND_RAY
1058         float depth_max = depth_get(local_bvmax, data->ray_origin_local, data->ray_direction_local);
1059         if (depth_max < data->ray_min_dist) {
1060                 return FLT_MAX;
1061         }
1062 #endif
1063 #undef IGNORE_BEHIND_RAY
1064
1065         /* if rtmin <= rtmax, ray intersect `AABB` */
1066         if (rtmin <= rtmax) {
1067                 return 0;
1068         }
1069
1070         if (data->sign[main_axis]) {
1071                 va[main_axis] = local_bvmax[main_axis];
1072                 vb[main_axis] = local_bvmin[main_axis];
1073         }
1074         else {
1075                 va[main_axis] = local_bvmin[main_axis];
1076                 vb[main_axis] = local_bvmax[main_axis];
1077         }
1078         float scale = fabsf(local_bvmax[main_axis] - local_bvmin[main_axis]);
1079
1080         float (*pmat)[4] = data->pmat;
1081
1082         float va2d[2] = {
1083                 (dot_m4_v3_row_x(pmat, va) + pmat[3][0]),
1084                 (dot_m4_v3_row_y(pmat, va) + pmat[3][1]),
1085         };
1086         float vb2d[2] = {
1087                 (va2d[0] + pmat[main_axis][0] * scale),
1088                 (va2d[1] + pmat[main_axis][1] * scale),
1089         };
1090
1091         if (data->is_persp) {
1092                 float depth_a = mul_project_m4_v3_zfac(pmat, va);
1093                 float depth_b = depth_a + pmat[main_axis][3] * scale;
1094                 va2d[0] /= depth_a;
1095                 va2d[1] /= depth_a;
1096                 vb2d[0] /= depth_b;
1097                 vb2d[1] /= depth_b;
1098         }
1099
1100         va2d[0] += 1.0f;
1101         va2d[1] += 1.0f;
1102         vb2d[0] += 1.0f;
1103         vb2d[1] += 1.0f;
1104
1105         va2d[0] *= data->win_half[0];
1106         va2d[1] *= data->win_half[1];
1107         vb2d[0] *= data->win_half[0];
1108         vb2d[1] *= data->win_half[1];
1109
1110         float dvec[2], edge[2], lambda, rdist;
1111         sub_v2_v2v2(dvec, data->mval, va2d);
1112         sub_v2_v2v2(edge, vb2d, va2d);
1113         lambda = dot_v2v2(dvec, edge);
1114         if (lambda != 0.0f) {
1115                 lambda /= len_squared_v2(edge);
1116                 if (lambda <= 0.0f) {
1117                         rdist = len_squared_v2v2(data->mval, va2d);
1118                         r_axis_closest[main_axis] = true;
1119                 }
1120                 else if (lambda >= 1.0f) {
1121                         rdist = len_squared_v2v2(data->mval, vb2d);
1122                         r_axis_closest[main_axis] = false;
1123                 }
1124                 else {
1125                         va2d[0] += edge[0] * lambda;
1126                         va2d[1] += edge[1] * lambda;
1127                         rdist = len_squared_v2v2(data->mval, va2d);
1128                         r_axis_closest[main_axis] = lambda < 0.5f;
1129                 }
1130         }
1131         else {
1132                 rdist = len_squared_v2v2(data->mval, va2d);
1133         }
1134         return rdist;
1135 }
1136
1137 static float dist_squared_to_projected_aabb_simple(
1138         float lpmat[4][4], const float win_half[2],
1139         const float ray_min_dist, const float mval[2],
1140         const float ray_origin_local[3], const float ray_direction_local[3],
1141         const float bbmin[3], const float bbmax[3])
1142 {
1143         struct Nearest2dPrecalc data;
1144         dist_squared_to_projected_aabb_precalc(
1145                 &data, lpmat, true, win_half, ray_min_dist,
1146                 mval, ray_origin_local, ray_direction_local);
1147
1148         bool dummy[3] = {true, true, true};
1149         return dist_squared_to_projected_aabb(&data, bbmin, bbmax, dummy);
1150 }
1151
1152 /** \} */
1153
1154 /* -------------------------------------------------------------------- */
1155 /** Walk DFS
1156  * \{ */
1157
1158 typedef void (*Nearest2DGetEdgeVertsCallback)(const int index, const float *v_pair[2], void *data);
1159 typedef void (*Nearest2DCopyVertNoCallback)(const int index, float r_no[3], void *data);
1160
1161 typedef struct Nearest2dUserData {
1162         struct Nearest2dPrecalc data_precalc;
1163
1164         float dist_px_sq;
1165
1166         bool r_axis_closest[3];
1167
1168         float depth_range[2];
1169
1170         void *userdata;
1171         Nearest2DGetEdgeVertsCallback get_edge_verts;
1172         Nearest2DCopyVertNoCallback copy_vert_no;
1173
1174         int index;
1175         float co[3];
1176         float no[3];
1177 } Nearest2dUserData;
1178
1179
1180 static bool cb_walk_parent_snap_project(const BVHTreeAxisRange *bounds, void *user_data)
1181 {
1182         Nearest2dUserData *data = user_data;
1183         const float bbmin[3] = {bounds[0].min, bounds[1].min, bounds[2].min};
1184         const float bbmax[3] = {bounds[0].max, bounds[1].max, bounds[2].max};
1185         const float rdist = dist_squared_to_projected_aabb(
1186                 &data->data_precalc, bbmin, bbmax, data->r_axis_closest);
1187         return rdist < data->dist_px_sq;
1188 }
1189
1190 static bool cb_walk_leaf_snap_vert(const BVHTreeAxisRange *bounds, int index, void *userdata)
1191 {
1192         struct Nearest2dUserData *data = userdata;
1193         struct Nearest2dPrecalc *neasrest_precalc = &data->data_precalc;
1194         const float co[3] = {
1195                 (bounds[0].min + bounds[0].max) / 2,
1196                 (bounds[1].min + bounds[1].max) / 2,
1197                 (bounds[2].min + bounds[2].max) / 2,
1198         };
1199
1200         if (test_projected_vert_dist(
1201                 data->depth_range,
1202                 neasrest_precalc->mval, co,
1203                 neasrest_precalc->pmat,
1204                 neasrest_precalc->win_half,
1205                 neasrest_precalc->is_persp,
1206                 &data->dist_px_sq,
1207                 data->co))
1208         {
1209                 data->copy_vert_no(index, data->no, data->userdata);
1210                 data->index = index;
1211         }
1212         return true;
1213 }
1214
1215 static bool cb_walk_leaf_snap_edge(const BVHTreeAxisRange *UNUSED(bounds), int index, void *userdata)
1216 {
1217         struct Nearest2dUserData *data = userdata;
1218         struct Nearest2dPrecalc *neasrest_precalc = &data->data_precalc;
1219
1220         const float *v_pair[2];
1221         data->get_edge_verts(index, v_pair, data->userdata);
1222
1223         if (test_projected_edge_dist(
1224                 data->depth_range,
1225                 neasrest_precalc->mval,
1226                 neasrest_precalc->pmat,
1227                 neasrest_precalc->win_half,
1228                 neasrest_precalc->is_persp,
1229                 neasrest_precalc->ray_origin_local,
1230                 neasrest_precalc->ray_direction_local,
1231                 v_pair[0], v_pair[1],
1232                 &data->dist_px_sq,
1233                 data->co))
1234         {
1235                 sub_v3_v3v3(data->no, v_pair[0], v_pair[1]);
1236                 data->index = index;
1237         }
1238         return true;
1239 }
1240
1241 static bool cb_nearest_walk_order(const BVHTreeAxisRange *UNUSED(bounds), char axis, void *userdata)
1242 {
1243         const bool *r_axis_closest = ((struct Nearest2dUserData *)userdata)->r_axis_closest;
1244         return r_axis_closest[axis];
1245 }
1246
1247 /** \} */
1248
1249 /* -------------------------------------------------------------------- */
1250 /** \name Internal Object Snapping API
1251  * \{ */
1252
1253 static bool snapArmature(
1254         SnapData *snapdata,
1255         Object *ob, bArmature *arm, float obmat[4][4],
1256         /* read/write args */
1257         float *ray_depth, float *dist_px,
1258         /* return args */
1259         float r_loc[3], float *UNUSED(r_no))
1260 {
1261         bool retval = false;
1262
1263         float ray_start_local[3], ray_normal_local[3]; /* Used only in the snap to edges */
1264         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1265                 float imat[4][4];
1266                 invert_m4_m4(imat, obmat);
1267
1268                 copy_v3_v3(ray_start_local, snapdata->ray_origin);
1269                 copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1270                 mul_m4_v3(imat, ray_start_local);
1271                 mul_mat3_m4_v3(imat, ray_normal_local);
1272         }
1273         else if (snapdata->snap_to != SCE_SNAP_MODE_VERTEX) { /* Currently only edge and vert */
1274                 return retval;
1275         }
1276
1277         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1278         float lpmat[4][4], dist_px_sq;
1279         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1280         dist_px_sq = SQUARE(*dist_px);
1281
1282         if (arm->edbo) {
1283                 for (EditBone *eBone = arm->edbo->first; eBone; eBone = eBone->next) {
1284                         if (eBone->layer & arm->layer) {
1285                                 /* skip hidden or moving (selected) bones */
1286                                 if ((eBone->flag & (BONE_HIDDEN_A | BONE_ROOTSEL | BONE_TIPSEL)) == 0) {
1287                                         switch (snapdata->snap_to) {
1288                                                 case SCE_SNAP_MODE_VERTEX:
1289                                                         retval |= test_projected_vert_dist(
1290                                                                 snapdata->depth_range, snapdata->mval, eBone->head,
1291                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1292                                                                 r_loc);
1293                                                         retval |= test_projected_vert_dist(
1294                                                                 snapdata->depth_range, snapdata->mval, eBone->tail,
1295                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1296                                                                 r_loc);
1297                                                         break;
1298                                                 case SCE_SNAP_MODE_EDGE:
1299                                                         retval |= test_projected_edge_dist(
1300                                                                 snapdata->depth_range, snapdata->mval, lpmat,
1301                                                                 snapdata->win_half, is_persp, ray_start_local, ray_normal_local,
1302                                                                 eBone->head, eBone->tail,
1303                                                                 &dist_px_sq, r_loc);
1304                                                         break;
1305                                         }
1306                                 }
1307                         }
1308                 }
1309         }
1310         else if (ob->pose && ob->pose->chanbase.first) {
1311                 for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1312                         Bone *bone = pchan->bone;
1313                         /* skip hidden bones */
1314                         if (bone && !(bone->flag & (BONE_HIDDEN_P | BONE_HIDDEN_PG))) {
1315                                 const float *head_vec = pchan->pose_head;
1316                                 const float *tail_vec = pchan->pose_tail;
1317
1318                                 switch (snapdata->snap_to) {
1319                                         case SCE_SNAP_MODE_VERTEX:
1320                                                 retval |= test_projected_vert_dist(
1321                                                         snapdata->depth_range, snapdata->mval, head_vec,
1322                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1323                                                         r_loc);
1324                                                 retval |= test_projected_vert_dist(
1325                                                         snapdata->depth_range, snapdata->mval, tail_vec,
1326                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1327                                                         r_loc);
1328                                                 break;
1329                                         case SCE_SNAP_MODE_EDGE:
1330                                                 retval |= test_projected_edge_dist(
1331                                                         snapdata->depth_range, snapdata->mval, lpmat,
1332                                                         snapdata->win_half, is_persp, ray_start_local, ray_normal_local,
1333                                                         head_vec, tail_vec,
1334                                                         &dist_px_sq, r_loc);
1335                                                 break;
1336                                 }
1337                         }
1338                 }
1339         }
1340         if (retval) {
1341                 *dist_px = sqrtf(dist_px_sq);
1342                 mul_m4_v3(obmat, r_loc);
1343                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1344                 return true;
1345         }
1346         return false;
1347 }
1348
1349 static bool snapCurve(
1350         SnapData *snapdata,
1351         Object *ob, Curve *cu, float obmat[4][4],
1352         /* read/write args */
1353         float *ray_depth, float *dist_px,
1354         /* return args */
1355         float r_loc[3], float *UNUSED(r_no))
1356 {
1357         bool retval = false;
1358
1359         /* only vertex snapping mode (eg control points and handles) supported for now) */
1360         if (snapdata->snap_to != SCE_SNAP_MODE_VERTEX) {
1361                 return retval;
1362         }
1363
1364         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1365         float lpmat[4][4], dist_px_sq;
1366         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1367         dist_px_sq = SQUARE(*dist_px);
1368
1369         for (Nurb *nu = (ob->mode == OB_MODE_EDIT ? cu->editnurb->nurbs.first : cu->nurb.first); nu; nu = nu->next) {
1370                 for (int u = 0; u < nu->pntsu; u++) {
1371                         switch (snapdata->snap_to) {
1372                                 case SCE_SNAP_MODE_VERTEX:
1373                                 {
1374                                         if (ob->mode == OB_MODE_EDIT) {
1375                                                 if (nu->bezt) {
1376                                                         /* don't snap to selected (moving) or hidden */
1377                                                         if (nu->bezt[u].f2 & SELECT || nu->bezt[u].hide != 0) {
1378                                                                 break;
1379                                                         }
1380                                                         retval |= test_projected_vert_dist(
1381                                                                 snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[1],
1382                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1383                                                                 r_loc);
1384                                                         /* don't snap if handle is selected (moving), or if it is aligning to a moving handle */
1385                                                         if (!(nu->bezt[u].f1 & SELECT) &&
1386                                                             !(nu->bezt[u].h1 & HD_ALIGN && nu->bezt[u].f3 & SELECT))
1387                                                         {
1388                                                                 retval |= test_projected_vert_dist(
1389                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[0],
1390                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1391                                                                         r_loc);
1392                                                         }
1393                                                         if (!(nu->bezt[u].f3 & SELECT) &&
1394                                                             !(nu->bezt[u].h2 & HD_ALIGN && nu->bezt[u].f1 & SELECT))
1395                                                         {
1396                                                                 retval |= test_projected_vert_dist(
1397                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[2],
1398                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1399                                                                         r_loc);
1400                                                         }
1401                                                 }
1402                                                 else {
1403                                                         /* don't snap to selected (moving) or hidden */
1404                                                         if (nu->bp[u].f1 & SELECT || nu->bp[u].hide != 0) {
1405                                                                 break;
1406                                                         }
1407                                                         retval |= test_projected_vert_dist(
1408                                                                 snapdata->depth_range, snapdata->mval, nu->bp[u].vec,
1409                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1410                                                                 r_loc);
1411                                                 }
1412                                         }
1413                                         else {
1414                                                 /* curve is not visible outside editmode if nurb length less than two */
1415                                                 if (nu->pntsu > 1) {
1416                                                         if (nu->bezt) {
1417                                                                 retval |= test_projected_vert_dist(
1418                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[1],
1419                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1420                                                                         r_loc);
1421                                                         }
1422                                                         else {
1423                                                                 retval |= test_projected_vert_dist(
1424                                                                         snapdata->depth_range, snapdata->mval, nu->bp[u].vec,
1425                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1426                                                                         r_loc);
1427                                                         }
1428                                                 }
1429                                         }
1430                                         break;
1431                                 }
1432                                 default:
1433                                         break;
1434                         }
1435                 }
1436         }
1437         if (retval) {
1438                 *dist_px = sqrtf(dist_px_sq);
1439                 mul_m4_v3(obmat, r_loc);
1440                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1441                 return true;
1442         }
1443         return false;
1444 }
1445
1446 /* may extend later (for now just snaps to empty center) */
1447 static bool snapEmpty(
1448         SnapData *snapdata,
1449         Object *ob, float obmat[4][4],
1450         /* read/write args */
1451         float *ray_depth, float *dist_px,
1452         /* return args */
1453         float r_loc[3], float *UNUSED(r_no))
1454 {
1455         bool retval = false;
1456
1457         if (ob->transflag & OB_DUPLI) {
1458                 return retval;
1459         }
1460
1461         /* for now only vertex supported */
1462         switch (snapdata->snap_to) {
1463                 case SCE_SNAP_MODE_VERTEX:
1464                 {
1465                         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1466                         float dist_px_sq = SQUARE(*dist_px);
1467                         float tmp_co[3];
1468                         copy_v3_v3(tmp_co, obmat[3]);
1469                         if (test_projected_vert_dist(
1470                                 snapdata->depth_range, snapdata->mval, tmp_co,
1471                                 snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
1472                                 r_loc))
1473                         {
1474                                 *dist_px = sqrtf(dist_px_sq);
1475                                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1476                                 retval = true;
1477                         }
1478                         break;
1479                 }
1480                 default:
1481                         break;
1482         }
1483
1484         return retval;
1485 }
1486
1487 static bool snapCamera(
1488         const SnapObjectContext *sctx, SnapData *snapdata,
1489         Object *object, float obmat[4][4],
1490         /* read/write args */
1491         float *ray_depth, float *dist_px,
1492         /* return args */
1493         float r_loc[3], float *UNUSED(r_no))
1494 {
1495         Scene *scene = sctx->scene;
1496
1497         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1498         float dist_px_sq = SQUARE(*dist_px);
1499
1500         float orig_camera_mat[4][4], orig_camera_imat[4][4], imat[4][4];
1501         bool retval = false;
1502         MovieClip *clip = BKE_object_movieclip_get(scene, object, false);
1503         MovieTracking *tracking;
1504
1505         if (clip == NULL) {
1506                 return retval;
1507         }
1508         if (object->transflag & OB_DUPLI) {
1509                 return retval;
1510         }
1511
1512         tracking = &clip->tracking;
1513
1514         BKE_tracking_get_camera_object_matrix(scene, object, orig_camera_mat);
1515
1516         invert_m4_m4(orig_camera_imat, orig_camera_mat);
1517         invert_m4_m4(imat, obmat);
1518
1519         switch (snapdata->snap_to) {
1520                 case SCE_SNAP_MODE_VERTEX:
1521                 {
1522                         MovieTrackingObject *tracking_object;
1523
1524                         for (tracking_object = tracking->objects.first;
1525                              tracking_object;
1526                              tracking_object = tracking_object->next)
1527                         {
1528                                 ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
1529                                 MovieTrackingTrack *track;
1530                                 float reconstructed_camera_mat[4][4],
1531                                       reconstructed_camera_imat[4][4];
1532                                 float (*vertex_obmat)[4];
1533
1534                                 if ((tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0) {
1535                                         BKE_tracking_camera_get_reconstructed_interpolate(tracking, tracking_object,
1536                                                                                           CFRA, reconstructed_camera_mat);
1537
1538                                         invert_m4_m4(reconstructed_camera_imat, reconstructed_camera_mat);
1539                                 }
1540
1541                                 for (track = tracksbase->first; track; track = track->next) {
1542                                         float bundle_pos[3];
1543
1544                                         if ((track->flag & TRACK_HAS_BUNDLE) == 0) {
1545                                                 continue;
1546                                         }
1547
1548                                         copy_v3_v3(bundle_pos, track->bundle_pos);
1549                                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1550                                                 vertex_obmat = orig_camera_mat;
1551                                         }
1552                                         else {
1553                                                 mul_m4_v3(reconstructed_camera_imat, bundle_pos);
1554                                                 vertex_obmat = obmat;
1555                                         }
1556
1557                                         mul_m4_v3(vertex_obmat, bundle_pos);
1558                                         retval |= test_projected_vert_dist(
1559                                                 snapdata->depth_range, snapdata->mval, bundle_pos,
1560                                                 snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
1561                                                 r_loc);
1562                                 }
1563                         }
1564
1565                         break;
1566                 }
1567                 default:
1568                         break;
1569         }
1570
1571         if (retval) {
1572                 *dist_px = sqrtf(dist_px_sq);
1573                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1574                 return true;
1575         }
1576         return false;
1577 }
1578
1579 static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt)
1580 {
1581         const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1582         return index_mp_to_orig ? index_mp_to_orig[lt->poly] : lt->poly;
1583 }
1584
1585 static bool snapDerivedMesh(
1586         SnapObjectContext *sctx, SnapData *snapdata,
1587         Object *ob, DerivedMesh *dm, float obmat[4][4],
1588         /* read/write args */
1589         float *ray_depth, float *dist_px,
1590         /* return args */
1591         float r_loc[3], float r_no[3])
1592 {
1593         bool retval = false;
1594
1595         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1596                 if (dm->getNumEdges(dm) == 0) {
1597                         return retval;
1598                 }
1599         }
1600         else {
1601                 if (dm->getNumVerts(dm) == 0) {
1602                         return retval;
1603                 }
1604         }
1605
1606         float imat[4][4];
1607         float timat[3][3]; /* transpose inverse matrix for normals */
1608         float ray_normal_local[3];
1609         float local_scale;
1610
1611         invert_m4_m4(imat, obmat);
1612         transpose_m3_m4(timat, imat);
1613
1614         copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1615
1616         mul_mat3_m4_v3(imat, ray_normal_local);
1617
1618         /* local scale in normal direction */
1619         local_scale = normalize_v3(ray_normal_local);
1620
1621         float lpmat[4][4];
1622         float ray_org_local[3];
1623         float ray_min_dist;
1624
1625         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1626         ray_min_dist = snapdata->depth_range[0] * local_scale;
1627
1628         copy_v3_v3(ray_org_local, snapdata->ray_origin);
1629         mul_m4_v3(imat, ray_org_local);
1630
1631         /* Test BoundBox */
1632         BoundBox *bb = BKE_object_boundbox_get(ob);
1633         if (bb) {
1634                 /* In vertex and edges you need to get the pixel distance from ray to BoundBox, see: T46099, T46816 */
1635                 float dist_px_sq = dist_squared_to_projected_aabb_simple(
1636                             lpmat, snapdata->win_half, ray_min_dist, snapdata->mval,
1637                             ray_org_local, ray_normal_local, bb->vec[0], bb->vec[6]);
1638                 if (dist_px_sq > SQUARE(*dist_px)) {
1639                         return retval;
1640                 }
1641         }
1642
1643         SnapObjectData_Mesh *sod = NULL;
1644         BVHTreeFromMesh *treedata = NULL;
1645
1646         void **sod_p;
1647         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
1648                 sod = *sod_p;
1649         }
1650         else {
1651                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
1652                 sod->sd.type = SNAP_MESH;
1653         }
1654
1655         int tree_index = -1;
1656         switch (snapdata->snap_to) {
1657                 case SCE_SNAP_MODE_EDGE:
1658                         tree_index = 1;
1659                         break;
1660                 case SCE_SNAP_MODE_VERTEX:
1661                         tree_index = 0;
1662                         break;
1663         }
1664         if (tree_index != -1) {
1665                 if (sod->bvh_trees[tree_index] == NULL) {
1666                         sod->bvh_trees[tree_index] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
1667                 }
1668                 treedata = sod->bvh_trees[tree_index];
1669
1670                 /* the tree is owned by the DM and may have been freed since we last used! */
1671                 if (treedata && treedata->tree) {
1672                         if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
1673                                 free_bvhtree_from_mesh(treedata);
1674                         }
1675                         else {
1676                                 if (treedata->vert == NULL) {
1677                                         treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
1678                                 }
1679                                 if ((tree_index == 1) && (treedata->edge == NULL)) {
1680                                         treedata->edge = DM_get_edge_array(dm, &treedata->edge_allocated);
1681                                 }
1682                         }
1683                 }
1684         }
1685
1686         if (treedata) {
1687                 if (treedata->tree == NULL) {
1688                         switch (snapdata->snap_to) {
1689                                 case SCE_SNAP_MODE_EDGE:
1690                                         bvhtree_from_mesh_edges(treedata, dm, 0.0f, 2, 6);
1691                                         break;
1692                                 case SCE_SNAP_MODE_VERTEX:
1693                                         bvhtree_from_mesh_verts(treedata, dm, 0.0f, 2, 6);
1694                                         break;
1695                         }
1696                 }
1697                 if (treedata->tree == NULL) {
1698                         return retval;
1699                 }
1700         }
1701         else {
1702                 return retval;
1703         }
1704
1705         /* Warning: the depth_max is currently being used only in perspective view.
1706          * It is not correct to limit the maximum depth for elements obtained with nearest
1707          * since this limitation depends on the normal and the size of the occlusion face.
1708          * And more... ray_depth is being confused with Z-depth here... (varies only the precision) */
1709         const float ray_depth_max_global = *ray_depth + snapdata->depth_range[0];
1710
1711         Nearest2dUserData neasrest2d = {
1712                 .dist_px_sq = SQUARE(*dist_px),
1713                 .r_axis_closest = {1.0f, 1.0f, 1.0f},
1714                 .depth_range = {snapdata->depth_range[0], ray_depth_max_global},
1715                 .userdata = treedata,
1716                 .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_dm_edge_verts,
1717                 .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_dm_vert_no,
1718                 .index = -1};
1719
1720         dist_squared_to_projected_aabb_precalc(
1721                 &neasrest2d.data_precalc, lpmat,
1722                 snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
1723                 ray_min_dist, snapdata->mval, ray_org_local, ray_normal_local);
1724
1725         BVHTree_WalkLeafCallback cb_walk_leaf =
1726                 (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
1727                 cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
1728
1729         BLI_bvhtree_walk_dfs(
1730                 treedata->tree,
1731                 cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
1732
1733         if (neasrest2d.index != -1) {
1734                 copy_v3_v3(r_loc, neasrest2d.co);
1735                 mul_m4_v3(obmat, r_loc);
1736                 if (r_no) {
1737                         copy_v3_v3(r_no, neasrest2d.no);
1738                         mul_m3_v3(timat, r_no);
1739                         normalize_v3(r_no);
1740                 }
1741                 *dist_px = sqrtf(neasrest2d.dist_px_sq);
1742                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1743
1744                 retval = true;
1745         }
1746
1747         return retval;
1748 }
1749
1750 static bool snapEditMesh(
1751         SnapObjectContext *sctx, SnapData *snapdata,
1752         Object *ob, BMEditMesh *em, float obmat[4][4],
1753         /* read/write args */
1754         float *ray_depth, float *dist_px,
1755         /* return args */
1756         float r_loc[3], float r_no[3])
1757 {
1758         bool retval = false;
1759
1760         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1761                 if (em->bm->totedge == 0) {
1762                         return retval;
1763                 }
1764         }
1765         else {
1766                 if (em->bm->totvert == 0) {
1767                         return retval;
1768                 }
1769         }
1770
1771         float imat[4][4];
1772         float timat[3][3]; /* transpose inverse matrix for normals */
1773         float ray_normal_local[3];
1774
1775         invert_m4_m4(imat, obmat);
1776         transpose_m3_m4(timat, imat);
1777
1778         copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1779
1780         mul_mat3_m4_v3(imat, ray_normal_local);
1781
1782         /* local scale in normal direction */
1783         float local_scale = normalize_v3(ray_normal_local);
1784
1785         SnapObjectData_EditMesh *sod = NULL;
1786         BVHTreeFromEditMesh *treedata = NULL;
1787
1788         void **sod_p;
1789         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
1790                 sod = *sod_p;
1791         }
1792         else {
1793                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
1794                 sod->sd.type = SNAP_EDIT_MESH;
1795         }
1796
1797         int tree_index = -1;
1798         switch (snapdata->snap_to) {
1799                 case SCE_SNAP_MODE_EDGE:
1800                         tree_index = 1;
1801                         break;
1802                 case SCE_SNAP_MODE_VERTEX:
1803                         tree_index = 0;
1804                         break;
1805         }
1806         if (tree_index != -1) {
1807                 if (sod->bvh_trees[tree_index] == NULL) {
1808                         sod->bvh_trees[tree_index] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
1809                 }
1810                 treedata = sod->bvh_trees[tree_index];
1811         }
1812
1813         if (treedata) {
1814                 if (treedata->tree == NULL) {
1815                         BLI_bitmap *elem_mask = NULL;
1816                         switch (snapdata->snap_to) {
1817                                 case SCE_SNAP_MODE_EDGE:
1818                                 {
1819                                         int edges_num_active = -1;
1820                                         if (sctx->callbacks.edit_mesh.test_edge_fn) {
1821                                                 elem_mask = BLI_BITMAP_NEW(em->bm->totedge, __func__);
1822                                                 edges_num_active = BM_iter_mesh_bitmap_from_filter(
1823                                                         BM_EDGES_OF_MESH, em->bm, elem_mask,
1824                                                         (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_edge_fn,
1825                                                         sctx->callbacks.edit_mesh.user_data);
1826                                         }
1827                                         bvhtree_from_editmesh_edges_ex(treedata, em, elem_mask, edges_num_active, 0.0f, 2, 6);
1828                                         break;
1829                                 }
1830                                 case SCE_SNAP_MODE_VERTEX:
1831                                 {
1832                                         int verts_num_active = -1;
1833                                         if (sctx->callbacks.edit_mesh.test_vert_fn) {
1834                                                 elem_mask = BLI_BITMAP_NEW(em->bm->totvert, __func__);
1835                                                 verts_num_active = BM_iter_mesh_bitmap_from_filter(
1836                                                         BM_VERTS_OF_MESH, em->bm, elem_mask,
1837                                                         (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_vert_fn,
1838                                                         sctx->callbacks.edit_mesh.user_data);
1839                                         }
1840                                         bvhtree_from_editmesh_verts_ex(treedata, em, elem_mask, verts_num_active, 0.0f, 2, 6);
1841                                         break;
1842                                 }
1843                         }
1844                         if (elem_mask) {
1845                                 MEM_freeN(elem_mask);
1846                         }
1847                 }
1848                 if (treedata->tree == NULL) {
1849                         return retval;
1850                 }
1851         }
1852         else {
1853                 return retval;
1854         }
1855
1856         float ray_org_local[3];
1857         copy_v3_v3(ray_org_local, snapdata->ray_origin);
1858         mul_m4_v3(imat, ray_org_local);
1859
1860         Nearest2dUserData neasrest2d = {
1861                 .dist_px_sq = SQUARE(*dist_px),
1862                 .r_axis_closest = {1.0f, 1.0f, 1.0f},
1863                 .depth_range = {snapdata->depth_range[0], *ray_depth + snapdata->depth_range[0]},
1864                 .userdata = treedata,
1865                 .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_bedge_verts,
1866                 .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_bvert_no,
1867                 .index = -1};
1868
1869         float lpmat[4][4];
1870         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1871         dist_squared_to_projected_aabb_precalc(
1872                 &neasrest2d.data_precalc, lpmat,
1873                 snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
1874                 (snapdata->depth_range[0] * local_scale), snapdata->mval,
1875                 ray_org_local, ray_normal_local);
1876
1877         BVHTree_WalkLeafCallback cb_walk_leaf =
1878                 (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
1879                 cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
1880
1881         BLI_bvhtree_walk_dfs(
1882                 treedata->tree,
1883                 cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
1884
1885         if (neasrest2d.index != -1) {
1886                 copy_v3_v3(r_loc, neasrest2d.co);
1887                 mul_m4_v3(obmat, r_loc);
1888                 if (r_no) {
1889                         copy_v3_v3(r_no, neasrest2d.no);
1890                         mul_m3_v3(timat, r_no);
1891                         normalize_v3(r_no);
1892                 }
1893                 *dist_px = sqrtf(neasrest2d.dist_px_sq);
1894                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1895
1896                 retval = true;
1897         }
1898
1899         return retval;
1900 }
1901
1902 /**
1903  * \param use_obedit: Uses the coordinates of BMesh (if any) to do the snapping;
1904  *
1905  * \note Duplicate args here are documented at #snapObjectsRay
1906  */
1907 static bool snapObject(
1908         SnapObjectContext *sctx, SnapData *snapdata,
1909         Object *ob, float obmat[4][4],
1910         bool use_obedit,
1911         /* read/write args */
1912         float *ray_depth, float *dist_px,
1913         /* return args */
1914         float r_loc[3], float r_no[3],
1915         Object **r_ob, float r_obmat[4][4])
1916 {
1917         bool retval = false;
1918
1919         if (ob->type == OB_MESH) {
1920                 BMEditMesh *em;
1921
1922                 if (use_obedit) {
1923                         em = BKE_editmesh_from_object(ob);
1924                         retval = snapEditMesh(
1925                                 sctx, snapdata, ob, em, obmat,
1926                                 ray_depth, dist_px,
1927                                 r_loc, r_no);
1928                 }
1929                 else {
1930                         /* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
1931                          * still set the 'em' to NULL, since we only want the 'dm'. */
1932                         DerivedMesh *dm;
1933                         em = BKE_editmesh_from_object(ob);
1934                         if (em) {
1935                                 editbmesh_get_derived_cage_and_final(sctx->scene, ob, em, CD_MASK_BAREMESH, &dm);
1936                         }
1937                         else {
1938                                 dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
1939                         }
1940                         retval = snapDerivedMesh(
1941                                 sctx, snapdata, ob, dm, obmat,
1942                                 ray_depth, dist_px,
1943                                 r_loc, r_no);
1944
1945                         dm->release(dm);
1946                 }
1947         }
1948         else if (snapdata->snap_to != SCE_SNAP_MODE_FACE) {
1949                 if (ob->type == OB_ARMATURE) {
1950                         retval = snapArmature(
1951                                 snapdata,
1952                                 ob, ob->data, obmat,
1953                                 ray_depth, dist_px,
1954                                 r_loc, r_no);
1955                 }
1956                 else if (ob->type == OB_CURVE) {
1957                         retval = snapCurve(
1958                                 snapdata,
1959                                 ob, ob->data, obmat,
1960                                 ray_depth, dist_px,
1961                                 r_loc, r_no);
1962                 }
1963                 else if (ob->type == OB_EMPTY) {
1964                         retval = snapEmpty(
1965                                 snapdata,
1966                                 ob, obmat,
1967                                 ray_depth, dist_px,
1968                                 r_loc, r_no);
1969                 }
1970                 else if (ob->type == OB_CAMERA) {
1971                         retval = snapCamera(
1972                                 sctx, snapdata, ob, obmat,
1973                                 ray_depth, dist_px,
1974                                 r_loc, r_no);
1975                 }
1976         }
1977
1978         if (retval) {
1979                 if (r_ob) {
1980                         *r_ob = ob;
1981                         copy_m4_m4(r_obmat, obmat);
1982                 }
1983         }
1984
1985         return retval;
1986 }
1987
1988
1989 struct SnapObjUserData {
1990         SnapData *snapdata;
1991         /* read/write args */
1992         float *ray_depth;
1993         float *dist_px;
1994         /* return args */
1995         float *r_loc;
1996         float *r_no;
1997         Object **r_ob;
1998         float (*r_obmat)[4];
1999         bool ret;
2000 };
2001
2002 static void sanp_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
2003 {
2004         struct SnapObjUserData *dt = data;
2005         dt->ret |= snapObject(
2006                 sctx, dt->snapdata,
2007                 ob, obmat, is_obedit,
2008                 /* read/write args */
2009                 dt->ray_depth, dt->dist_px,
2010                 /* return args */
2011                 dt->r_loc, dt->r_no,
2012                 dt->r_ob, dt->r_obmat);
2013 }
2014
2015
2016 /**
2017  * Main Snapping Function
2018  * ======================
2019  *
2020  * Walks through all objects in the scene to find the closest snap element ray.
2021  *
2022  * \param sctx: Snap context to store data.
2023  * \param snapdata: struct generated in `get_snapdata`.
2024  * \param snap_select : from enum eSnapSelect.
2025  * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
2026  *
2027  * Read/Write Args
2028  * ---------------
2029  *
2030  * \param ray_depth: maximum depth allowed for r_co, elements deeper than this value will be ignored.
2031  * \param dist_px: Maximum threshold distance (in pixels).
2032  *
2033  * Output Args
2034  * -----------
2035  *
2036  * \param r_loc: Hit location.
2037  * \param r_no: Hit normal (optional).
2038  * \param r_index: Hit index or -1 when no valid index is found.
2039  * (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
2040  * \param r_ob: Hit object.
2041  * \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
2042  *
2043  */
2044 static bool snapObjectsRay(
2045         SnapObjectContext *sctx, SnapData *snapdata,
2046         const eSnapSelect snap_select, const bool use_object_edit_cage,
2047         /* read/write args */
2048         float *ray_depth, float *dist_px,
2049         /* return args */
2050         float r_loc[3], float r_no[3],
2051         Object **r_ob, float r_obmat[4][4])
2052 {
2053         Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
2054
2055         struct SnapObjUserData data = {
2056                 .snapdata = snapdata,
2057                 .ray_depth = ray_depth,
2058                 .dist_px = dist_px,
2059                 .r_loc = r_loc,
2060                 .r_no = r_no,
2061                 .r_ob = r_ob,
2062                 .r_obmat = r_obmat,
2063                 .ret = false,
2064         };
2065
2066         iter_snap_objects(sctx, snap_select, obedit, sanp_obj_cb, &data);
2067
2068         return data.ret;
2069 }
2070
2071 /** \} */
2072
2073 /* -------------------------------------------------------------------- */
2074 /** \name Public Object Snapping API
2075  * \{ */
2076
2077 SnapObjectContext *ED_transform_snap_object_context_create(
2078         Main *bmain, Scene *scene, int flag)
2079 {
2080         SnapObjectContext *sctx = MEM_callocN(sizeof(*sctx), __func__);
2081
2082         sctx->flag = flag;
2083
2084         sctx->bmain = bmain;
2085         sctx->scene = scene;
2086
2087         sctx->cache.object_map = BLI_ghash_ptr_new(__func__);
2088         sctx->cache.mem_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
2089
2090         return sctx;
2091 }
2092
2093 SnapObjectContext *ED_transform_snap_object_context_create_view3d(
2094         Main *bmain, Scene *scene, int flag,
2095         /* extra args for view3d */
2096         const ARegion *ar, const View3D *v3d)
2097 {
2098         SnapObjectContext *sctx = ED_transform_snap_object_context_create(bmain, scene, flag);
2099
2100         sctx->use_v3d = true;
2101         sctx->v3d_data.ar = ar;
2102         sctx->v3d_data.v3d = v3d;
2103
2104         return sctx;
2105 }
2106
2107 static void snap_object_data_free(void *sod_v)
2108 {
2109         switch (((SnapObjectData *)sod_v)->type) {
2110                 case SNAP_MESH:
2111                 {
2112                         SnapObjectData_Mesh *sod = sod_v;
2113                         for (int i = 0; i < ARRAY_SIZE(sod->bvh_trees); i++) {
2114                                 if (sod->bvh_trees[i]) {
2115                                         free_bvhtree_from_mesh(sod->bvh_trees[i]);
2116                                 }
2117                         }
2118                         if (sod->poly_allocated) {
2119                                 MEM_freeN(sod->mpoly);
2120                         }
2121                         break;
2122                 }
2123                 case SNAP_EDIT_MESH:
2124                 {
2125                         SnapObjectData_EditMesh *sod = sod_v;
2126                         for (int i = 0; i < ARRAY_SIZE(sod->bvh_trees); i++) {
2127                                 if (sod->bvh_trees[i]) {
2128                                         free_bvhtree_from_editmesh(sod->bvh_trees[i]);
2129                                 }
2130                         }
2131                         break;
2132                 }
2133         }
2134 }
2135
2136 void ED_transform_snap_object_context_destroy(SnapObjectContext *sctx)
2137 {
2138         BLI_ghash_free(sctx->cache.object_map, NULL, snap_object_data_free);
2139         BLI_memarena_free(sctx->cache.mem_arena);
2140
2141         MEM_freeN(sctx);
2142 }
2143
2144 void ED_transform_snap_object_context_set_editmesh_callbacks(
2145         SnapObjectContext *sctx,
2146         bool (*test_vert_fn)(BMVert *, void *user_data),
2147         bool (*test_edge_fn)(BMEdge *, void *user_data),
2148         bool (*test_face_fn)(BMFace *, void *user_data),
2149         void *user_data)
2150 {
2151         sctx->callbacks.edit_mesh.test_vert_fn = test_vert_fn;
2152         sctx->callbacks.edit_mesh.test_edge_fn = test_edge_fn;
2153         sctx->callbacks.edit_mesh.test_face_fn = test_face_fn;
2154
2155         sctx->callbacks.edit_mesh.user_data = user_data;
2156 }
2157
2158 bool ED_transform_snap_object_project_ray_ex(
2159         SnapObjectContext *sctx,
2160         const struct SnapObjectParams *params,
2161         const float ray_start[3], const float ray_normal[3],
2162         float *ray_depth,
2163         float r_loc[3], float r_no[3], int *r_index,
2164         Object **r_ob, float r_obmat[4][4])
2165 {
2166         return raycastObjects(
2167                 sctx,
2168                 ray_start, ray_normal,
2169                 params->snap_select, params->use_object_edit_cage,
2170                 ray_depth, r_loc, r_no, r_index, r_ob, r_obmat, NULL);
2171 }
2172
2173 /**
2174  * Fill in a list of all hits.
2175  *
2176  * \param ray_depth: Only depths in this range are considered, -1.0 for maximum.
2177  * \param sort: Optionally sort the hits by depth.
2178  * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
2179  */
2180 bool ED_transform_snap_object_project_ray_all(
2181         SnapObjectContext *sctx,
2182         const struct SnapObjectParams *params,
2183         const float ray_start[3], const float ray_normal[3],
2184         float ray_depth, bool sort,
2185         ListBase *r_hit_list)
2186 {
2187         if (ray_depth == -1.0f) {
2188                 ray_depth = BVH_RAYCAST_DIST_MAX;
2189         }
2190
2191 #ifdef DEBUG
2192         float ray_depth_prev = ray_depth;
2193 #endif
2194
2195         bool retval = raycastObjects(
2196                 sctx,
2197                 ray_start, ray_normal,
2198                 params->snap_select, params->use_object_edit_cage,
2199                 &ray_depth, NULL, NULL, NULL, NULL, NULL,
2200                 r_hit_list);
2201
2202         /* meant to be readonly for 'all' hits, ensure it is */
2203 #ifdef DEBUG
2204         BLI_assert(ray_depth_prev == ray_depth);
2205 #endif
2206
2207         if (sort) {
2208                 BLI_listbase_sort(r_hit_list, hit_depth_cmp);
2209         }
2210
2211         return retval;
2212 }
2213
2214 /**
2215  * Convenience function for snap ray-casting.
2216  *
2217  * Given a ray, cast it into the scene (snapping to faces).
2218  *
2219  * \return Snap success
2220  */
2221 static bool transform_snap_context_project_ray_impl(
2222         SnapObjectContext *sctx,
2223         const struct SnapObjectParams *params,
2224         const float ray_start[3], const float ray_normal[3], float *ray_depth,
2225         float r_co[3], float r_no[3])
2226 {
2227         bool ret;
2228
2229         /* try snap edge, then face if it fails */
2230         ret = ED_transform_snap_object_project_ray_ex(
2231                 sctx,
2232                 params,
2233                 ray_start, ray_normal, ray_depth,
2234                 r_co, r_no, NULL,
2235                 NULL, NULL);
2236
2237         return ret;
2238 }
2239
2240 bool ED_transform_snap_object_project_ray(
2241         SnapObjectContext *sctx,
2242         const struct SnapObjectParams *params,
2243         const float ray_origin[3], const float ray_direction[3], float *ray_depth,
2244         float r_co[3], float r_no[3])
2245 {
2246         float ray_depth_fallback;
2247         if (ray_depth == NULL) {
2248                 ray_depth_fallback = BVH_RAYCAST_DIST_MAX;
2249                 ray_depth = &ray_depth_fallback;
2250         }
2251
2252         return transform_snap_context_project_ray_impl(
2253                 sctx,
2254                 params,
2255                 ray_origin, ray_direction, ray_depth,
2256                 r_co, r_no);
2257 }
2258
2259 static bool transform_snap_context_project_view3d_mixed_impl(
2260         SnapObjectContext *sctx,
2261         const unsigned short snap_to_flag,
2262         const struct SnapObjectParams *params,
2263         const float mval[2], float *dist_px,
2264         bool use_depth,
2265         float r_co[3], float r_no[3])
2266 {
2267         float ray_depth = BVH_RAYCAST_DIST_MAX;
2268         bool is_hit = false;
2269
2270         const int  elem_type[3] = {SCE_SNAP_MODE_VERTEX, SCE_SNAP_MODE_EDGE, SCE_SNAP_MODE_FACE};
2271
2272         BLI_assert(snap_to_flag != 0);
2273         BLI_assert((snap_to_flag & ~(1 | 2 | 4)) == 0);
2274
2275         if (use_depth) {
2276                 const float dist_px_orig = dist_px ? *dist_px : 0;
2277                 for (int i = 2; i >= 0; i--) {
2278                         if (snap_to_flag & (1 << i)) {
2279                                 if (i == 0) {
2280                                         BLI_assert(dist_px != NULL);
2281                                         *dist_px = dist_px_orig;
2282                                 }
2283                                 if (ED_transform_snap_object_project_view3d(
2284                                         sctx,
2285                                         elem_type[i], params,
2286                                         mval, dist_px, &ray_depth,
2287                                         r_co, r_no))
2288                                 {
2289                                         /* 0.01 is a random but small value to prioritizing
2290                                          * the first elements of the loop */
2291                                         ray_depth += 0.01f;
2292                                         is_hit = true;
2293                                 }
2294                         }
2295                 }
2296         }
2297         else {
2298                 for (int i = 0; i < 3; i++) {
2299                         if (snap_to_flag & (1 << i)) {
2300                                 if (ED_transform_snap_object_project_view3d(
2301                                         sctx,
2302                                         elem_type[i], params,
2303                                         mval, dist_px, &ray_depth,
2304                                         r_co, r_no))
2305                                 {
2306                                         is_hit = true;
2307                                         break;
2308                                 }
2309                         }
2310                 }
2311         }
2312
2313         return is_hit;
2314 }
2315
2316 /**
2317  * Convenience function for performing snapping.
2318  *
2319  * Given a 2D region value, snap to vert/edge/face.
2320  *
2321  * \param sctx: Snap context.
2322  * \param mval_fl: Screenspace coordinate.
2323  * \param dist_px: Maximum distance to snap (in pixels).
2324  * \param use_depth: Snap to the closest element, use when using more than one snap type.
2325  * \param r_co: hit location.
2326  * \param r_no: hit normal (optional).
2327  * \return Snap success
2328  */
2329 bool ED_transform_snap_object_project_view3d_mixed(
2330         SnapObjectContext *sctx,
2331         const unsigned short snap_to_flag,
2332         const struct SnapObjectParams *params,
2333         const float mval_fl[2], float *dist_px,
2334         bool use_depth,
2335         float r_co[3], float r_no[3])
2336 {
2337         return transform_snap_context_project_view3d_mixed_impl(
2338                 sctx,
2339                 snap_to_flag, params,
2340                 mval_fl, dist_px, use_depth,
2341                 r_co, r_no);
2342 }
2343
2344 bool ED_transform_snap_object_project_view3d_ex(
2345         SnapObjectContext *sctx,
2346         const unsigned short snap_to,
2347         const struct SnapObjectParams *params,
2348         const float mval[2], float *dist_px,
2349         float *ray_depth,
2350         float r_loc[3], float r_no[3], int *r_index)
2351 {
2352         float ray_origin[3], ray_start[3], ray_normal[3], depth_range[2], ray_end[3];
2353
2354         const ARegion *ar = sctx->v3d_data.ar;
2355         const RegionView3D *rv3d = ar->regiondata;
2356
2357         ED_view3d_win_to_origin(ar, mval, ray_origin);
2358         ED_view3d_win_to_vector(ar, mval, ray_normal);
2359
2360         ED_view3d_clip_range_get(
2361                 sctx->v3d_data.v3d, sctx->v3d_data.ar->regiondata,
2362                 &depth_range[0], &depth_range[1], false);
2363
2364         madd_v3_v3v3fl(ray_start, ray_origin, ray_normal, depth_range[0]);
2365         madd_v3_v3v3fl(ray_end, ray_origin, ray_normal, depth_range[1]);
2366
2367         if (!ED_view3d_clip_segment(rv3d, ray_start, ray_end)) {
2368                 return false;
2369         }
2370
2371         float ray_depth_fallback;
2372         if (ray_depth == NULL) {
2373                 ray_depth_fallback = BVH_RAYCAST_DIST_MAX;
2374                 ray_depth = &ray_depth_fallback;
2375         }
2376
2377         if (snap_to == SCE_SNAP_MODE_FACE) {
2378                 return raycastObjects(
2379                         sctx,
2380                         ray_start, ray_normal,
2381                         params->snap_select, params->use_object_edit_cage,
2382                         ray_depth, r_loc, r_no, r_index, NULL, NULL, NULL);
2383         }
2384         else {
2385                 SnapData snapdata;
2386                 const enum eViewProj view_proj = ((RegionView3D *)ar->regiondata)->is_persp ? VIEW_PROJ_PERSP : VIEW_PROJ_ORTHO;
2387                 snap_data_set(&snapdata, ar, snap_to, view_proj, mval,
2388                         ray_origin, ray_start, ray_normal, depth_range);
2389
2390                 return snapObjectsRay(
2391                         sctx, &snapdata,
2392                         params->snap_select, params->use_object_edit_cage,
2393                         ray_depth, dist_px, r_loc, r_no, NULL, NULL);
2394         }
2395 }
2396
2397 bool ED_transform_snap_object_project_view3d(
2398         SnapObjectContext *sctx,
2399         const unsigned short snap_to,
2400         const struct SnapObjectParams *params,
2401         const float mval[2], float *dist_px,
2402         float *ray_depth,
2403         float r_loc[3], float r_no[3])
2404 {
2405         return ED_transform_snap_object_project_view3d_ex(
2406                 sctx,
2407                 snap_to,
2408                 params,
2409                 mval, dist_px,
2410                 ray_depth,
2411                 r_loc, r_no, NULL);
2412 }
2413
2414 /**
2415  * see: #ED_transform_snap_object_project_ray_all
2416  */
2417 bool ED_transform_snap_object_project_all_view3d_ex(
2418         SnapObjectContext *sctx,
2419         const struct SnapObjectParams *params,
2420         const float mval[2],
2421         float ray_depth, bool sort,
2422         ListBase *r_hit_list)
2423 {
2424         float ray_start[3], ray_normal[3];
2425
2426         if (!ED_view3d_win_to_ray_ex(
2427                 sctx->v3d_data.ar, sctx->v3d_data.v3d,
2428                 mval, NULL, ray_normal, ray_start, true))
2429         {
2430                 return false;
2431         }
2432
2433         return ED_transform_snap_object_project_ray_all(
2434                 sctx,
2435                 params,
2436                 ray_start, ray_normal, ray_depth, sort,
2437                 r_hit_list);
2438 }
2439
2440 /** \} */