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