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