5ea826521ed809547550b925fdcf03b65b9bc061
[blender.git] / source / blender / editors / transform / transform_snap.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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Martin Poirier
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/transform/transform_snap.c
29  *  \ingroup edtransform
30  */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <float.h>
35 #include <stdio.h>
36
37 #include "PIL_time.h"
38
39 #include "DNA_scene_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_meshdata_types.h"  /* Temporary, for snapping to other unselected meshes */
42 #include "DNA_node_types.h"
43 #include "DNA_space_types.h"
44 #include "DNA_screen_types.h"
45 #include "DNA_view3d_types.h"
46 #include "DNA_windowmanager_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_utildefines.h"
51
52 #include "BIF_gl.h"
53
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_global.h"
56 #include "BKE_object.h"
57 #include "BKE_anim.h"  /* for duplis */
58 #include "BKE_context.h"
59 #include "BKE_editmesh.h"
60 #include "BKE_sequencer.h"
61 #include "BKE_main.h"
62
63 #include "RNA_access.h"
64
65 #include "WM_types.h"
66
67 #include "ED_image.h"
68 #include "ED_node.h"
69 #include "ED_uvedit.h"
70 #include "ED_view3d.h"
71 #include "ED_transform_snap_object_context.h"
72
73 #include "UI_resources.h"
74 #include "UI_view2d.h"
75
76 #include "MEM_guardedalloc.h"
77
78 #include "transform.h"
79
80 /* this should be passed as an arg for use in snap functions */
81 #undef BASACT
82
83 /* use half of flt-max so we can scale up without an exception */
84
85 /********************* PROTOTYPES ***********************/
86
87 static void setSnappingCallback(TransInfo *t);
88
89 static void ApplySnapTranslation(TransInfo *t, float vec[3]);
90 static void ApplySnapRotation(TransInfo *t, float *vec);
91 static void ApplySnapResize(TransInfo *t, float vec[2]);
92
93 /* static void CalcSnapGrid(TransInfo *t, float *vec); */
94 static void CalcSnapGeometry(TransInfo *t, float *vec);
95
96 static void TargetSnapMedian(TransInfo *t);
97 static void TargetSnapCenter(TransInfo *t);
98 static void TargetSnapClosest(TransInfo *t);
99 static void TargetSnapActive(TransInfo *t);
100
101 static float RotationBetween(TransInfo *t, const float p1[3], const float p2[3]);
102 static float TranslationBetween(TransInfo *t, const float p1[3], const float p2[3]);
103 static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3]);
104
105
106 /****************** IMPLEMENTATIONS *********************/
107
108 static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select);
109 static NodeBorder snapNodeBorder(int snap_node_mode);
110
111 #if 0
112 int BIF_snappingSupported(Object *obedit)
113 {
114         int status = 0;
115
116         /* only support object mesh, armature, curves */
117         if (obedit == NULL || ELEM(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE, OB_MBALL)) {
118                 status = 1;
119         }
120
121         return status;
122 }
123 #endif
124
125 bool validSnap(TransInfo *t)
126 {
127         return (t->tsnap.status & (POINT_INIT | TARGET_INIT)) == (POINT_INIT | TARGET_INIT) ||
128                (t->tsnap.status & (MULTI_POINTS | TARGET_INIT)) == (MULTI_POINTS | TARGET_INIT);
129 }
130
131 bool activeSnap(TransInfo *t)
132 {
133         return ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP) ||
134                ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP_INVERT);
135 }
136
137 void drawSnapping(const struct bContext *C, TransInfo *t)
138 {
139         unsigned char col[4], selectedCol[4], activeCol[4];
140
141         if (!activeSnap(t))
142                 return;
143
144         UI_GetThemeColor3ubv(TH_TRANSFORM, col);
145         col[3] = 128;
146
147         UI_GetThemeColor3ubv(TH_SELECT, selectedCol);
148         selectedCol[3] = 128;
149
150         UI_GetThemeColor3ubv(TH_ACTIVE, activeCol);
151         activeCol[3] = 192;
152
153         if (t->spacetype == SPACE_VIEW3D) {
154                 if (validSnap(t)) {
155                         TransSnapPoint *p;
156                         View3D *v3d = CTX_wm_view3d(C);
157                         RegionView3D *rv3d = CTX_wm_region_view3d(C);
158                         float imat[4][4];
159                         float size;
160
161                         glDisable(GL_DEPTH_TEST);
162
163                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
164
165                         invert_m4_m4(imat, rv3d->viewmat);
166
167                         for (p = t->tsnap.points.first; p; p = p->next) {
168                                 if (p == t->tsnap.selectedPoint) {
169                                         glColor4ubv(selectedCol);
170                                 }
171                                 else {
172                                         glColor4ubv(col);
173                                 }
174
175                                 drawcircball(GL_LINE_LOOP, p->co, ED_view3d_pixel_size(rv3d, p->co) * size * 0.75f, imat);
176                         }
177
178                         if (t->tsnap.status & POINT_INIT) {
179                                 glColor4ubv(activeCol);
180
181                                 drawcircball(GL_LINE_LOOP, t->tsnap.snapPoint, ED_view3d_pixel_size(rv3d, t->tsnap.snapPoint) * size, imat);
182                         }
183
184                         /* draw normal if needed */
185                         if (usingSnappingNormal(t) && validSnappingNormal(t)) {
186                                 glColor4ubv(activeCol);
187
188                                 glBegin(GL_LINES);
189                                 glVertex3f(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], t->tsnap.snapPoint[2]);
190                                 glVertex3f(t->tsnap.snapPoint[0] + t->tsnap.snapNormal[0],
191                                            t->tsnap.snapPoint[1] + t->tsnap.snapNormal[1],
192                                            t->tsnap.snapPoint[2] + t->tsnap.snapNormal[2]);
193                                 glEnd();
194                         }
195
196                         if (v3d->zbuf)
197                                 glEnable(GL_DEPTH_TEST);
198                 }
199         }
200         else if (t->spacetype == SPACE_IMAGE) {
201                 if (validSnap(t)) {
202                         /* This will not draw, and Im nor sure why - campbell */
203 #if 0
204                         float xuser_asp, yuser_asp;
205                         int wi, hi;
206                         float w, h;
207
208                         calc_image_view(G.sima, 'f');   // float
209                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
210                         glLoadIdentity();
211
212                         ED_space_image_get_aspect(t->sa->spacedata.first, &xuser_aspx, &yuser_asp);
213                         ED_space_image_width(t->sa->spacedata.first, &wi, &hi);
214                         w = (((float)wi) / IMG_SIZE_FALLBACK) * G.sima->zoom * xuser_asp;
215                         h = (((float)hi) / IMG_SIZE_FALLBACK) * G.sima->zoom * yuser_asp;
216
217                         cpack(0xFFFFFF);
218                         glTranslate2fv(t->tsnap.snapPoint);
219
220                         //glRectf(0, 0, 1, 1);
221
222                         setlinestyle(0);
223                         cpack(0x0);
224                         fdrawline(-0.020 / w, 0, -0.1 / w, 0);
225                         fdrawline(0.1 / w, 0, 0.020 / w, 0);
226                         fdrawline(0, -0.020 / h, 0, -0.1 / h);
227                         fdrawline(0, 0.1 / h, 0, 0.020 / h);
228
229                         glTranslatef(-t->tsnap.snapPoint[0], -t->tsnap.snapPoint[1], 0.0f);
230                         setlinestyle(0);
231 #endif
232                 }
233         }
234         else if (t->spacetype == SPACE_NODE) {
235                 if (validSnap(t)) {
236                         ARegion *ar = CTX_wm_region(C);
237                         TransSnapPoint *p;
238                         float size;
239
240                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
241
242                         glEnable(GL_BLEND);
243
244                         for (p = t->tsnap.points.first; p; p = p->next) {
245                                 if (p == t->tsnap.selectedPoint) {
246                                         glColor4ubv(selectedCol);
247                                 }
248                                 else {
249                                         glColor4ubv(col);
250                                 }
251
252                                 ED_node_draw_snap(&ar->v2d, p->co, size, 0);
253                         }
254
255                         if (t->tsnap.status & POINT_INIT) {
256                                 glColor4ubv(activeCol);
257
258                                 ED_node_draw_snap(&ar->v2d, t->tsnap.snapPoint, size, t->tsnap.snapNodeBorder);
259                         }
260
261                         glDisable(GL_BLEND);
262                 }
263         }
264 }
265
266 eRedrawFlag handleSnapping(TransInfo *t, const wmEvent *event)
267 {
268         eRedrawFlag status = TREDRAW_NOTHING;
269
270 #if 0 // XXX need a proper selector for all snap mode
271         if (BIF_snappingSupported(t->obedit) && event->type == TABKEY && event->shift) {
272                 /* toggle snap and reinit */
273                 t->settings->snap_flag ^= SCE_SNAP;
274                 initSnapping(t, NULL);
275                 status = TREDRAW_HARD;
276         }
277 #endif
278         if (event->type == MOUSEMOVE) {
279                 status |= updateSelectedSnapPoint(t);
280         }
281
282         return status;
283 }
284
285 void applyProject(TransInfo *t)
286 {
287         Main *bmain = CTX_data_main(t->context);
288
289         /* XXX FLICKER IN OBJECT MODE */
290         if ((t->tsnap.project) && activeSnap(t) && (t->flag & T_NO_PROJECT) == 0) {
291                 TransData *td = t->data;
292                 float tvec[3];
293                 float imat[4][4];
294                 int i;
295
296                 if (t->flag & (T_EDIT | T_POSE)) {
297                         Object *ob = t->obedit ? t->obedit : t->poseobj;
298                         invert_m4_m4(imat, ob->obmat);
299                 }
300
301                 for (i = 0; i < t->total; i++, td++) {
302                         float iloc[3], loc[3], no[3];
303                         float mval_fl[2];
304                         float dist_px = TRANSFORM_DIST_MAX_PX;
305
306                         if (td->flag & TD_NOACTION)
307                                 break;
308
309                         if (td->flag & TD_SKIP)
310                                 continue;
311
312                         if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
313                                 continue;
314
315                         copy_v3_v3(iloc, td->loc);
316                         if (t->flag & (T_EDIT | T_POSE)) {
317                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
318                                 mul_m4_v3(ob->obmat, iloc);
319                         }
320                         else if (t->flag & T_OBJECT) {
321                                 BKE_object_eval_transform_all(bmain->eval_ctx, t->scene, td->ob);
322                                 copy_v3_v3(iloc, td->ob->obmat[3]);
323                         }
324
325                         if (ED_view3d_project_float_global(t->ar, iloc, mval_fl, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
326                                 if (snapObjectsTransform(
327                                         t, mval_fl, &dist_px,
328                                         loc, no))
329                                 {
330 //                                      if (t->flag & (T_EDIT|T_POSE)) {
331 //                                              mul_m4_v3(imat, loc);
332 //                                      }
333
334                                         sub_v3_v3v3(tvec, loc, iloc);
335
336                                         mul_m3_v3(td->smtx, tvec);
337
338                                         add_v3_v3(td->loc, tvec);
339
340                                         if (t->tsnap.align && (t->flag & T_OBJECT)) {
341                                                 /* handle alignment as well */
342                                                 const float *original_normal;
343                                                 float mat[3][3];
344
345                                                 /* In pose mode, we want to align normals with Y axis of bones... */
346                                                 original_normal = td->axismtx[2];
347
348                                                 rotation_between_vecs_to_mat3(mat, original_normal, no);
349
350                                                 transform_data_ext_rotate(td, mat, true);
351
352                                                 /* TODO support constraints for rotation too? see ElementRotation */
353                                         }
354                                 }
355                         }
356
357                         //XXX constraintTransLim(t, td);
358                 }
359         }
360 }
361
362 void applyGridAbsolute(TransInfo *t)
363 {
364         Main *bmain = CTX_data_main(t->context);
365
366         float grid_size = 0.0f;
367         GearsType grid_action;
368         TransData *td;
369         float (*obmat)[4] = NULL;
370         bool use_obmat = false;
371         int i;
372
373         if (!(activeSnap(t) && (ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))))
374                 return;
375
376         grid_action = BIG_GEARS;
377         if (t->modifiers & MOD_PRECISION)
378                 grid_action = SMALL_GEARS;
379
380         switch (grid_action) {
381                 case NO_GEARS: grid_size = t->snap_spatial[0]; break;
382                 case BIG_GEARS: grid_size = t->snap_spatial[1]; break;
383                 case SMALL_GEARS: grid_size = t->snap_spatial[2]; break;
384         }
385         /* early exit on unusable grid size */
386         if (grid_size == 0.0f)
387                 return;
388
389         if (t->flag & (T_EDIT | T_POSE)) {
390                 Object *ob = t->obedit ? t->obedit : t->poseobj;
391                 obmat = ob->obmat;
392                 use_obmat = true;
393         }
394
395         for (i = 0, td = t->data; i < t->total; i++, td++) {
396                 float iloc[3], loc[3], tvec[3];
397
398                 if (td->flag & TD_NOACTION)
399                         break;
400
401                 if (td->flag & TD_SKIP)
402                         continue;
403
404                 if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
405                         continue;
406
407                 copy_v3_v3(iloc, td->loc);
408                 if (use_obmat) {
409                         mul_m4_v3(obmat, iloc);
410                 }
411                 else if (t->flag & T_OBJECT) {
412                         BKE_object_eval_transform_all(bmain->eval_ctx, t->scene, td->ob);
413                         copy_v3_v3(iloc, td->ob->obmat[3]);
414                 }
415
416                 mul_v3_v3fl(loc, iloc, 1.0f / grid_size);
417                 loc[0] = roundf(loc[0]);
418                 loc[1] = roundf(loc[1]);
419                 loc[2] = roundf(loc[2]);
420                 mul_v3_fl(loc, grid_size);
421
422                 sub_v3_v3v3(tvec, loc, iloc);
423                 mul_m3_v3(td->smtx, tvec);
424                 add_v3_v3(td->loc, tvec);
425         }
426 }
427
428 void applySnapping(TransInfo *t, float *vec)
429 {
430         /* project is not applied this way */
431         if (t->tsnap.project)
432                 return;
433
434         if (t->tsnap.status & SNAP_FORCED) {
435                 t->tsnap.targetSnap(t);
436
437                 t->tsnap.applySnap(t, vec);
438         }
439         else if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID) && activeSnap(t)) {
440                 double current = PIL_check_seconds_timer();
441
442                 // Time base quirky code to go around findnearest slowness
443                 /* !TODO! add exception for object mode, no need to slow it down then */
444                 if (current - t->tsnap.last >= 0.01) {
445                         t->tsnap.calcSnap(t, vec);
446                         t->tsnap.targetSnap(t);
447
448                         t->tsnap.last = current;
449                 }
450                 if (validSnap(t)) {
451                         t->tsnap.applySnap(t, vec);
452                 }
453         }
454 }
455
456 void resetSnapping(TransInfo *t)
457 {
458         t->tsnap.status = 0;
459         t->tsnap.align = false;
460         t->tsnap.project = 0;
461         t->tsnap.mode = 0;
462         t->tsnap.modeSelect = 0;
463         t->tsnap.target = 0;
464         t->tsnap.last = 0;
465         t->tsnap.applySnap = NULL;
466
467         t->tsnap.snapNormal[0] = 0;
468         t->tsnap.snapNormal[1] = 0;
469         t->tsnap.snapNormal[2] = 0;
470
471         t->tsnap.snapNodeBorder = 0;
472 }
473
474 bool usingSnappingNormal(TransInfo *t)
475 {
476         return t->tsnap.align;
477 }
478
479 bool validSnappingNormal(TransInfo *t)
480 {
481         if (validSnap(t)) {
482                 if (!is_zero_v3(t->tsnap.snapNormal)) {
483                         return true;
484                 }
485         }
486
487         return false;
488 }
489
490 static bool bm_edge_is_snap_target(BMEdge *e, void *UNUSED(user_data))
491 {
492         if (BM_elem_flag_test(e, BM_ELEM_SELECT | BM_ELEM_HIDDEN) ||
493             BM_elem_flag_test(e->v1, BM_ELEM_SELECT) ||
494             BM_elem_flag_test(e->v2, BM_ELEM_SELECT))
495         {
496                 return false;
497         }
498
499         return true;
500 }
501
502 static bool bm_face_is_snap_target(BMFace *f, void *UNUSED(user_data))
503 {
504         if (BM_elem_flag_test(f, BM_ELEM_SELECT | BM_ELEM_HIDDEN)) {
505                 return false;
506         }
507
508         BMLoop *l_iter, *l_first;
509         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
510         do {
511                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
512                         return false;
513                 }
514         } while ((l_iter = l_iter->next) != l_first);
515
516         return true;
517 }
518
519 static void initSnappingMode(TransInfo *t)
520 {
521         Main *bmain = CTX_data_main(t->context);
522         ToolSettings *ts = t->settings;
523         Object *obedit = t->obedit;
524         Scene *scene = t->scene;
525         Base *base_act = scene->basact;
526
527         if (t->spacetype == SPACE_NODE) {
528                 /* force project off when not supported */
529                 t->tsnap.project = 0;
530
531                 t->tsnap.mode = ts->snap_node_mode;
532         }
533         else if (t->spacetype == SPACE_IMAGE) {
534                 /* force project off when not supported */
535                 t->tsnap.project = 0;
536
537                 t->tsnap.mode = ts->snap_uv_mode;
538         }
539         else {
540                 /* force project off when not supported */
541                 if (ts->snap_mode != SCE_SNAP_MODE_FACE)
542                         t->tsnap.project = 0;
543
544                 t->tsnap.mode = ts->snap_mode;
545         }
546
547         if ((t->spacetype == SPACE_VIEW3D || t->spacetype == SPACE_IMAGE) &&  /* Only 3D view or UV */
548             (t->flag & T_CAMERA) == 0)  /* Not with camera selected in camera view */
549         {
550                 setSnappingCallback(t);
551
552                 /* Edit mode */
553                 if (t->tsnap.applySnap != NULL && // A snapping function actually exist
554                     (obedit != NULL && ELEM(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE, OB_MBALL)) ) // Temporary limited to edit mode meshes, armature, curves, mballs
555                 {
556                         /* Exclude editmesh if using proportional edit */
557                         if ((obedit->type == OB_MESH) && (t->flag & T_PROP_EDIT)) {
558                                 t->tsnap.modeSelect = SNAP_NOT_ACTIVE;
559                         }
560                         else {
561                                 t->tsnap.modeSelect = t->tsnap.snap_self ? SNAP_ALL : SNAP_NOT_ACTIVE;
562                         }
563                 }
564                 /* Particles edit mode*/
565                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
566                          (obedit == NULL && base_act && base_act->object && base_act->object->mode & OB_MODE_PARTICLE_EDIT))
567                 {
568                         t->tsnap.modeSelect = SNAP_ALL;
569                 }
570                 /* Object mode */
571                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
572                          (obedit == NULL) ) // Object Mode
573                 {
574                         /* In "Edit Strokes" mode, Snap tool can perform snap to selected or active objects (see T49632)
575                          * TODO: perform self snap in gpencil_strokes */
576                         t->tsnap.modeSelect = ((t->options & CTX_GPENCIL_STROKES) != 0) ? SNAP_ALL : SNAP_NOT_SELECTED;
577                 }
578                 else {
579                         /* Grid if snap is not possible */
580                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
581                 }
582         }
583         else if (t->spacetype == SPACE_NODE) {
584                 setSnappingCallback(t);
585
586                 if (t->tsnap.applySnap != NULL) {
587                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
588                 }
589                 else {
590                         /* Grid if snap is not possible */
591                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
592                 }
593         }
594         else if (t->spacetype == SPACE_SEQ) {
595                 /* We do our own snapping currently, so nothing here */
596                 t->tsnap.mode = SCE_SNAP_MODE_GRID;  /* Dummy, should we rather add a NOP mode? */
597         }
598         else {
599                 /* Always grid outside of 3D view */
600                 t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
601         }
602
603         if (t->spacetype == SPACE_VIEW3D) {
604                 if (t->tsnap.object_context == NULL) {
605                         t->tsnap.object_context = ED_transform_snap_object_context_create_view3d(
606                                 bmain, t->scene, 0,
607                                 t->ar, t->view);
608
609                         ED_transform_snap_object_context_set_editmesh_callbacks(
610                                 t->tsnap.object_context,
611                                 (bool (*)(BMVert *, void *))BM_elem_cb_check_hflag_disabled,
612                                 bm_edge_is_snap_target,
613                                 bm_face_is_snap_target,
614                                 SET_UINT_IN_POINTER((BM_ELEM_SELECT | BM_ELEM_HIDDEN)));
615                 }
616         }
617 }
618
619 void initSnapping(TransInfo *t, wmOperator *op)
620 {
621         ToolSettings *ts = t->settings;
622         short snap_target = t->settings->snap_target;
623
624         resetSnapping(t);
625
626         /* if snap property exists */
627         if (op && RNA_struct_find_property(op->ptr, "snap") && RNA_struct_property_is_set(op->ptr, "snap")) {
628                 if (RNA_boolean_get(op->ptr, "snap")) {
629                         t->modifiers |= MOD_SNAP;
630
631                         if (RNA_struct_property_is_set(op->ptr, "snap_target")) {
632                                 snap_target = RNA_enum_get(op->ptr, "snap_target");
633                         }
634
635                         if (RNA_struct_property_is_set(op->ptr, "snap_point")) {
636                                 RNA_float_get_array(op->ptr, "snap_point", t->tsnap.snapPoint);
637                                 t->tsnap.status |= SNAP_FORCED | POINT_INIT;
638                         }
639
640                         /* snap align only defined in specific cases */
641                         if (RNA_struct_find_property(op->ptr, "snap_align")) {
642                                 t->tsnap.align = RNA_boolean_get(op->ptr, "snap_align");
643                                 RNA_float_get_array(op->ptr, "snap_normal", t->tsnap.snapNormal);
644                                 normalize_v3(t->tsnap.snapNormal);
645                         }
646
647                         if (RNA_struct_find_property(op->ptr, "use_snap_project")) {
648                                 t->tsnap.project = RNA_boolean_get(op->ptr, "use_snap_project");
649                         }
650
651                         if (RNA_struct_find_property(op->ptr, "use_snap_self")) {
652                                 t->tsnap.snap_self = RNA_boolean_get(op->ptr, "use_snap_self");
653                         }
654                 }
655         }
656         /* use scene defaults only when transform is modal */
657         else if (t->flag & T_MODAL) {
658                 if (ELEM(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE, SPACE_NODE)) {
659                         if (ts->snap_flag & SCE_SNAP) {
660                                 t->modifiers |= MOD_SNAP;
661                         }
662
663                         t->tsnap.align = ((t->settings->snap_flag & SCE_SNAP_ROTATE) != 0);
664                         t->tsnap.project = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
665                         t->tsnap.snap_self = !((t->settings->snap_flag & SCE_SNAP_NO_SELF) != 0);
666                         t->tsnap.peel = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
667                 }
668
669                 /* for now only 3d view (others can be added if we want) */
670                 if (t->spacetype == SPACE_VIEW3D) {
671                         t->tsnap.snap_spatial_grid = ((t->settings->snap_flag & SCE_SNAP_ABS_GRID) != 0);
672                 }
673         }
674
675         t->tsnap.target = snap_target;
676
677         initSnappingMode(t);
678 }
679
680 void freeSnapping(TransInfo *t)
681 {
682         if (t->tsnap.object_context) {
683                 ED_transform_snap_object_context_destroy(t->tsnap.object_context);
684                 t->tsnap.object_context = NULL;
685         }
686 }
687
688 static void setSnappingCallback(TransInfo *t)
689 {
690         t->tsnap.calcSnap = CalcSnapGeometry;
691
692         switch (t->tsnap.target) {
693                 case SCE_SNAP_TARGET_CLOSEST:
694                         t->tsnap.targetSnap = TargetSnapClosest;
695                         break;
696                 case SCE_SNAP_TARGET_CENTER:
697                         t->tsnap.targetSnap = TargetSnapCenter;
698                         break;
699                 case SCE_SNAP_TARGET_MEDIAN:
700                         t->tsnap.targetSnap = TargetSnapMedian;
701                         break;
702                 case SCE_SNAP_TARGET_ACTIVE:
703                         t->tsnap.targetSnap = TargetSnapActive;
704                         break;
705
706         }
707
708         switch (t->mode) {
709                 case TFM_TRANSLATION:
710                         t->tsnap.applySnap = ApplySnapTranslation;
711                         t->tsnap.distance = TranslationBetween;
712                         break;
713                 case TFM_ROTATION:
714                         t->tsnap.applySnap = ApplySnapRotation;
715                         t->tsnap.distance = RotationBetween;
716
717                         // Can't do TARGET_CENTER with rotation, use TARGET_MEDIAN instead
718                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
719                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
720                                 t->tsnap.targetSnap = TargetSnapMedian;
721                         }
722                         break;
723                 case TFM_RESIZE:
724                         t->tsnap.applySnap = ApplySnapResize;
725                         t->tsnap.distance = ResizeBetween;
726
727                         // Can't do TARGET_CENTER with resize, use TARGET_MEDIAN instead
728                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
729                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
730                                 t->tsnap.targetSnap = TargetSnapMedian;
731                         }
732                         break;
733                 default:
734                         t->tsnap.applySnap = NULL;
735                         break;
736         }
737 }
738
739 void addSnapPoint(TransInfo *t)
740 {
741         /* Currently only 3D viewport works for snapping points. */
742         if (t->tsnap.status & POINT_INIT && t->spacetype == SPACE_VIEW3D) {
743                 TransSnapPoint *p = MEM_callocN(sizeof(TransSnapPoint), "SnapPoint");
744
745                 t->tsnap.selectedPoint = p;
746
747                 copy_v3_v3(p->co, t->tsnap.snapPoint);
748
749                 BLI_addtail(&t->tsnap.points, p);
750
751                 t->tsnap.status |= MULTI_POINTS;
752         }
753 }
754
755 eRedrawFlag updateSelectedSnapPoint(TransInfo *t)
756 {
757         eRedrawFlag status = TREDRAW_NOTHING;
758
759         if (t->tsnap.status & MULTI_POINTS) {
760                 TransSnapPoint *p, *closest_p = NULL;
761                 float dist_min_sq = TRANSFORM_SNAP_MAX_PX;
762                 const float mval_fl[2] = {t->mval[0], t->mval[1]};
763                 float screen_loc[2];
764
765                 for (p = t->tsnap.points.first; p; p = p->next) {
766                         float dist_sq;
767
768                         if (ED_view3d_project_float_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
769                                 continue;
770                         }
771
772                         dist_sq = len_squared_v2v2(mval_fl, screen_loc);
773
774                         if (dist_sq < dist_min_sq) {
775                                 closest_p = p;
776                                 dist_min_sq = dist_sq;
777                         }
778                 }
779
780                 if (closest_p) {
781                         if (t->tsnap.selectedPoint != closest_p) {
782                                 status = TREDRAW_HARD;
783                         }
784
785                         t->tsnap.selectedPoint = closest_p;
786                 }
787         }
788
789         return status;
790 }
791
792 void removeSnapPoint(TransInfo *t)
793 {
794         if (t->tsnap.status & MULTI_POINTS) {
795                 updateSelectedSnapPoint(t);
796
797                 if (t->tsnap.selectedPoint) {
798                         BLI_freelinkN(&t->tsnap.points, t->tsnap.selectedPoint);
799
800                         if (BLI_listbase_is_empty(&t->tsnap.points)) {
801                                 t->tsnap.status &= ~MULTI_POINTS;
802                         }
803
804                         t->tsnap.selectedPoint = NULL;
805                 }
806
807         }
808 }
809
810 void getSnapPoint(TransInfo *t, float vec[3])
811 {
812         if (t->tsnap.points.first) {
813                 TransSnapPoint *p;
814                 int total = 0;
815
816                 vec[0] = vec[1] = vec[2] = 0;
817
818                 for (p = t->tsnap.points.first; p; p = p->next, total++) {
819                         add_v3_v3(vec, p->co);
820                 }
821
822                 if (t->tsnap.status & POINT_INIT) {
823                         add_v3_v3(vec, t->tsnap.snapPoint);
824                         total++;
825                 }
826
827                 mul_v3_fl(vec, 1.0f / total);
828         }
829         else {
830                 copy_v3_v3(vec, t->tsnap.snapPoint);
831         }
832 }
833
834 /********************** APPLY **************************/
835
836 static void ApplySnapTranslation(TransInfo *t, float vec[3])
837 {
838         float point[3];
839         getSnapPoint(t, point);
840
841         if (t->spacetype == SPACE_NODE) {
842                 char border = t->tsnap.snapNodeBorder;
843                 if (border & (NODE_LEFT | NODE_RIGHT))
844                         vec[0] = point[0] - t->tsnap.snapTarget[0];
845                 if (border & (NODE_BOTTOM | NODE_TOP))
846                         vec[1] = point[1] - t->tsnap.snapTarget[1];
847         }
848         else {
849                 if (t->spacetype == SPACE_VIEW3D) {
850                         if (t->options & CTX_PAINT_CURVE) {
851                                 if (ED_view3d_project_float_global(t->ar, point, point, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
852                                         zero_v3(point);  /* no good answer here... */
853                                 }
854                         }
855                 }
856
857                 sub_v3_v3v3(vec, point, t->tsnap.snapTarget);
858         }
859 }
860
861 static void ApplySnapRotation(TransInfo *t, float *value)
862 {
863         float point[3];
864         getSnapPoint(t, point);
865
866         float dist = RotationBetween(t, t->tsnap.snapTarget, point);
867         *value = dist;
868 }
869
870 static void ApplySnapResize(TransInfo *t, float vec[3])
871 {
872         float point[3];
873         getSnapPoint(t, point);
874
875         float dist = ResizeBetween(t, t->tsnap.snapTarget, point);
876         copy_v3_fl(vec, dist);
877 }
878
879 /********************** DISTANCE **************************/
880
881 static float TranslationBetween(TransInfo *UNUSED(t), const float p1[3], const float p2[3])
882 {
883         return len_squared_v3v3(p1, p2);
884 }
885
886 static float RotationBetween(TransInfo *t, const float p1[3], const float p2[3])
887 {
888         float angle, start[3], end[3];
889
890         sub_v3_v3v3(start, p1, t->center_global);
891         sub_v3_v3v3(end,   p2, t->center_global);
892
893         // Angle around a constraint axis (error prone, will need debug)
894         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
895                 float axis[3], tmp[3];
896
897                 t->con.applyRot(t, NULL, axis, NULL);
898
899                 project_v3_v3v3(tmp, end, axis);
900                 sub_v3_v3v3(end, end, tmp);
901
902                 project_v3_v3v3(tmp, start, axis);
903                 sub_v3_v3v3(start, start, tmp);
904
905                 normalize_v3(end);
906                 normalize_v3(start);
907
908                 cross_v3_v3v3(tmp, start, end);
909
910                 if (dot_v3v3(tmp, axis) < 0.0f)
911                         angle = -acosf(dot_v3v3(start, end));
912                 else
913                         angle = acosf(dot_v3v3(start, end));
914         }
915         else {
916                 float mtx[3][3];
917
918                 copy_m3_m4(mtx, t->viewmat);
919
920                 mul_m3_v3(mtx, end);
921                 mul_m3_v3(mtx, start);
922
923                 angle = atan2f(start[1], start[0]) - atan2f(end[1], end[0]);
924         }
925
926         if (angle > (float)M_PI) {
927                 angle = angle - 2 * (float)M_PI;
928         }
929         else if (angle < -((float)M_PI)) {
930                 angle = 2.0f * (float)M_PI + angle;
931         }
932
933         return angle;
934 }
935
936 static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3])
937 {
938         float d1[3], d2[3], len_d1;
939
940         sub_v3_v3v3(d1, p1, t->center_global);
941         sub_v3_v3v3(d2, p2, t->center_global);
942
943         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
944                 mul_m3_v3(t->con.pmtx, d1);
945                 mul_m3_v3(t->con.pmtx, d2);
946         }
947
948         project_v3_v3v3(d1, d1, d2);
949
950         len_d1 = len_v3(d1);
951
952         /* Use 'invalid' dist when `center == p1` (after projecting),
953          * in this case scale will _never_ move the point in relation to the center,
954          * so it makes no sense to take it into account when scaling. see: T46503 */
955         return len_d1 != 0.0f ? len_v3(d2) / len_d1 : TRANSFORM_DIST_INVALID;
956 }
957
958 /********************** CALC **************************/
959
960 static void UNUSED_FUNCTION(CalcSnapGrid) (TransInfo *t, float *UNUSED(vec))
961 {
962         snapGridIncrementAction(t, t->tsnap.snapPoint, BIG_GEARS);
963 }
964
965 static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
966 {
967         if (t->spacetype == SPACE_VIEW3D) {
968                 float loc[3];
969                 float no[3];
970                 float mval[2];
971                 bool found = false;
972                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
973
974                 mval[0] = t->mval[0];
975                 mval[1] = t->mval[1];
976
977                 if (t->tsnap.mode == SCE_SNAP_MODE_VOLUME) {
978                         found = peelObjectsTransform(
979                                 t, mval,
980                                 (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) != 0,
981                                 loc, no, NULL);
982                 }
983                 else {
984                         zero_v3(no);  /* objects won't set this */
985                         found = snapObjectsTransform(
986                                 t, mval, &dist_px,
987                                 loc, no);
988                 }
989
990                 if (found == true) {
991                         copy_v3_v3(t->tsnap.snapPoint, loc);
992                         copy_v3_v3(t->tsnap.snapNormal, no);
993
994                         t->tsnap.status |=  POINT_INIT;
995                 }
996                 else {
997                         t->tsnap.status &= ~POINT_INIT;
998                 }
999         }
1000         else if (t->spacetype == SPACE_IMAGE && t->obedit != NULL && t->obedit->type == OB_MESH) {
1001                 /* same as above but for UV's */
1002                 Image *ima = ED_space_image(t->sa->spacedata.first);
1003                 float co[2];
1004
1005                 UI_view2d_region_to_view(&t->ar->v2d, t->mval[0], t->mval[1], &co[0], &co[1]);
1006
1007                 if (ED_uvedit_nearest_uv(t->scene, t->obedit, ima, co, t->tsnap.snapPoint)) {
1008                         t->tsnap.snapPoint[0] *= t->aspect[0];
1009                         t->tsnap.snapPoint[1] *= t->aspect[1];
1010
1011                         t->tsnap.status |=  POINT_INIT;
1012                 }
1013                 else {
1014                         t->tsnap.status &= ~POINT_INIT;
1015                 }
1016         }
1017         else if (t->spacetype == SPACE_NODE) {
1018                 float loc[2];
1019                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
1020                 char node_border;
1021
1022                 if (snapNodesTransform(t, t->mval, loc, &dist_px, &node_border)) {
1023                         copy_v2_v2(t->tsnap.snapPoint, loc);
1024                         t->tsnap.snapNodeBorder = node_border;
1025
1026                         t->tsnap.status |=  POINT_INIT;
1027                 }
1028                 else {
1029                         t->tsnap.status &= ~POINT_INIT;
1030                 }
1031         }
1032 }
1033
1034 /********************** TARGET **************************/
1035
1036 static void TargetSnapOffset(TransInfo *t, TransData *td)
1037 {
1038         if (t->spacetype == SPACE_NODE && td != NULL) {
1039                 bNode *node = td->extra;
1040                 char border = t->tsnap.snapNodeBorder;
1041                 float width  = BLI_rctf_size_x(&node->totr);
1042                 float height = BLI_rctf_size_y(&node->totr);
1043
1044 #ifdef USE_NODE_CENTER
1045                 if (border & NODE_LEFT)
1046                         t->tsnap.snapTarget[0] -= 0.5f * width;
1047                 if (border & NODE_RIGHT)
1048                         t->tsnap.snapTarget[0] += 0.5f * width;
1049                 if (border & NODE_BOTTOM)
1050                         t->tsnap.snapTarget[1] -= 0.5f * height;
1051                 if (border & NODE_TOP)
1052                         t->tsnap.snapTarget[1] += 0.5f * height;
1053 #else
1054                 if (border & NODE_LEFT)
1055                         t->tsnap.snapTarget[0] -= 0.0f;
1056                 if (border & NODE_RIGHT)
1057                         t->tsnap.snapTarget[0] += width;
1058                 if (border & NODE_BOTTOM)
1059                         t->tsnap.snapTarget[1] -= height;
1060                 if (border & NODE_TOP)
1061                         t->tsnap.snapTarget[1] += 0.0f;
1062 #endif
1063         }
1064 }
1065
1066 static void TargetSnapCenter(TransInfo *t)
1067 {
1068         /* Only need to calculate once */
1069         if ((t->tsnap.status & TARGET_INIT) == 0) {
1070                 copy_v3_v3(t->tsnap.snapTarget, t->center_global);
1071                 TargetSnapOffset(t, NULL);
1072
1073                 t->tsnap.status |= TARGET_INIT;
1074         }
1075 }
1076
1077 static void TargetSnapActive(TransInfo *t)
1078 {
1079         /* Only need to calculate once */
1080         if ((t->tsnap.status & TARGET_INIT) == 0) {
1081                 if (calculateCenterActive(t, true, t->tsnap.snapTarget)) {
1082                         if (t->flag & (T_EDIT | T_POSE)) {
1083                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
1084                                 mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1085                         }
1086
1087                         TargetSnapOffset(t, NULL);
1088
1089                         t->tsnap.status |= TARGET_INIT;
1090                 }
1091                 /* No active, default to median */
1092                 else {
1093                         t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
1094                         t->tsnap.targetSnap = TargetSnapMedian;
1095                         TargetSnapMedian(t);
1096                 }
1097         }
1098 }
1099
1100 static void TargetSnapMedian(TransInfo *t)
1101 {
1102         // Only need to calculate once
1103         if ((t->tsnap.status & TARGET_INIT) == 0) {
1104                 TransData *td = NULL;
1105                 int i;
1106
1107                 t->tsnap.snapTarget[0] = 0;
1108                 t->tsnap.snapTarget[1] = 0;
1109                 t->tsnap.snapTarget[2] = 0;
1110
1111                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1112                         add_v3_v3(t->tsnap.snapTarget, td->center);
1113                 }
1114
1115                 mul_v3_fl(t->tsnap.snapTarget, 1.0 / i);
1116
1117                 if (t->flag & (T_EDIT | T_POSE)) {
1118                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1119                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1120                 }
1121
1122                 TargetSnapOffset(t, NULL);
1123
1124                 t->tsnap.status |= TARGET_INIT;
1125         }
1126 }
1127
1128 static void TargetSnapClosest(TransInfo *t)
1129 {
1130         // Only valid if a snap point has been selected
1131         if (t->tsnap.status & POINT_INIT) {
1132                 float dist_closest = 0.0f;
1133                 TransData *closest = NULL, *td = NULL;
1134
1135                 /* Object mode */
1136                 if (t->flag & T_OBJECT) {
1137                         int i;
1138                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1139                                 struct BoundBox *bb = BKE_object_boundbox_get(td->ob);
1140
1141                                 /* use boundbox if possible */
1142                                 if (bb) {
1143                                         int j;
1144
1145                                         for (j = 0; j < 8; j++) {
1146                                                 float loc[3];
1147                                                 float dist;
1148
1149                                                 copy_v3_v3(loc, bb->vec[j]);
1150                                                 mul_m4_v3(td->ext->obmat, loc);
1151
1152                                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1153
1154                                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1155                                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1156                                                 {
1157                                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1158                                                         closest = td;
1159                                                         dist_closest = dist;
1160                                                 }
1161                                         }
1162                                 }
1163                                 /* use element center otherwise */
1164                                 else {
1165                                         float loc[3];
1166                                         float dist;
1167
1168                                         copy_v3_v3(loc, td->center);
1169
1170                                         dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1171
1172                                         if ((dist != TRANSFORM_DIST_INVALID) &&
1173                                             (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1174                                         {
1175                                                 copy_v3_v3(t->tsnap.snapTarget, loc);
1176                                                 closest = td;
1177                                         }
1178                                 }
1179                         }
1180                 }
1181                 else {
1182                         int i;
1183                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1184                                 float loc[3];
1185                                 float dist;
1186
1187                                 copy_v3_v3(loc, td->center);
1188
1189                                 if (t->flag & (T_EDIT | T_POSE)) {
1190                                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1191                                         mul_m4_v3(ob->obmat, loc);
1192                                 }
1193
1194                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1195
1196                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1197                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1198                                 {
1199                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1200                                         closest = td;
1201                                         dist_closest = dist;
1202                                 }
1203                         }
1204                 }
1205
1206                 TargetSnapOffset(t, closest);
1207
1208                 t->tsnap.status |= TARGET_INIT;
1209         }
1210 }
1211
1212 bool snapObjectsTransform(
1213         TransInfo *t, const float mval[2],
1214         float *dist_px,
1215         float r_loc[3], float r_no[3])
1216 {
1217         return ED_transform_snap_object_project_view3d_ex(
1218                 t->tsnap.object_context,
1219                 t->scene->toolsettings->snap_mode,
1220                 &(const struct SnapObjectParams){
1221                     .snap_select = t->tsnap.modeSelect,
1222                     .use_object_edit_cage = (t->flag & T_EDIT) != 0,
1223                 },
1224                 mval, dist_px, NULL,
1225                 r_loc, r_no, NULL,
1226                 NULL, NULL);
1227 }
1228
1229
1230 /******************** PEELING *********************************/
1231
1232 bool peelObjectsSnapContext(
1233         SnapObjectContext *sctx,
1234         const float mval[2],
1235         const struct SnapObjectParams *params,
1236         const bool use_peel_object,
1237         /* return args */
1238         float r_loc[3], float r_no[3], float *r_thickness)
1239 {
1240         ListBase depths_peel = {0};
1241         ED_transform_snap_object_project_all_view3d_ex(
1242                 sctx,
1243                 params,
1244                 mval, -1.0f, false,
1245                 &depths_peel);
1246
1247         if (!BLI_listbase_is_empty(&depths_peel)) {
1248                 /* At the moment we only use the hits of the first object */
1249                 struct SnapObjectHitDepth *hit_min = depths_peel.first;
1250                 for (struct SnapObjectHitDepth *iter = hit_min->next; iter; iter = iter->next) {
1251                         if (iter->depth < hit_min->depth) {
1252                                 hit_min = iter;
1253                         }
1254                 }
1255                 struct SnapObjectHitDepth *hit_max = NULL;
1256
1257                 if (use_peel_object) {
1258                         /* if peeling objects, take the first and last from each object */
1259                         hit_max = hit_min;
1260                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1261                                 if ((iter->depth > hit_max->depth) && (iter->ob_uuid == hit_min->ob_uuid)) {
1262                                         hit_max = iter;
1263                                 }
1264                         }
1265                 }
1266                 else {
1267                         /* otherwise, pair first with second and so on */
1268                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1269                                 if ((iter != hit_min) && (iter->ob_uuid == hit_min->ob_uuid)) {
1270                                         if (hit_max == NULL) {
1271                                                 hit_max = iter;
1272                                         }
1273                                         else if (iter->depth < hit_max->depth) {
1274                                                 hit_max = iter;
1275                                         }
1276                                 }
1277                         }
1278                         /* in this case has only one hit. treat as raycast */
1279                         if (hit_max == NULL) {
1280                                 hit_max = hit_min;
1281                         }
1282                 }
1283
1284                 mid_v3_v3v3(r_loc, hit_min->co, hit_max->co);
1285
1286                 if (r_thickness) {
1287                         *r_thickness = hit_max->depth - hit_min->depth;
1288                 }
1289
1290                 /* XXX, is there a correct normal in this case ???, for now just z up */
1291                 r_no[0] = 0.0;
1292                 r_no[1] = 0.0;
1293                 r_no[2] = 1.0;
1294
1295                 BLI_freelistN(&depths_peel);
1296                 return true;
1297         }
1298         return false;
1299 }
1300
1301 bool peelObjectsTransform(
1302         TransInfo *t,
1303         const float mval[2],
1304         const bool use_peel_object,
1305         /* return args */
1306         float r_loc[3], float r_no[3], float *r_thickness)
1307 {
1308         return peelObjectsSnapContext(
1309                 t->tsnap.object_context,
1310                 mval,
1311                 &(const struct SnapObjectParams){
1312                     .snap_select = t->tsnap.modeSelect,
1313                     .use_object_edit_cage = (t->flag & T_EDIT) != 0,
1314                 },
1315                 use_peel_object,
1316                 r_loc, r_no, r_thickness);
1317 }
1318
1319 /******************** NODES ***********************************/
1320
1321 static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select)
1322 {
1323         /* node is use for snapping only if a) snap mode matches and b) node is inside the view */
1324         return ((snap_select == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
1325                 (snap_select == SNAP_ALL          && !(node->flag & NODE_ACTIVE))) &&
1326                 (node->totr.xmin < v2d->cur.xmax && node->totr.xmax > v2d->cur.xmin &&
1327                  node->totr.ymin < v2d->cur.ymax && node->totr.ymax > v2d->cur.ymin);
1328 }
1329
1330 static NodeBorder snapNodeBorder(int snap_node_mode)
1331 {
1332         switch (snap_node_mode) {
1333                 case SCE_SNAP_MODE_NODE_X:
1334                         return NODE_LEFT | NODE_RIGHT;
1335                 case SCE_SNAP_MODE_NODE_Y:
1336                         return NODE_TOP | NODE_BOTTOM;
1337                 case SCE_SNAP_MODE_NODE_XY:
1338                         return NODE_LEFT | NODE_RIGHT | NODE_TOP | NODE_BOTTOM;
1339         }
1340         return 0;
1341 }
1342
1343 static bool snapNode(
1344         ToolSettings *ts, SpaceNode *UNUSED(snode), ARegion *ar, bNode *node, const int mval[2],
1345         float r_loc[2], float *r_dist_px, char *r_node_border)
1346 {
1347         View2D *v2d = &ar->v2d;
1348         NodeBorder border = snapNodeBorder(ts->snap_node_mode);
1349         bool retval = false;
1350         rcti totr;
1351         int new_dist;
1352
1353         UI_view2d_view_to_region_rcti(v2d, &node->totr, &totr);
1354
1355         if (border & NODE_LEFT) {
1356                 new_dist = abs(totr.xmin - mval[0]);
1357                 if (new_dist < *r_dist_px) {
1358                         UI_view2d_region_to_view(v2d, totr.xmin, mval[1], &r_loc[0], &r_loc[1]);
1359                         *r_dist_px = new_dist;
1360                         *r_node_border = NODE_LEFT;
1361                         retval = true;
1362                 }
1363         }
1364
1365         if (border & NODE_RIGHT) {
1366                 new_dist = abs(totr.xmax - mval[0]);
1367                 if (new_dist < *r_dist_px) {
1368                         UI_view2d_region_to_view(v2d, totr.xmax, mval[1], &r_loc[0], &r_loc[1]);
1369                         *r_dist_px = new_dist;
1370                         *r_node_border = NODE_RIGHT;
1371                         retval = true;
1372                 }
1373         }
1374
1375         if (border & NODE_BOTTOM) {
1376                 new_dist = abs(totr.ymin - mval[1]);
1377                 if (new_dist < *r_dist_px) {
1378                         UI_view2d_region_to_view(v2d, mval[0], totr.ymin, &r_loc[0], &r_loc[1]);
1379                         *r_dist_px = new_dist;
1380                         *r_node_border = NODE_BOTTOM;
1381                         retval = true;
1382                 }
1383         }
1384
1385         if (border & NODE_TOP) {
1386                 new_dist = abs(totr.ymax - mval[1]);
1387                 if (new_dist < *r_dist_px) {
1388                         UI_view2d_region_to_view(v2d, mval[0], totr.ymax, &r_loc[0], &r_loc[1]);
1389                         *r_dist_px = new_dist;
1390                         *r_node_border = NODE_TOP;
1391                         retval = true;
1392                 }
1393         }
1394
1395         return retval;
1396 }
1397
1398 static bool snapNodes(
1399         ToolSettings *ts, SpaceNode *snode, ARegion *ar,
1400         const int mval[2], eSnapSelect snap_select,
1401         float r_loc[2], float *r_dist_px, char *r_node_border)
1402 {
1403         bNodeTree *ntree = snode->edittree;
1404         bNode *node;
1405         bool retval = false;
1406
1407         *r_node_border = 0;
1408
1409         for (node = ntree->nodes.first; node; node = node->next) {
1410                 if (snapNodeTest(&ar->v2d, node, snap_select)) {
1411                         retval |= snapNode(ts, snode, ar, node, mval, r_loc, r_dist_px, r_node_border);
1412                 }
1413         }
1414
1415         return retval;
1416 }
1417
1418 bool snapNodesTransform(
1419         TransInfo *t, const int mval[2],
1420         float r_loc[2], float *r_dist_px, char *r_node_border)
1421 {
1422         return snapNodes(
1423                 t->settings, t->sa->spacedata.first, t->ar, mval, t->tsnap.modeSelect,
1424                 r_loc, r_dist_px, r_node_border);
1425 }
1426
1427 /*================================================================*/
1428
1429 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action);
1430
1431
1432 void snapGridIncrementAction(TransInfo *t, float *val, GearsType action)
1433 {
1434         float fac[3];
1435
1436         fac[NO_GEARS]    = t->snap[0];
1437         fac[BIG_GEARS]   = t->snap[1];
1438         fac[SMALL_GEARS] = t->snap[2];
1439
1440         applyGridIncrement(t, val, t->idx_max, fac, action);
1441 }
1442
1443
1444 void snapGridIncrement(TransInfo *t, float *val)
1445 {
1446         GearsType action;
1447
1448         /* only do something if using absolute or incremental grid snapping */
1449         if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))
1450                 return;
1451
1452         action = activeSnap(t) ? BIG_GEARS : NO_GEARS;
1453
1454         if (action == BIG_GEARS && (t->modifiers & MOD_PRECISION)) {
1455                 action = SMALL_GEARS;
1456         }
1457
1458         snapGridIncrementAction(t, val, action);
1459 }
1460
1461 void snapSequenceBounds(TransInfo *t, const int mval[2])
1462 {
1463         float xmouse, ymouse;
1464         int frame;
1465         int mframe;
1466         TransSeq *ts = t->custom.type.data;
1467         /* reuse increment, strictly speaking could be another snap mode, but leave as is */
1468         if (!(t->modifiers & MOD_SNAP_INVERT))
1469                 return;
1470
1471         /* convert to frame range */
1472         UI_view2d_region_to_view(&t->ar->v2d, mval[0], mval[1], &xmouse, &ymouse);
1473         mframe = round_fl_to_int(xmouse);
1474         /* now find the closest sequence */
1475         frame = BKE_sequencer_find_next_prev_edit(t->scene, mframe, SEQ_SIDE_BOTH, true, false, true);
1476
1477         if (!ts->snap_left)
1478                 frame = frame - (ts->max - ts->min);
1479
1480         t->values[0] = frame - ts->min;
1481 }
1482
1483 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action)
1484 {
1485         float asp_local[3] = {1, 1, 1};
1486         const bool use_aspect = ELEM(t->mode, TFM_TRANSLATION);
1487         const float *asp = use_aspect ? t->aspect : asp_local;
1488         int i;
1489
1490         BLI_assert(ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID));
1491         BLI_assert(max_index <= 2);
1492
1493         /* Early bailing out if no need to snap */
1494         if (fac[action] == 0.0f) {
1495                 return;
1496         }
1497
1498         if (use_aspect) {
1499                 /* custom aspect for fcurve */
1500                 if (t->spacetype == SPACE_IPO) {
1501                         View2D *v2d = &t->ar->v2d;
1502                         View2DGrid *grid;
1503                         SpaceIpo *sipo = t->sa->spacedata.first;
1504                         int unity = V2D_UNIT_VALUES;
1505                         int unitx = (sipo->flag & SIPO_DRAWTIME) ? V2D_UNIT_SECONDS : V2D_UNIT_FRAMESCALE;
1506
1507                         /* grid */
1508                         grid = UI_view2d_grid_calc(t->scene, v2d, unitx, V2D_GRID_NOCLAMP, unity, V2D_GRID_NOCLAMP, t->ar->winx, t->ar->winy);
1509
1510                         UI_view2d_grid_size(grid, &asp_local[0], &asp_local[1]);
1511                         UI_view2d_grid_free(grid);
1512
1513                         asp = asp_local;
1514                 }
1515         }
1516
1517         /* absolute snapping on grid based on global center */
1518         if ((t->tsnap.snap_spatial_grid) && (t->mode == TFM_TRANSLATION)) {
1519                 const float *center_global = t->center_global;
1520
1521                 /* use a fallback for cursor selection,
1522                  * this isn't useful as a global center for absolute grid snapping
1523                  * since its not based on the position of the selection. */
1524                 if (t->around == V3D_AROUND_CURSOR) {
1525                         const TransCenterData *cd = transformCenter_from_type(t, V3D_AROUND_CENTER_MEAN);
1526                         center_global = cd->global;
1527                 }
1528
1529                 for (i = 0; i <= max_index; i++) {
1530                         /* do not let unconstrained axis jump to absolute grid increments */
1531                         if (!(t->con.mode & CON_APPLY) || t->con.mode & (CON_AXIS0 << i)) {
1532                                 const float iter_fac = fac[action] * asp[i];
1533                                 val[i] = iter_fac * roundf((val[i] + center_global[i]) / iter_fac) - center_global[i];
1534                         }
1535                 }
1536         }
1537         else {
1538                 /* relative snapping in fixed increments */
1539                 for (i = 0; i <= max_index; i++) {
1540                         const float iter_fac = fac[action] * asp[i];
1541                         val[i] = iter_fac * roundf(val[i] / iter_fac);
1542                 }
1543         }
1544 }