04bccac2a15f7f69aab939dca6ab9950451b06ef
[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_armature_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"  /* Temporary, for snapping to other unselected meshes */
44 #include "DNA_node_types.h"
45 #include "DNA_space_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_view3d_types.h"
48 #include "DNA_windowmanager_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_utildefines.h"
53
54 #include "BIF_gl.h"
55
56 #include "BKE_DerivedMesh.h"
57 #include "BKE_object.h"
58 #include "BKE_anim.h"  /* for duplis */
59 #include "BKE_context.h"
60 #include "BKE_editmesh.h"
61 #include "BKE_mesh.h"
62 #include "BKE_tracking.h"
63
64 #include "RNA_access.h"
65
66 #include "WM_types.h"
67
68 #include "ED_armature.h"
69 #include "ED_image.h"
70 #include "ED_mesh.h"
71 #include "ED_node.h"
72 #include "ED_uvedit.h"
73 #include "ED_view3d.h"
74
75 #include "UI_resources.h"
76 #include "UI_view2d.h"
77
78 #include "MEM_guardedalloc.h"
79
80 #include "transform.h"
81
82 /* this should be passed as an arg for use in snap functions */
83 #undef BASACT
84
85 #define TRANSFORM_DIST_MAX_PX 1000.0f
86 #define TRANSFORM_SNAP_MAX_PX 100.0f
87 /* use half of flt-max so we can scale up without an exception */
88
89 /********************* PROTOTYPES ***********************/
90
91 static void setSnappingCallback(TransInfo *t);
92
93 static void ApplySnapTranslation(TransInfo *t, float vec[3]);
94 static void ApplySnapRotation(TransInfo *t, float *vec);
95 static void ApplySnapResize(TransInfo *t, float vec[2]);
96
97 /* static void CalcSnapGrid(TransInfo *t, float *vec); */
98 static void CalcSnapGeometry(TransInfo *t, float *vec);
99
100 static void TargetSnapMedian(TransInfo *t);
101 static void TargetSnapCenter(TransInfo *t);
102 static void TargetSnapClosest(TransInfo *t);
103 static void TargetSnapActive(TransInfo *t);
104
105 static float RotationBetween(TransInfo *t, float p1[3], float p2[3]);
106 static float TranslationBetween(TransInfo *t, float p1[3], float p2[3]);
107 static float ResizeBetween(TransInfo *t, float p1[3], float p2[3]);
108
109
110 /****************** IMPLEMENTATIONS *********************/
111
112 static bool snapNodeTest(View2D *v2d, bNode *node, SnapMode mode);
113 static NodeBorder snapNodeBorder(int snap_node_mode);
114
115 #if 0
116 int BIF_snappingSupported(Object *obedit)
117 {
118         int status = 0;
119         
120         if (obedit == NULL || ELEM4(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE)) /* only support object mesh, armature, curves */
121         {
122                 status = 1;
123         }
124         
125         return status;
126 }
127 #endif
128
129 bool validSnap(TransInfo *t)
130 {
131         return (t->tsnap.status & (POINT_INIT | TARGET_INIT)) == (POINT_INIT | TARGET_INIT) ||
132                (t->tsnap.status & (MULTI_POINTS | TARGET_INIT)) == (MULTI_POINTS | TARGET_INIT);
133 }
134
135 bool activeSnap(TransInfo *t)
136 {
137         return ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP) ||
138                ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP_INVERT);
139 }
140
141 void drawSnapping(const struct bContext *C, TransInfo *t)
142 {
143         unsigned char col[4], selectedCol[4], activeCol[4];
144         
145         if (!activeSnap(t))
146                 return;
147         
148         UI_GetThemeColor3ubv(TH_TRANSFORM, col);
149         col[3] = 128;
150         
151         UI_GetThemeColor3ubv(TH_SELECT, selectedCol);
152         selectedCol[3] = 128;
153         
154         UI_GetThemeColor3ubv(TH_ACTIVE, activeCol);
155         activeCol[3] = 192;
156         
157         if (t->spacetype == SPACE_VIEW3D) {
158                 if (validSnap(t)) {
159                         TransSnapPoint *p;
160                         View3D *v3d = CTX_wm_view3d(C);
161                         RegionView3D *rv3d = CTX_wm_region_view3d(C);
162                         float imat[4][4];
163                         float size;
164                         
165                         glDisable(GL_DEPTH_TEST);
166                         
167                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
168                         
169                         invert_m4_m4(imat, rv3d->viewmat);
170                         
171                         for (p = t->tsnap.points.first; p; p = p->next) {
172                                 if (p == t->tsnap.selectedPoint) {
173                                         glColor4ubv(selectedCol);
174                                 }
175                                 else {
176                                         glColor4ubv(col);
177                                 }
178                                 
179                                 drawcircball(GL_LINE_LOOP, p->co, ED_view3d_pixel_size(rv3d, p->co) * size * 0.75f, imat);
180                         }
181                         
182                         if (t->tsnap.status & POINT_INIT) {
183                                 glColor4ubv(activeCol);
184                                 
185                                 drawcircball(GL_LINE_LOOP, t->tsnap.snapPoint, ED_view3d_pixel_size(rv3d, t->tsnap.snapPoint) * size, imat);
186                         }
187                         
188                         /* draw normal if needed */
189                         if (usingSnappingNormal(t) && validSnappingNormal(t)) {
190                                 glColor4ubv(activeCol);
191                                 
192                                 glBegin(GL_LINES);
193                                 glVertex3f(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], t->tsnap.snapPoint[2]);
194                                 glVertex3f(t->tsnap.snapPoint[0] + t->tsnap.snapNormal[0],
195                                            t->tsnap.snapPoint[1] + t->tsnap.snapNormal[1],
196                                            t->tsnap.snapPoint[2] + t->tsnap.snapNormal[2]);
197                                 glEnd();
198                         }
199                         
200                         if (v3d->zbuf)
201                                 glEnable(GL_DEPTH_TEST);
202                 }
203         }
204         else if (t->spacetype == SPACE_IMAGE) {
205                 if (validSnap(t)) {
206                         /* This will not draw, and Im nor sure why - campbell */
207 #if 0
208                         float xuser_asp, yuser_asp;
209                         int wi, hi;
210                         float w, h;
211                         
212                         calc_image_view(G.sima, 'f');   // float
213                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
214                         glLoadIdentity();
215                         
216                         ED_space_image_get_aspect(t->sa->spacedata.first, &xuser_aspx, &yuser_asp);
217                         ED_space_image_width(t->sa->spacedata.first, &wi, &hi);
218                         w = (((float)wi) / IMG_SIZE_FALLBACK) * G.sima->zoom * xuser_asp;
219                         h = (((float)hi) / IMG_SIZE_FALLBACK) * G.sima->zoom * yuser_asp;
220                         
221                         cpack(0xFFFFFF);
222                         glTranslatef(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], 0.0f);
223                         
224                         //glRectf(0, 0, 1, 1);
225                         
226                         setlinestyle(0);
227                         cpack(0x0);
228                         fdrawline(-0.020 / w, 0, -0.1 / w, 0);
229                         fdrawline(0.1 / w, 0, 0.020 / w, 0);
230                         fdrawline(0, -0.020 / h, 0, -0.1 / h);
231                         fdrawline(0, 0.1 / h, 0, 0.020 / h);
232                         
233                         glTranslatef(-t->tsnap.snapPoint[0], -t->tsnap.snapPoint[1], 0.0f);
234                         setlinestyle(0);
235 #endif
236                 }
237         }
238         else if (t->spacetype == SPACE_NODE) {
239                 if (validSnap(t)) {
240                         ARegion *ar = CTX_wm_region(C);
241                         TransSnapPoint *p;
242                         float size;
243                         
244                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
245                         
246                         glEnable(GL_BLEND);
247                         
248                         for (p = t->tsnap.points.first; p; p = p->next) {
249                                 if (p == t->tsnap.selectedPoint) {
250                                         glColor4ubv(selectedCol);
251                                 }
252                                 else {
253                                         glColor4ubv(col);
254                                 }
255                                 
256                                 ED_node_draw_snap(&ar->v2d, p->co, size, 0);
257                         }
258                         
259                         if (t->tsnap.status & POINT_INIT) {
260                                 glColor4ubv(activeCol);
261                                 
262                                 ED_node_draw_snap(&ar->v2d, t->tsnap.snapPoint, size, t->tsnap.snapNodeBorder);
263                         }
264                         
265                         glDisable(GL_BLEND);
266                 }
267         }
268 }
269
270 bool handleSnapping(TransInfo *t, const wmEvent *event)
271 {
272         bool status = false;
273
274 #if 0 // XXX need a proper selector for all snap mode
275         if (BIF_snappingSupported(t->obedit) && event->type == TABKEY && event->shift) {
276                 /* toggle snap and reinit */
277                 t->settings->snap_flag ^= SCE_SNAP;
278                 initSnapping(t, NULL);
279                 status = 1;
280         }
281 #endif
282         if (event->type == MOUSEMOVE) {
283                 status |= updateSelectedSnapPoint(t);
284         }
285         
286         return status;
287 }
288
289 void applyProject(TransInfo *t)
290 {
291         /* XXX FLICKER IN OBJECT MODE */
292         if ((t->tsnap.project) && activeSnap(t) && (t->flag & T_NO_PROJECT) == 0 && (t->con.mode & CON_APPLY) == 0) {
293                 TransData *td = t->data;
294                 float tvec[3];
295                 float imat[4][4];
296                 int i;
297         
298                 if (t->flag & (T_EDIT | T_POSE)) {
299                         Object *ob = t->obedit ? t->obedit : t->poseobj;
300                         invert_m4_m4(imat, ob->obmat);
301                 }
302
303                 for (i = 0; i < t->total; i++, td++) {
304                         float iloc[3], loc[3], no[3];
305                         float mval_fl[2];
306                         float dist_px = TRANSFORM_DIST_MAX_PX;
307                         
308                         if (td->flag & TD_NOACTION)
309                                 break;
310                         
311                         if (td->flag & TD_SKIP)
312                                 continue;
313
314                         if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
315                                 continue;
316                         
317                         copy_v3_v3(iloc, td->loc);
318                         if (t->flag & (T_EDIT | T_POSE)) {
319                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
320                                 mul_m4_v3(ob->obmat, iloc);
321                         }
322                         else if (t->flag & T_OBJECT) {
323                                 td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
324                                 BKE_object_handle_update(t->scene, td->ob);
325                                 copy_v3_v3(iloc, td->ob->obmat[3]);
326                         }
327                         
328                         if (ED_view3d_project_float_global(t->ar, iloc, mval_fl, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
329                                 if (snapObjectsTransform(t, mval_fl, &dist_px, loc, no, t->tsnap.modeSelect)) {
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                         }
341                         
342                         //XXX constraintTransLim(t, td);
343                 }
344         }
345 }
346
347 void applySnapping(TransInfo *t, float *vec)
348 {
349         /* project is not applied this way */
350         if (t->tsnap.project)
351                 return;
352         
353         if (t->tsnap.status & SNAP_FORCED) {
354                 t->tsnap.targetSnap(t);
355         
356                 t->tsnap.applySnap(t, vec);
357         }
358         else if ((t->tsnap.mode != SCE_SNAP_MODE_INCREMENT) && activeSnap(t)) {
359                 double current = PIL_check_seconds_timer();
360                 
361                 // Time base quirky code to go around findnearest slowness
362                 /* !TODO! add exception for object mode, no need to slow it down then */
363                 if (current - t->tsnap.last >= 0.01) {
364                         t->tsnap.calcSnap(t, vec);
365                         t->tsnap.targetSnap(t);
366         
367                         t->tsnap.last = current;
368                 }
369                 if (validSnap(t)) {
370                         t->tsnap.applySnap(t, vec);
371                 }
372         }
373 }
374
375 void resetSnapping(TransInfo *t)
376 {
377         t->tsnap.status = 0;
378         t->tsnap.align = false;
379         t->tsnap.project = 0;
380         t->tsnap.mode = 0;
381         t->tsnap.modeSelect = 0;
382         t->tsnap.target = 0;
383         t->tsnap.last = 0;
384         t->tsnap.applySnap = NULL;
385
386         t->tsnap.snapNormal[0] = 0;
387         t->tsnap.snapNormal[1] = 0;
388         t->tsnap.snapNormal[2] = 0;
389         
390         t->tsnap.snapNodeBorder = 0;
391 }
392
393 bool usingSnappingNormal(TransInfo *t)
394 {
395         return t->tsnap.align;
396 }
397
398 bool validSnappingNormal(TransInfo *t)
399 {
400         if (validSnap(t)) {
401                 if (dot_v3v3(t->tsnap.snapNormal, t->tsnap.snapNormal) > 0) {
402                         return true;
403                 }
404         }
405         
406         return false;
407 }
408
409 static void initSnappingMode(TransInfo *t)
410 {
411         ToolSettings *ts = t->settings;
412         Object *obedit = t->obedit;
413         Scene *scene = t->scene;
414         Base *base_act = scene->basact;
415
416         if (t->spacetype == SPACE_NODE) {
417                 /* force project off when not supported */
418                 t->tsnap.project = 0;
419                 
420                 t->tsnap.mode = ts->snap_node_mode;
421         }
422         else if (t->spacetype == SPACE_IMAGE) {
423                 /* force project off when not supported */
424                 t->tsnap.project = 0;
425                 
426                 t->tsnap.mode = ts->snap_uv_mode;
427         }
428         else {
429                 /* force project off when not supported */
430                 if (ts->snap_mode != SCE_SNAP_MODE_FACE)
431                         t->tsnap.project = 0;
432                 
433                 t->tsnap.mode = ts->snap_mode;
434         }
435
436         if ((t->spacetype == SPACE_VIEW3D || t->spacetype == SPACE_IMAGE) &&  /* Only 3D view or UV */
437             (t->flag & T_CAMERA) == 0)  /* Not with camera selected in camera view */
438         {
439                 setSnappingCallback(t);
440
441                 /* Edit mode */
442                 if (t->tsnap.applySnap != NULL && // A snapping function actually exist
443                     (obedit != NULL && ELEM4(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE)) ) // Temporary limited to edit mode meshes, armature, curves
444                 {
445                         /* Exclude editmesh if using proportional edit */
446                         if ((obedit->type == OB_MESH) && (t->flag & T_PROP_EDIT)) {
447                                 t->tsnap.modeSelect = SNAP_NOT_OBEDIT;
448                         }
449                         else {
450                                 t->tsnap.modeSelect = t->tsnap.snap_self ? SNAP_ALL : SNAP_NOT_OBEDIT;
451                         }
452                 }
453                 /* Particles edit mode*/
454                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
455                          (obedit == NULL && base_act && base_act->object && base_act->object->mode & OB_MODE_PARTICLE_EDIT))
456                 {
457                         t->tsnap.modeSelect = SNAP_ALL;
458                 }
459                 /* Object mode */
460                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
461                          (obedit == NULL) ) // Object Mode
462                 {
463                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
464                 }
465                 else {
466                         /* Grid if snap is not possible */
467                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
468                 }
469         }
470         else if (t->spacetype == SPACE_NODE) {
471                 setSnappingCallback(t);
472                 
473                 if (t->tsnap.applySnap != NULL) {
474                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
475                 }
476                 else {
477                         /* Grid if snap is not possible */
478                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
479                 }
480         }
481         else {
482                 /* Always grid outside of 3D view */
483                 t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
484         }
485 }
486
487 void initSnapping(TransInfo *t, wmOperator *op)
488 {
489         ToolSettings *ts = t->settings;
490         short snap_target = t->settings->snap_target;
491         
492         resetSnapping(t);
493         
494         /* if snap property exists */
495         if (op && RNA_struct_find_property(op->ptr, "snap") && RNA_struct_property_is_set(op->ptr, "snap")) {
496                 if (RNA_boolean_get(op->ptr, "snap")) {
497                         t->modifiers |= MOD_SNAP;
498
499                         if (RNA_struct_property_is_set(op->ptr, "snap_target")) {
500                                 snap_target = RNA_enum_get(op->ptr, "snap_target");
501                         }
502                         
503                         if (RNA_struct_property_is_set(op->ptr, "snap_point")) {
504                                 RNA_float_get_array(op->ptr, "snap_point", t->tsnap.snapPoint);
505                                 t->tsnap.status |= SNAP_FORCED | POINT_INIT;
506                         }
507                         
508                         /* snap align only defined in specific cases */
509                         if (RNA_struct_find_property(op->ptr, "snap_align")) {
510                                 t->tsnap.align = RNA_boolean_get(op->ptr, "snap_align");
511                                 RNA_float_get_array(op->ptr, "snap_normal", t->tsnap.snapNormal);
512                                 normalize_v3(t->tsnap.snapNormal);
513                         }
514
515                         if (RNA_struct_find_property(op->ptr, "use_snap_project")) {
516                                 t->tsnap.project = RNA_boolean_get(op->ptr, "use_snap_project");
517                         }
518
519                         if (RNA_struct_find_property(op->ptr, "use_snap_self")) {
520                                 t->tsnap.snap_self = RNA_boolean_get(op->ptr, "use_snap_self");
521                         }
522                 }
523         }
524         /* use scene defaults only when transform is modal */
525         else if (t->flag & T_MODAL) {
526                 if (ELEM3(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE, SPACE_NODE)) {
527                         if (ts->snap_flag & SCE_SNAP) {
528                                 t->modifiers |= MOD_SNAP;
529                         }
530
531                         t->tsnap.align = ((t->settings->snap_flag & SCE_SNAP_ROTATE) == SCE_SNAP_ROTATE);
532                         t->tsnap.project = ((t->settings->snap_flag & SCE_SNAP_PROJECT) == SCE_SNAP_PROJECT);
533                         t->tsnap.snap_self = !((t->settings->snap_flag & SCE_SNAP_NO_SELF) == SCE_SNAP_NO_SELF);
534                         t->tsnap.peel = ((t->settings->snap_flag & SCE_SNAP_PROJECT) == SCE_SNAP_PROJECT);
535                 }
536         }
537         
538         t->tsnap.target = snap_target;
539
540         initSnappingMode(t);
541 }
542
543 static void setSnappingCallback(TransInfo *t)
544 {
545         t->tsnap.calcSnap = CalcSnapGeometry;
546
547         switch (t->tsnap.target) {
548                 case SCE_SNAP_TARGET_CLOSEST:
549                         t->tsnap.targetSnap = TargetSnapClosest;
550                         break;
551                 case SCE_SNAP_TARGET_CENTER:
552                         t->tsnap.targetSnap = TargetSnapCenter;
553                         break;
554                 case SCE_SNAP_TARGET_MEDIAN:
555                         t->tsnap.targetSnap = TargetSnapMedian;
556                         break;
557                 case SCE_SNAP_TARGET_ACTIVE:
558                         t->tsnap.targetSnap = TargetSnapActive;
559                         break;
560
561         }
562
563         switch (t->mode) {
564                 case TFM_TRANSLATION:
565                         t->tsnap.applySnap = ApplySnapTranslation;
566                         t->tsnap.distance = TranslationBetween;
567                         break;
568                 case TFM_ROTATION:
569                         t->tsnap.applySnap = ApplySnapRotation;
570                         t->tsnap.distance = RotationBetween;
571
572                         // Can't do TARGET_CENTER with rotation, use TARGET_MEDIAN instead
573                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
574                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
575                                 t->tsnap.targetSnap = TargetSnapMedian;
576                         }
577                         break;
578                 case TFM_RESIZE:
579                         t->tsnap.applySnap = ApplySnapResize;
580                         t->tsnap.distance = ResizeBetween;
581
582                         // Can't do TARGET_CENTER with resize, use TARGET_MEDIAN instead
583                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
584                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
585                                 t->tsnap.targetSnap = TargetSnapMedian;
586                         }
587                         break;
588                 default:
589                         t->tsnap.applySnap = NULL;
590                         break;
591         }
592 }
593
594 void addSnapPoint(TransInfo *t)
595 {
596         if (t->tsnap.status & POINT_INIT) {
597                 TransSnapPoint *p = MEM_callocN(sizeof(TransSnapPoint), "SnapPoint");
598
599                 t->tsnap.selectedPoint = p;
600
601                 copy_v3_v3(p->co, t->tsnap.snapPoint);
602
603                 BLI_addtail(&t->tsnap.points, p);
604
605                 t->tsnap.status |= MULTI_POINTS;
606         }
607 }
608
609 bool updateSelectedSnapPoint(TransInfo *t)
610 {
611         bool status = false;
612         if (t->tsnap.status & MULTI_POINTS) {
613                 TransSnapPoint *p, *closest_p = NULL;
614                 float closest_dist = TRANSFORM_SNAP_MAX_PX;
615                 const float mval_fl[2] = {t->mval[0], t->mval[1]};
616                 float screen_loc[2];
617
618                 for (p = t->tsnap.points.first; p; p = p->next) {
619                         float dist;
620
621                         if (ED_view3d_project_float_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
622                                 continue;
623                         }
624
625                         dist = len_squared_v2v2(mval_fl, screen_loc);
626
627                         if (dist < closest_dist) {
628                                 closest_p = p;
629                                 closest_dist = dist;
630                         }
631                 }
632
633                 if (closest_p) {
634                         status = (t->tsnap.selectedPoint != closest_p);
635                         t->tsnap.selectedPoint = closest_p;
636                 }
637         }
638
639         return status;
640 }
641
642 void removeSnapPoint(TransInfo *t)
643 {
644         if (t->tsnap.status & MULTI_POINTS) {
645                 updateSelectedSnapPoint(t);
646
647                 if (t->tsnap.selectedPoint) {
648                         BLI_freelinkN(&t->tsnap.points, t->tsnap.selectedPoint);
649
650                         if (t->tsnap.points.first == NULL) {
651                                 t->tsnap.status &= ~MULTI_POINTS;
652                         }
653
654                         t->tsnap.selectedPoint = NULL;
655                 }
656
657         }
658 }
659
660 void getSnapPoint(TransInfo *t, float vec[3])
661 {
662         if (t->tsnap.points.first) {
663                 TransSnapPoint *p;
664                 int total = 0;
665
666                 vec[0] = vec[1] = vec[2] = 0;
667
668                 for (p = t->tsnap.points.first; p; p = p->next, total++) {
669                         add_v3_v3(vec, p->co);
670                 }
671
672                 if (t->tsnap.status & POINT_INIT) {
673                         add_v3_v3(vec, t->tsnap.snapPoint);
674                         total++;
675                 }
676
677                 mul_v3_fl(vec, 1.0f / total);
678         }
679         else {
680                 copy_v3_v3(vec, t->tsnap.snapPoint);
681         }
682 }
683
684 /********************** APPLY **************************/
685
686 static void ApplySnapTranslation(TransInfo *t, float vec[3])
687 {
688         float point[3];
689         getSnapPoint(t, point);
690
691         if (t->spacetype == SPACE_NODE) {
692                 char border = t->tsnap.snapNodeBorder;
693                 if (border & (NODE_LEFT | NODE_RIGHT))
694                         vec[0] = point[0] - t->tsnap.snapTarget[0];
695                 if (border & (NODE_BOTTOM | NODE_TOP))
696                         vec[1] = point[1] - t->tsnap.snapTarget[1];
697         }
698         else {
699                 sub_v3_v3v3(vec, point, t->tsnap.snapTarget);
700         }
701 }
702
703 static void ApplySnapRotation(TransInfo *t, float *value)
704 {
705         if (t->tsnap.target == SCE_SNAP_TARGET_CLOSEST) {
706                 *value = t->tsnap.dist;
707         }
708         else {
709                 float point[3];
710                 getSnapPoint(t, point);
711                 *value = RotationBetween(t, t->tsnap.snapTarget, point);
712         }
713 }
714
715 static void ApplySnapResize(TransInfo *t, float vec[3])
716 {
717         if (t->tsnap.target == SCE_SNAP_TARGET_CLOSEST) {
718                 vec[0] = vec[1] = vec[2] = t->tsnap.dist;
719         }
720         else {
721                 float point[3];
722                 getSnapPoint(t, point);
723                 vec[0] = vec[1] = vec[2] = ResizeBetween(t, t->tsnap.snapTarget, point);
724         }
725 }
726
727 /********************** DISTANCE **************************/
728
729 static float TranslationBetween(TransInfo *UNUSED(t), float p1[3], float p2[3])
730 {
731         return len_v3v3(p1, p2);
732 }
733
734 static float RotationBetween(TransInfo *t, float p1[3], float p2[3])
735 {
736         float angle, start[3], end[3], center[3];
737         
738         copy_v3_v3(center, t->center);
739         if (t->flag & (T_EDIT | T_POSE)) {
740                 Object *ob = t->obedit ? t->obedit : t->poseobj;
741                 mul_m4_v3(ob->obmat, center);
742         }
743
744         sub_v3_v3v3(start, p1, center);
745         sub_v3_v3v3(end, p2, center);
746                 
747         // Angle around a constraint axis (error prone, will need debug)
748         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
749                 float axis[3], tmp[3];
750                 
751                 t->con.applyRot(t, NULL, axis, NULL);
752
753                 project_v3_v3v3(tmp, end, axis);
754                 sub_v3_v3v3(end, end, tmp);
755                 
756                 project_v3_v3v3(tmp, start, axis);
757                 sub_v3_v3v3(start, start, tmp);
758                 
759                 normalize_v3(end);
760                 normalize_v3(start);
761                 
762                 cross_v3_v3v3(tmp, start, end);
763                 
764                 if (dot_v3v3(tmp, axis) < 0.0f)
765                         angle = -acos(dot_v3v3(start, end));
766                 else
767                         angle = acos(dot_v3v3(start, end));
768         }
769         else {
770                 float mtx[3][3];
771                 
772                 copy_m3_m4(mtx, t->viewmat);
773
774                 mul_m3_v3(mtx, end);
775                 mul_m3_v3(mtx, start);
776                 
777                 angle = atan2(start[1], start[0]) - atan2(end[1], end[0]);
778         }
779         
780         if (angle > (float)M_PI) {
781                 angle = angle - 2 * (float)M_PI;
782         }
783         else if (angle < -((float)M_PI)) {
784                 angle = 2.0f * (float)M_PI + angle;
785         }
786         
787         return angle;
788 }
789
790 static float ResizeBetween(TransInfo *t, float p1[3], float p2[3])
791 {
792         float d1[3], d2[3], center[3], len_d1;
793         
794         copy_v3_v3(center, t->center);
795         if (t->flag & (T_EDIT | T_POSE)) {
796                 Object *ob = t->obedit ? t->obedit : t->poseobj;
797                 mul_m4_v3(ob->obmat, center);
798         }
799
800         sub_v3_v3v3(d1, p1, center);
801         sub_v3_v3v3(d2, p2, center);
802         
803         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
804                 mul_m3_v3(t->con.pmtx, d1);
805                 mul_m3_v3(t->con.pmtx, d2);
806         }
807         
808         len_d1 = len_v3(d1);
809
810         return len_d1 != 0.0f ? len_v3(d2) / len_d1 : 1;
811 }
812
813 /********************** CALC **************************/
814
815 static void UNUSED_FUNCTION(CalcSnapGrid) (TransInfo *t, float *UNUSED(vec))
816 {
817         snapGridAction(t, t->tsnap.snapPoint, BIG_GEARS);
818 }
819
820 static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
821 {
822         if (t->spacetype == SPACE_VIEW3D) {
823                 float loc[3];
824                 float no[3];
825                 float mval[2];
826                 bool found = false;
827                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
828                 
829                 mval[0] = t->mval[0];
830                 mval[1] = t->mval[1];
831                 
832                 if (t->tsnap.mode == SCE_SNAP_MODE_VOLUME) {
833                         ListBase depth_peels;
834                         DepthPeel *p1, *p2;
835                         float *last_p = NULL;
836                         float max_dist = FLT_MAX;
837                         float p[3] = {0.0f, 0.0f, 0.0f};
838                         
839                         depth_peels.first = depth_peels.last = NULL;
840                         
841                         peelObjectsTransForm(t, &depth_peels, mval, t->tsnap.modeSelect);
842                         
843 //                      if (LAST_SNAP_POINT_VALID)
844 //                      {
845 //                              last_p = LAST_SNAP_POINT;
846 //                      }
847 //                      else
848 //                      {
849                                 last_p = t->tsnap.snapPoint;
850 //                      }
851                         
852                         
853                         for (p1 = depth_peels.first; p1; p1 = p1->next) {
854                                 if (p1->flag == 0) {
855                                         float vec[3];
856                                         float new_dist;
857                                         
858                                         p2 = NULL;
859                                         p1->flag = 1;
860                 
861                                         /* if peeling objects, take the first and last from each object */
862                                         if (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) {
863                                                 DepthPeel *peel;
864                                                 for (peel = p1->next; peel; peel = peel->next) {
865                                                         if (peel->ob == p1->ob) {
866                                                                 peel->flag = 1;
867                                                                 p2 = peel;
868                                                         }
869                                                 }
870                                         }
871                                         /* otherwise, pair first with second and so on */
872                                         else {
873                                                 for (p2 = p1->next; p2 && p2->ob != p1->ob; p2 = p2->next) {
874                                                         /* nothing to do here */
875                                                 }
876                                         }
877                                         
878                                         if (p2) {
879                                                 p2->flag = 1;
880                                                 
881                                                 add_v3_v3v3(vec, p1->p, p2->p);
882                                                 mul_v3_fl(vec, 0.5f);
883                                         }
884                                         else {
885                                                 copy_v3_v3(vec, p1->p);
886                                         }
887
888                                         if (last_p == NULL) {
889                                                 copy_v3_v3(p, vec);
890                                                 max_dist = 0;
891                                                 break;
892                                         }
893                                         
894                                         new_dist = len_v3v3(last_p, vec);
895                                         
896                                         if (new_dist < max_dist) {
897                                                 copy_v3_v3(p, vec);
898                                                 max_dist = new_dist;
899                                         }
900                                 }
901                         }
902                         
903                         if (max_dist != FLT_MAX) {
904                                 copy_v3_v3(loc, p);
905                                 /* XXX, is there a correct normal in this case ???, for now just z up */
906                                 no[0] = 0.0;
907                                 no[1] = 0.0;
908                                 no[2] = 1.0;
909                                 found = true;
910                         }
911                         
912                         BLI_freelistN(&depth_peels);
913                 }
914                 else {
915                         found = snapObjectsTransform(t, mval, &dist_px, loc, no, t->tsnap.modeSelect);
916                 }
917                 
918                 if (found == true) {
919                         float tangent[3];
920                         
921                         sub_v3_v3v3(tangent, loc, t->tsnap.snapPoint);
922                         tangent[2] = 0; 
923                         
924                         if (dot_v3v3(tangent, tangent) > 0) {
925                                 copy_v3_v3(t->tsnap.snapTangent, tangent);
926                         }
927                         
928                         copy_v3_v3(t->tsnap.snapPoint, loc);
929                         copy_v3_v3(t->tsnap.snapNormal, no);
930
931                         t->tsnap.status |=  POINT_INIT;
932                 }
933                 else {
934                         t->tsnap.status &= ~POINT_INIT;
935                 }
936         }
937         else if (t->spacetype == SPACE_IMAGE && t->obedit != NULL && t->obedit->type == OB_MESH) {
938                 /* same as above but for UV's */
939                 Image *ima = ED_space_image(t->sa->spacedata.first);
940                 float aspx, aspy, co[2];
941                 
942                 UI_view2d_region_to_view(&t->ar->v2d, t->mval[0], t->mval[1], co, co + 1);
943
944                 if (ED_uvedit_nearest_uv(t->scene, t->obedit, ima, co, t->tsnap.snapPoint)) {
945                         ED_space_image_get_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
946                         t->tsnap.snapPoint[0] *= aspx;
947                         t->tsnap.snapPoint[1] *= aspy;
948
949                         t->tsnap.status |=  POINT_INIT;
950                 }
951                 else {
952                         t->tsnap.status &= ~POINT_INIT;
953                 }
954         }
955         else if (t->spacetype == SPACE_NODE) {
956                 float loc[2];
957                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
958                 char node_border;
959                 
960                 if (snapNodesTransform(t, t->mval, &dist_px, loc, &node_border, t->tsnap.modeSelect)) {
961                         copy_v2_v2(t->tsnap.snapPoint, loc);
962                         t->tsnap.snapNodeBorder = node_border;
963                         
964                         t->tsnap.status |=  POINT_INIT;
965                 }
966                 else {
967                         t->tsnap.status &= ~POINT_INIT;
968                 }
969         }
970 }
971
972 /********************** TARGET **************************/
973
974 static void TargetSnapOffset(TransInfo *t, TransData *td)
975 {
976         if (t->spacetype == SPACE_NODE && td != NULL) {
977                 bNode *node = td->extra;
978                 char border = t->tsnap.snapNodeBorder;
979                 float width  = BLI_rctf_size_x(&node->totr);
980                 float height = BLI_rctf_size_y(&node->totr);
981                 
982                 if (border & NODE_LEFT)
983                         t->tsnap.snapTarget[0] -= 0.5f * width;
984                 if (border & NODE_RIGHT)
985                         t->tsnap.snapTarget[0] += 0.5f * width;
986                 if (border & NODE_BOTTOM)
987                         t->tsnap.snapTarget[1] -= 0.5f * height;
988                 if (border & NODE_TOP)
989                         t->tsnap.snapTarget[1] += 0.5f * height;
990         }
991 }
992
993 static void TargetSnapCenter(TransInfo *t)
994 {
995         /* Only need to calculate once */
996         if ((t->tsnap.status & TARGET_INIT) == 0) {
997                 copy_v3_v3(t->tsnap.snapTarget, t->center);
998                 
999                 if (t->flag & (T_EDIT | T_POSE)) {
1000                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1001                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1002                 }
1003                 
1004                 TargetSnapOffset(t, NULL);
1005                 
1006                 t->tsnap.status |= TARGET_INIT;
1007         }
1008 }
1009
1010 static void TargetSnapActive(TransInfo *t)
1011 {
1012         /* Only need to calculate once */
1013         if ((t->tsnap.status & TARGET_INIT) == 0) {
1014                 TransData *td = NULL;
1015                 TransData *active_td = NULL;
1016                 int i;
1017
1018                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1019                         if (td->flag & TD_ACTIVE) {
1020                                 active_td = td;
1021                                 break;
1022                         }
1023                 }
1024
1025                 if (active_td) {
1026                         copy_v3_v3(t->tsnap.snapTarget, active_td->center);
1027                         
1028                         if (t->flag & (T_EDIT | T_POSE)) {
1029                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
1030                                 mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1031                         }
1032                         
1033                         TargetSnapOffset(t, active_td);
1034                         
1035                         t->tsnap.status |= TARGET_INIT;
1036                 }
1037                 /* No active, default to median */
1038                 else {
1039                         t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
1040                         t->tsnap.targetSnap = TargetSnapMedian;
1041                         TargetSnapMedian(t);
1042                 }
1043         }
1044 }
1045
1046 static void TargetSnapMedian(TransInfo *t)
1047 {
1048         // Only need to calculate once
1049         if ((t->tsnap.status & TARGET_INIT) == 0) {
1050                 TransData *td = NULL;
1051                 int i;
1052
1053                 t->tsnap.snapTarget[0] = 0;
1054                 t->tsnap.snapTarget[1] = 0;
1055                 t->tsnap.snapTarget[2] = 0;
1056                 
1057                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1058                         add_v3_v3(t->tsnap.snapTarget, td->center);
1059                 }
1060                 
1061                 mul_v3_fl(t->tsnap.snapTarget, 1.0 / i);
1062                 
1063                 if (t->flag & (T_EDIT | T_POSE)) {
1064                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1065                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1066                 }
1067                 
1068                 TargetSnapOffset(t, NULL);
1069                 
1070                 t->tsnap.status |= TARGET_INIT;
1071         }
1072 }
1073
1074 static void TargetSnapClosest(TransInfo *t)
1075 {
1076         // Only valid if a snap point has been selected
1077         if (t->tsnap.status & POINT_INIT) {
1078                 TransData *closest = NULL, *td = NULL;
1079                 
1080                 /* Object mode */
1081                 if (t->flag & T_OBJECT) {
1082                         int i;
1083                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1084                                 struct BoundBox *bb = BKE_object_boundbox_get(td->ob);
1085                                 
1086                                 /* use boundbox if possible */
1087                                 if (bb) {
1088                                         int j;
1089                                         
1090                                         for (j = 0; j < 8; j++) {
1091                                                 float loc[3];
1092                                                 float dist;
1093                                                 
1094                                                 copy_v3_v3(loc, bb->vec[j]);
1095                                                 mul_m4_v3(td->ext->obmat, loc);
1096                                                 
1097                                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1098                                                 
1099                                                 if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1100                                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1101                                                         closest = td;
1102                                                         t->tsnap.dist = dist; 
1103                                                 }
1104                                         }
1105                                 }
1106                                 /* use element center otherwise */
1107                                 else {
1108                                         float loc[3];
1109                                         float dist;
1110                                         
1111                                         copy_v3_v3(loc, td->center);
1112                                         
1113                                         dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1114                                         
1115                                         if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1116                                                 copy_v3_v3(t->tsnap.snapTarget, loc);
1117                                                 closest = td;
1118                                                 t->tsnap.dist = dist; 
1119                                         }
1120                                 }
1121                         }
1122                 }
1123                 else {
1124                         int i;
1125                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1126                                 float loc[3];
1127                                 float dist;
1128                                 
1129                                 copy_v3_v3(loc, td->center);
1130                                 
1131                                 if (t->flag & (T_EDIT | T_POSE)) {
1132                                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1133                                         mul_m4_v3(ob->obmat, loc);
1134                                 }
1135                                 
1136                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1137                                 
1138                                 if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1139                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1140                                         closest = td;
1141                                         t->tsnap.dist = dist; 
1142                                 }
1143                         }
1144                 }
1145                 
1146                 TargetSnapOffset(t, closest);
1147                 
1148                 t->tsnap.status |= TARGET_INIT;
1149         }
1150 }
1151
1152 static bool snapEdge(ARegion *ar, const float v1co[3], const short v1no[3], const float v2co[3], const short v2no[3], float obmat[4][4], float timat[3][3],
1153                      const float ray_start[3], const float ray_start_local[3], const float ray_normal_local[3], const float mval_fl[2],
1154                      float r_loc[3], float r_no[3], float *r_dist_px, float *r_depth)
1155 {
1156         float intersect[3] = {0, 0, 0}, ray_end[3], dvec[3];
1157         int result;
1158         bool retval = false;
1159         
1160         copy_v3_v3(ray_end, ray_normal_local);
1161         mul_v3_fl(ray_end, 2000);
1162         add_v3_v3v3(ray_end, ray_start_local, ray_end);
1163         
1164         result = isect_line_line_v3(v1co, v2co, ray_start_local, ray_end, intersect, dvec); /* dvec used but we don't care about result */
1165         
1166         if (result) {
1167                 float edge_loc[3], vec[3];
1168                 float mul;
1169         
1170                 /* check for behind ray_start */
1171                 sub_v3_v3v3(dvec, intersect, ray_start_local);
1172                 
1173                 sub_v3_v3v3(edge_loc, v1co, v2co);
1174                 sub_v3_v3v3(vec, intersect, v2co);
1175                 
1176                 mul = dot_v3v3(vec, edge_loc) / dot_v3v3(edge_loc, edge_loc);
1177                 
1178                 if (mul > 1) {
1179                         mul = 1;
1180                         copy_v3_v3(intersect, v1co);
1181                 }
1182                 else if (mul < 0) {
1183                         mul = 0;
1184                         copy_v3_v3(intersect, v2co);
1185                 }
1186
1187                 if (dot_v3v3(ray_normal_local, dvec) > 0) {
1188                         float location[3];
1189                         float new_depth;
1190                         float screen_loc[2];
1191                         float new_dist;
1192                         
1193                         copy_v3_v3(location, intersect);
1194                         
1195                         mul_m4_v3(obmat, location);
1196                         
1197                         new_depth = len_v3v3(location, ray_start);
1198                         
1199                         if (ED_view3d_project_float_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1200                                 new_dist = len_manhattan_v2v2(mval_fl, screen_loc);
1201                         }
1202                         else {
1203                                 new_dist = TRANSFORM_DIST_MAX_PX;
1204                         }
1205                         
1206                         /* 10% threshold if edge is closer but a bit further
1207                          * this takes care of series of connected edges a bit slanted w.r.t the viewport
1208                          * otherwise, it would stick to the verts of the closest edge and not slide along merrily 
1209                          * */
1210                         if (new_dist <= *r_dist_px && new_depth < *r_depth * 1.001f) {
1211                                 float n1[3], n2[3];
1212                                 
1213                                 *r_depth = new_depth;
1214                                 retval = true;
1215                                 
1216                                 sub_v3_v3v3(edge_loc, v1co, v2co);
1217                                 sub_v3_v3v3(vec, intersect, v2co);
1218                                 
1219                                 mul = dot_v3v3(vec, edge_loc) / dot_v3v3(edge_loc, edge_loc);
1220                                 
1221                                 if (r_no) {
1222                                         normal_short_to_float_v3(n1, v1no);
1223                                         normal_short_to_float_v3(n2, v2no);
1224                                         interp_v3_v3v3(r_no, n2, n1, mul);
1225                                         mul_m3_v3(timat, r_no);
1226                                         normalize_v3(r_no);
1227                                 }
1228
1229                                 copy_v3_v3(r_loc, location);
1230                                 
1231                                 *r_dist_px = new_dist;
1232                         }
1233                 }
1234         }
1235         
1236         return retval;
1237 }
1238
1239 static bool snapVertex(ARegion *ar, const float vco[3], const short vno[3], float obmat[4][4], float timat[3][3],
1240                        const float ray_start[3], const float ray_start_local[3], const float ray_normal_local[3], const float mval_fl[2],
1241                        float r_loc[3], float r_no[3], float *r_dist_px, float *r_depth)
1242 {
1243         bool retval = false;
1244         float dvec[3];
1245         
1246         sub_v3_v3v3(dvec, vco, ray_start_local);
1247         
1248         if (dot_v3v3(ray_normal_local, dvec) > 0) {
1249                 float location[3];
1250                 float new_depth;
1251                 float screen_loc[2];
1252                 float new_dist;
1253                 
1254                 copy_v3_v3(location, vco);
1255                 
1256                 mul_m4_v3(obmat, location);
1257                 
1258                 new_depth = len_v3v3(location, ray_start);
1259                 
1260                 if (ED_view3d_project_float_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1261                         new_dist = len_manhattan_v2v2(mval_fl, screen_loc);
1262                 }
1263                 else {
1264                         new_dist = TRANSFORM_DIST_MAX_PX;
1265                 }
1266
1267                 
1268                 if (new_dist <= *r_dist_px && new_depth < *r_depth) {
1269                         *r_depth = new_depth;
1270                         retval = true;
1271                         
1272                         copy_v3_v3(r_loc, location);
1273                         
1274                         if (r_no) {
1275                                 normal_short_to_float_v3(r_no, vno);
1276                                 mul_m3_v3(timat, r_no);
1277                                 normalize_v3(r_no);
1278                         }
1279
1280                         *r_dist_px = new_dist;
1281                 }
1282         }
1283         
1284         return retval;
1285 }
1286
1287 static bool snapArmature(short snap_mode, ARegion *ar, Object *ob, bArmature *arm, float obmat[4][4],
1288                          const float ray_start[3], const float ray_normal[3], const float mval[2],
1289                          float r_loc[3], float *UNUSED(r_no), float *r_dist_px, float *r_depth)
1290 {
1291         float imat[4][4];
1292         float ray_start_local[3], ray_normal_local[3];
1293         bool retval = false;
1294
1295         invert_m4_m4(imat, obmat);
1296
1297         copy_v3_v3(ray_start_local, ray_start);
1298         copy_v3_v3(ray_normal_local, ray_normal);
1299         
1300         mul_m4_v3(imat, ray_start_local);
1301         mul_mat3_m4_v3(imat, ray_normal_local);
1302
1303         if (arm->edbo) {
1304                 EditBone *eBone;
1305
1306                 for (eBone = arm->edbo->first; eBone; eBone = eBone->next) {
1307                         if (eBone->layer & arm->layer) {
1308                                 /* skip hidden or moving (selected) bones */
1309                                 if ((eBone->flag & (BONE_HIDDEN_A | BONE_ROOTSEL | BONE_TIPSEL)) == 0) {
1310                                         switch (snap_mode) {
1311                                                 case SCE_SNAP_MODE_VERTEX:
1312                                                         retval |= snapVertex(ar, eBone->head, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1313                                                         retval |= snapVertex(ar, eBone->tail, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1314                                                         break;
1315                                                 case SCE_SNAP_MODE_EDGE:
1316                                                         retval |= snapEdge(ar, eBone->head, NULL, eBone->tail, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1317                                                         break;
1318                                         }
1319                                 }
1320                         }
1321                 }
1322         }
1323         else if (ob->pose && ob->pose->chanbase.first) {
1324                 bPoseChannel *pchan;
1325                 Bone *bone;
1326                 
1327                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1328                         bone = pchan->bone;
1329                         /* skip hidden bones */
1330                         if (bone && !(bone->flag & (BONE_HIDDEN_P | BONE_HIDDEN_PG))) {
1331                                 float *head_vec = pchan->pose_head;
1332                                 float *tail_vec = pchan->pose_tail;
1333                                 
1334                                 switch (snap_mode) {
1335                                         case SCE_SNAP_MODE_VERTEX:
1336                                                 retval |= snapVertex(ar, head_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1337                                                 retval |= snapVertex(ar, tail_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1338                                                 break;
1339                                         case SCE_SNAP_MODE_EDGE:
1340                                                 retval |= snapEdge(ar, head_vec, NULL, tail_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1341                                                 break;
1342                                 }
1343                         }
1344                 }
1345         }
1346
1347         return retval;
1348 }
1349
1350 static bool snapDerivedMesh(short snap_mode, ARegion *ar, Object *ob, DerivedMesh *dm, BMEditMesh *em, float obmat[4][4],
1351                             const float ray_start[3], const float ray_normal[3], const float mval[2],
1352                             float r_loc[3], float r_no[3], float *r_dist_px, float *r_depth)
1353 {
1354         bool retval = false;
1355         int totvert = dm->getNumVerts(dm);
1356         int totface = dm->getNumTessFaces(dm);
1357
1358         if (totvert > 0) {
1359                 float imat[4][4];
1360                 float timat[3][3]; /* transpose inverse matrix for normals */
1361                 float ray_start_local[3], ray_normal_local[3];
1362                 int test = 1;
1363
1364                 invert_m4_m4(imat, obmat);
1365
1366                 copy_m3_m4(timat, imat);
1367                 transpose_m3(timat);
1368                 
1369                 copy_v3_v3(ray_start_local, ray_start);
1370                 copy_v3_v3(ray_normal_local, ray_normal);
1371                 
1372                 mul_m4_v3(imat, ray_start_local);
1373                 mul_mat3_m4_v3(imat, ray_normal_local);
1374                 
1375                 
1376                 /* If number of vert is more than an arbitrary limit, 
1377                  * test against boundbox first
1378                  * */
1379                 if (totface > 16) {
1380                         struct BoundBox *bb = BKE_object_boundbox_get(ob);
1381                         test = BKE_boundbox_ray_hit_check(bb, ray_start_local, ray_normal_local);
1382                 }
1383                 
1384                 if (test == 1) {
1385                         
1386                         switch (snap_mode) {
1387                                 case SCE_SNAP_MODE_FACE:
1388                                 {
1389                                         BVHTreeRayHit hit;
1390                                         BVHTreeFromMesh treeData;
1391
1392                                         /* local scale in normal direction */
1393                                         float local_scale = len_v3(ray_normal_local);
1394
1395                                         treeData.em_evil = em;
1396                                         bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6);
1397
1398                                         hit.index = -1;
1399                                         hit.dist = *r_depth * (*r_depth == TRANSFORM_DIST_MAX_RAY ? 1.0f : local_scale);
1400
1401                                         if (treeData.tree && BLI_bvhtree_ray_cast(treeData.tree, ray_start_local, ray_normal_local, 0.0f, &hit, treeData.raycast_callback, &treeData) != -1) {
1402                                                 if (hit.dist / local_scale <= *r_depth) {
1403                                                         *r_depth = hit.dist / local_scale;
1404                                                         copy_v3_v3(r_loc, hit.co);
1405                                                         copy_v3_v3(r_no, hit.no);
1406
1407                                                         /* back to worldspace */
1408                                                         mul_m4_v3(obmat, r_loc);
1409                                                         copy_v3_v3(r_no, hit.no);
1410
1411                                                         mul_m3_v3(timat, r_no);
1412                                                         normalize_v3(r_no);
1413
1414                                                         retval |= 1;
1415                                                 }
1416                                         }
1417                                         break;
1418                                 }
1419                                 case SCE_SNAP_MODE_VERTEX:
1420                                 {
1421                                         MVert *verts = dm->getVertArray(dm);
1422                                         int *index_array = NULL;
1423                                         int index = 0;
1424                                         int i;
1425                                         
1426                                         if (em != NULL) {
1427                                                 index_array = dm->getVertDataArray(dm, CD_ORIGINDEX);
1428                                                 EDBM_index_arrays_ensure(em, BM_VERT);
1429                                         }
1430                                         
1431                                         for (i = 0; i < totvert; i++) {
1432                                                 BMVert *eve = NULL;
1433                                                 MVert *v = verts + i;
1434                                                 
1435                                                 test = 1; /* reset for every vert */
1436                                         
1437                                                 if (em != NULL) {
1438                                                         if (index_array) {
1439                                                                 index = index_array[i];
1440                                                         }
1441                                                         else {
1442                                                                 index = i;
1443                                                         }
1444                                                         
1445                                                         if (index == ORIGINDEX_NONE) {
1446                                                                 test = 0;
1447                                                         }
1448                                                         else {
1449                                                                 eve = EDBM_vert_at_index(em, index);
1450                                                                 
1451                                                                 if ((BM_elem_flag_test(eve, BM_ELEM_HIDDEN) ||
1452                                                                      BM_elem_flag_test(eve, BM_ELEM_SELECT)))
1453                                                                 {
1454                                                                         test = 0;
1455                                                                 }
1456                                                         }
1457                                                 }
1458                                                 
1459                                                 
1460                                                 if (test) {
1461                                                         retval |= snapVertex(ar, v->co, v->no, obmat, timat, ray_start, ray_start_local, ray_normal_local, mval, r_loc, r_no, r_dist_px, r_depth);
1462                                                 }
1463                                         }
1464
1465                                         break;
1466                                 }
1467                                 case SCE_SNAP_MODE_EDGE:
1468                                 {
1469                                         MVert *verts = dm->getVertArray(dm);
1470                                         MEdge *edges = dm->getEdgeArray(dm);
1471                                         int totedge = dm->getNumEdges(dm);
1472                                         int *index_array = NULL;
1473                                         int index = 0;
1474                                         int i;
1475                                         
1476                                         if (em != NULL) {
1477                                                 index_array = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1478                                                 EDBM_index_arrays_ensure(em, BM_EDGE);
1479                                         }
1480                                         
1481                                         for (i = 0; i < totedge; i++) {
1482                                                 MEdge *e = edges + i;
1483                                                 
1484                                                 test = 1; /* reset for every vert */
1485                                         
1486                                                 if (em != NULL) {
1487                                                         if (index_array) {
1488                                                                 index = index_array[i];
1489                                                         }
1490                                                         else {
1491                                                                 index = i;
1492                                                         }
1493                                                         
1494                                                         if (index == ORIGINDEX_NONE) {
1495                                                                 test = 0;
1496                                                         }
1497                                                         else {
1498                                                                 BMEdge *eed = EDBM_edge_at_index(em, index);
1499
1500                                                                 if ((BM_elem_flag_test(eed, BM_ELEM_HIDDEN) ||
1501                                                                      BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) ||
1502                                                                      BM_elem_flag_test(eed->v2, BM_ELEM_SELECT)))
1503                                                                 {
1504                                                                         test = 0;
1505                                                                 }
1506                                                         }
1507                                                 }
1508
1509                                                 if (test) {
1510                                                         retval |= snapEdge(ar, verts[e->v1].co, verts[e->v1].no, verts[e->v2].co, verts[e->v2].no, obmat, timat, ray_start, ray_start_local, ray_normal_local, mval, r_loc, r_no, r_dist_px, r_depth);
1511                                                 }
1512                                         }
1513
1514                                         break;
1515                                 }
1516                         }
1517                 }
1518         }
1519
1520         return retval;
1521
1522
1523 /* may extend later (for now just snaps to empty center) */
1524 static bool snapEmpty(short snap_mode, ARegion *ar, Object *ob, float obmat[4][4],
1525                       const float ray_start[3], const float ray_normal[3], const float mval[2],
1526                       float r_loc[3], float *UNUSED(r_no), float *r_dist_px, float *r_depth)
1527 {
1528         float imat[4][4];
1529         float ray_start_local[3], ray_normal_local[3];
1530         bool retval = false;
1531
1532         if (ob->transflag & OB_DUPLI) {
1533                 return retval;
1534         }
1535         /* for now only vertex supported */
1536         if (snap_mode != SCE_SNAP_MODE_VERTEX) {
1537                 return retval;
1538         }
1539
1540         invert_m4_m4(imat, obmat);
1541
1542         copy_v3_v3(ray_start_local, ray_start);
1543         copy_v3_v3(ray_normal_local, ray_normal);
1544
1545         mul_m4_v3(imat, ray_start_local);
1546         mul_mat3_m4_v3(imat, ray_normal_local);
1547
1548         switch (snap_mode) {
1549                 case SCE_SNAP_MODE_VERTEX:
1550                 {
1551                         const float zero_co[3] = {0.0f};
1552                         retval |= snapVertex(ar, zero_co, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist_px, r_depth);
1553                         break;
1554                 }
1555                 default:
1556                         break;
1557         }
1558
1559         return retval;
1560 }
1561
1562 static bool snapCamera(short snap_mode, ARegion *ar, Scene *scene, Object *object, float obmat[4][4],
1563                        const float ray_start[3], const float ray_normal[3], const float mval[2],
1564                        float r_loc[3], float *UNUSED(r_no), float *r_dist_px, float *r_depth)
1565 {
1566         float orig_camera_mat[4][4], orig_camera_imat[4][4], imat[4][4];
1567         bool retval = false;
1568         MovieClip *clip = BKE_object_movieclip_get(scene, object, false);
1569         MovieTracking *tracking;
1570         float ray_start_local[3], ray_normal_local[3];
1571
1572         if (clip == NULL) {
1573                 return retval;
1574         }
1575         if (object->transflag & OB_DUPLI) {
1576                 return retval;
1577         }
1578
1579         tracking = &clip->tracking;
1580
1581         BKE_tracking_get_camera_object_matrix(scene, object, orig_camera_mat);
1582
1583         invert_m4_m4(orig_camera_imat, orig_camera_mat);
1584         invert_m4_m4(imat, obmat);
1585
1586         switch (snap_mode) {
1587                 case SCE_SNAP_MODE_VERTEX:
1588                 {
1589                         MovieTrackingObject *tracking_object;
1590
1591                         for (tracking_object = tracking->objects.first;
1592                              tracking_object;
1593                              tracking_object = tracking_object->next)
1594                         {
1595                                 ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
1596                                 MovieTrackingTrack *track;
1597                                 float reconstructed_camera_mat[4][4],
1598                                       reconstructed_camera_imat[4][4];
1599                                 float (*vertex_obmat)[4];
1600
1601                                 copy_v3_v3(ray_start_local, ray_start);
1602                                 copy_v3_v3(ray_normal_local, ray_normal);
1603
1604                                 if ((tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0) {
1605                                         BKE_tracking_camera_get_reconstructed_interpolate(tracking, tracking_object,
1606                                                                                           CFRA, reconstructed_camera_mat);
1607
1608                                         invert_m4_m4(reconstructed_camera_imat, reconstructed_camera_mat);
1609                                 }
1610
1611                                 for (track = tracksbase->first; track; track = track->next) {
1612                                         float bundle_pos[3];
1613
1614                                         if ((track->flag & TRACK_HAS_BUNDLE) == 0) {
1615                                                 continue;
1616                                         }
1617
1618                                         copy_v3_v3(bundle_pos, track->bundle_pos);
1619                                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1620                                                 mul_m4_v3(orig_camera_imat, ray_start_local);
1621                                                 mul_mat3_m4_v3(orig_camera_imat, ray_normal_local);
1622                                                 vertex_obmat = orig_camera_mat;
1623                                         }
1624                                         else {
1625                                                 mul_m4_v3(reconstructed_camera_imat, bundle_pos);
1626                                                 mul_m4_v3(imat, ray_start_local);
1627                                                 mul_mat3_m4_v3(imat, ray_normal_local);
1628                                                 vertex_obmat = obmat;
1629                                         }
1630
1631                                         retval |= snapVertex(ar, bundle_pos, NULL, vertex_obmat, NULL,
1632                                                              ray_start, ray_start_local, ray_normal_local, mval,
1633                                                              r_loc, NULL, r_dist_px, r_depth);
1634                                 }
1635                         }
1636
1637                         break;
1638                 }
1639                 default:
1640                         break;
1641         }
1642
1643         return retval;
1644 }
1645
1646 static bool snapObject(Scene *scene, short snap_mode, ARegion *ar, Object *ob, float obmat[4][4], bool use_obedit,
1647                        Object **r_ob, float r_obmat[4][4],
1648                        const float ray_start[3], const float ray_normal[3], const float mval[2],
1649                        float r_loc[3], float r_no[3], float *r_dist_px, float *r_depth)
1650 {
1651         bool retval = false;
1652         
1653         if (ob->type == OB_MESH) {
1654                 BMEditMesh *em;
1655                 DerivedMesh *dm;
1656                 
1657                 if (use_obedit) {
1658                         em = BKE_editmesh_from_object(ob);
1659                         dm = editbmesh_get_derived_cage(scene, ob, em, CD_MASK_BAREMESH);
1660                 }
1661                 else {
1662                         em = NULL;
1663                         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1664                 }
1665                 
1666                 retval = snapDerivedMesh(snap_mode, ar, ob, dm, em, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_depth);
1667
1668                 dm->release(dm);
1669         }
1670         else if (ob->type == OB_ARMATURE) {
1671                 retval = snapArmature(snap_mode, ar, ob, ob->data, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_depth);
1672         }
1673         else if (ob->type == OB_EMPTY) {
1674                 retval = snapEmpty(snap_mode, ar, ob, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_depth);
1675         }
1676         else if (ob->type == OB_CAMERA) {
1677                 retval = snapCamera(snap_mode, ar, scene, ob, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_depth);
1678         }
1679         
1680         if (retval) {
1681                 if (r_ob) {
1682                         *r_ob = ob;
1683                         copy_m4_m4(r_obmat, obmat);
1684                 }
1685         }
1686
1687         return retval;
1688 }
1689
1690 static bool snapObjectsRay(Scene *scene, short snap_mode, Base *base_act, View3D *v3d, ARegion *ar, Object *obedit,
1691                            Object **r_ob, float r_obmat[4][4],
1692                            const float ray_start[3], const float ray_normal[3], float *r_ray_dist,
1693                            const float mval[2], float *r_dist_px, float r_loc[3], float r_no[3], SnapMode mode)
1694 {
1695         Base *base;
1696         bool retval = false;
1697
1698         if (mode == SNAP_ALL && obedit) {
1699                 Object *ob = obedit;
1700
1701                 retval |= snapObject(scene, snap_mode, ar, ob, ob->obmat, true,
1702                                      r_ob, r_obmat,
1703                                      ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_ray_dist);
1704         }
1705
1706         /* Need an exception for particle edit because the base is flagged with BA_HAS_RECALC_DATA
1707          * which makes the loop skip it, even the derived mesh will never change
1708          *
1709          * To solve that problem, we do it first as an exception. 
1710          * */
1711         base = base_act;
1712         if (base && base->object && base->object->mode & OB_MODE_PARTICLE_EDIT) {
1713                 Object *ob = base->object;
1714                 retval |= snapObject(scene, snap_mode, ar, ob, ob->obmat, false,
1715                                      r_ob, r_obmat,
1716                                      ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_ray_dist);
1717         }
1718
1719         for (base = FIRSTBASE; base != NULL; base = base->next) {
1720                 if ((BASE_VISIBLE_BGMODE(v3d, scene, base)) &&
1721                     (base->flag & (BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA)) == 0 &&
1722
1723                     ((mode == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL)) == 0) ||
1724                      (ELEM(mode, SNAP_ALL, SNAP_NOT_OBEDIT) && base != base_act)))
1725                 {
1726                         Object *ob = base->object;
1727                         
1728                         if (ob->transflag & OB_DUPLI) {
1729                                 DupliObject *dupli_ob;
1730                                 ListBase *lb = object_duplilist(scene, ob, FALSE);
1731                                 
1732                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
1733                                         retval |= snapObject(scene, snap_mode, ar, dupli_ob->ob, dupli_ob->mat, false,
1734                                                              r_ob, r_obmat,
1735                                                              ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_ray_dist);
1736                                 }
1737                                 
1738                                 free_object_duplilist(lb);
1739                         }
1740                         
1741                         retval |= snapObject(scene, snap_mode, ar, ob, ob->obmat, false,
1742                                              r_ob, r_obmat,
1743                                              ray_start, ray_normal, mval, r_loc, r_no, r_dist_px, r_ray_dist);
1744                 }
1745         }
1746         
1747         return retval;
1748 }
1749 static bool snapObjects(Scene *scene, short snap_mode, Base *base_act, View3D *v3d, ARegion *ar, Object *obedit,
1750                         const float mval[2], float *r_dist_px,
1751                         float r_loc[3], float r_no[3], float *r_ray_dist, SnapMode mode)
1752 {
1753         float ray_start[3], ray_normal[3];
1754
1755         if (ED_view3d_win_to_ray(ar, v3d, mval, ray_start, ray_normal, true) == false) {
1756                 return false;
1757         }
1758
1759         return snapObjectsRay(scene, snap_mode, base_act, v3d, ar, obedit,
1760                               NULL, NULL,
1761                               ray_start, ray_normal, r_ray_dist,
1762                               mval, r_dist_px, r_loc, r_no, mode);
1763 }
1764
1765 bool snapObjectsTransform(TransInfo *t, const float mval[2], float *r_dist_px, float r_loc[3], float r_no[3], SnapMode mode)
1766 {
1767         float ray_dist = TRANSFORM_DIST_MAX_RAY;
1768         return snapObjects(t->scene, t->scene->toolsettings->snap_mode, t->scene->basact, t->view, t->ar, t->obedit,
1769                            mval, r_dist_px, r_loc, r_no, &ray_dist, mode);
1770 }
1771
1772 bool snapObjectsContext(bContext *C, const float mval[2], float *r_dist_px, float r_loc[3], float r_no[3], SnapMode mode)
1773 {
1774         ScrArea *sa = CTX_wm_area(C);
1775         View3D *v3d = sa->spacedata.first;
1776         Scene *scene = CTX_data_scene(C);
1777         ARegion *ar = CTX_wm_region(C);
1778         Object *obedit = CTX_data_edit_object(C);
1779         float ray_dist = TRANSFORM_DIST_MAX_RAY;
1780
1781         return snapObjects(scene, scene->toolsettings->snap_mode, scene->basact, v3d, ar, obedit,
1782                            mval, r_dist_px, r_loc, r_no, &ray_dist, mode);
1783 }
1784
1785 bool snapObjectsEx(Scene *scene, Base *base_act, View3D *v3d, ARegion *ar, Object *obedit, short snap_mode,
1786                    const float mval[2], float *r_dist_px,
1787                    float r_loc[3], float r_no[3], float *r_ray_dist, SnapMode mode)
1788 {
1789         return snapObjects(scene, snap_mode, base_act, v3d, ar, obedit,
1790                            mval, r_dist_px,
1791                            r_loc, r_no, r_ray_dist, mode);
1792 }
1793 bool snapObjectsRayEx(Scene *scene, Base *base_act, View3D *v3d, ARegion *ar, Object *obedit, short snap_mode,
1794                       Object **r_ob, float r_obmat[4][4],
1795                       const float ray_start[3], const float ray_normal[3], float *r_ray_dist,
1796                       const float mval[2], float *r_dist_px, float r_loc[3], float r_no[3], SnapMode mode)
1797 {
1798         return snapObjectsRay(scene, snap_mode, base_act, v3d, ar, obedit,
1799                               r_ob, r_obmat,
1800                               ray_start, ray_normal, r_ray_dist,
1801                               mval, r_dist_px, r_loc, r_no, mode);
1802 }
1803
1804 /******************** PEELING *********************************/
1805
1806
1807 static int cmpPeel(void *arg1, void *arg2)
1808 {
1809         DepthPeel *p1 = arg1;
1810         DepthPeel *p2 = arg2;
1811         int val = 0;
1812         
1813         if (p1->depth < p2->depth) {
1814                 val = -1;
1815         }
1816         else if (p1->depth > p2->depth) {
1817                 val = 1;
1818         }
1819         
1820         return val;
1821 }
1822
1823 static void removeDoublesPeel(ListBase *depth_peels)
1824 {
1825         DepthPeel *peel;
1826         
1827         for (peel = depth_peels->first; peel; peel = peel->next) {
1828                 DepthPeel *next_peel = peel->next;
1829
1830                 if (next_peel && ABS(peel->depth - next_peel->depth) < 0.0015f) {
1831                         peel->next = next_peel->next;
1832                         
1833                         if (next_peel->next) {
1834                                 next_peel->next->prev = peel;
1835                         }
1836                         
1837                         MEM_freeN(next_peel);
1838                 }
1839         }
1840 }
1841
1842 static void addDepthPeel(ListBase *depth_peels, float depth, float p[3], float no[3], Object *ob)
1843 {
1844         DepthPeel *peel = MEM_callocN(sizeof(DepthPeel), "DepthPeel");
1845         
1846         peel->depth = depth;
1847         peel->ob = ob;
1848         copy_v3_v3(peel->p, p);
1849         copy_v3_v3(peel->no, no);
1850         
1851         BLI_addtail(depth_peels, peel);
1852         
1853         peel->flag = 0;
1854 }
1855
1856 static bool peelDerivedMesh(Object *ob, DerivedMesh *dm, float obmat[4][4],
1857                             const float ray_start[3], const float ray_normal[3], const float UNUSED(mval[2]),
1858                             ListBase *depth_peels)
1859 {
1860         bool retval = false;
1861         int totvert = dm->getNumVerts(dm);
1862         int totface = dm->getNumTessFaces(dm);
1863         
1864         if (totvert > 0) {
1865                 float imat[4][4];
1866                 float timat[3][3]; /* transpose inverse matrix for normals */
1867                 float ray_start_local[3], ray_normal_local[3];
1868                 int test = 1;
1869
1870                 invert_m4_m4(imat, obmat);
1871
1872                 copy_m3_m4(timat, imat);
1873                 transpose_m3(timat);
1874                 
1875                 copy_v3_v3(ray_start_local, ray_start);
1876                 copy_v3_v3(ray_normal_local, ray_normal);
1877                 
1878                 mul_m4_v3(imat, ray_start_local);
1879                 mul_mat3_m4_v3(imat, ray_normal_local);
1880                 
1881                 
1882                 /* If number of vert is more than an arbitrary limit, 
1883                  * test against boundbox first
1884                  * */
1885                 if (totface > 16) {
1886                         struct BoundBox *bb = BKE_object_boundbox_get(ob);
1887                         test = BKE_boundbox_ray_hit_check(bb, ray_start_local, ray_normal_local);
1888                 }
1889                 
1890                 if (test == 1) {
1891                         MVert *verts = dm->getVertArray(dm);
1892                         MFace *faces = dm->getTessFaceArray(dm);
1893                         int i;
1894                         
1895                         for (i = 0; i < totface; i++) {
1896                                 MFace *f = faces + i;
1897                                 float lambda;
1898                                 int result;
1899                                 
1900                                 
1901                                 result = isect_ray_tri_threshold_v3(ray_start_local, ray_normal_local, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, &lambda, NULL, 0.001);
1902                                 
1903                                 if (result) {
1904                                         float location[3], normal[3];
1905                                         float intersect[3];
1906                                         float new_depth;
1907                                         
1908                                         copy_v3_v3(intersect, ray_normal_local);
1909                                         mul_v3_fl(intersect, lambda);
1910                                         add_v3_v3(intersect, ray_start_local);
1911                                         
1912                                         copy_v3_v3(location, intersect);
1913                                         
1914                                         if (f->v4)
1915                                                 normal_quad_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, verts[f->v4].co);
1916                                         else
1917                                                 normal_tri_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co);
1918
1919                                         mul_m4_v3(obmat, location);
1920                                         
1921                                         new_depth = len_v3v3(location, ray_start);
1922                                         
1923                                         mul_m3_v3(timat, normal);
1924                                         normalize_v3(normal);
1925
1926                                         addDepthPeel(depth_peels, new_depth, location, normal, ob);
1927                                 }
1928                 
1929                                 if (f->v4 && result == 0) {
1930                                         result = isect_ray_tri_threshold_v3(ray_start_local, ray_normal_local, verts[f->v3].co, verts[f->v4].co, verts[f->v1].co, &lambda, NULL, 0.001);
1931                                         
1932                                         if (result) {
1933                                                 float location[3], normal[3];
1934                                                 float intersect[3];
1935                                                 float new_depth;
1936                                                 
1937                                                 copy_v3_v3(intersect, ray_normal_local);
1938                                                 mul_v3_fl(intersect, lambda);
1939                                                 add_v3_v3(intersect, ray_start_local);
1940                                                 
1941                                                 copy_v3_v3(location, intersect);
1942                                                 
1943                                                 if (f->v4)
1944                                                         normal_quad_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, verts[f->v4].co);
1945                                                 else
1946                                                         normal_tri_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co);
1947
1948                                                 mul_m4_v3(obmat, location);
1949                                                 
1950                                                 new_depth = len_v3v3(location, ray_start);
1951                                                 
1952                                                 mul_m3_v3(timat, normal);
1953                                                 normalize_v3(normal);
1954         
1955                                                 addDepthPeel(depth_peels, new_depth, location, normal, ob);
1956                                         }
1957                                 }
1958                         }
1959                 }
1960         }
1961
1962         return retval;
1963
1964
1965 static bool peelObjects(Scene *scene, View3D *v3d, ARegion *ar, Object *obedit,
1966                         ListBase *depth_peels, const float mval[2], SnapMode mode)
1967 {
1968         Base *base;
1969         bool retval = false;
1970         float ray_start[3], ray_normal[3];
1971         
1972         if (ED_view3d_win_to_ray(ar, v3d, mval, ray_start, ray_normal, true) == false) {
1973                 return false;
1974         }
1975
1976         for (base = scene->base.first; base != NULL; base = base->next) {
1977                 if (BASE_SELECTABLE(v3d, base)) {
1978                         Object *ob = base->object;
1979
1980                         if (ob->transflag & OB_DUPLI) {
1981                                 DupliObject *dupli_ob;
1982                                 ListBase *lb = object_duplilist(scene, ob, FALSE);
1983                                 
1984                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
1985                                         Object *dob = dupli_ob->ob;
1986                                         
1987                                         if (dob->type == OB_MESH) {
1988                                                 BMEditMesh *em;
1989                                                 DerivedMesh *dm = NULL;
1990                                                 bool val;
1991
1992                                                 if (dob != obedit) {
1993                                                         dm = mesh_get_derived_final(scene, dob, CD_MASK_BAREMESH);
1994                                                         
1995                                                         val = peelDerivedMesh(dob, dm, dob->obmat, ray_start, ray_normal, mval, depth_peels);
1996                                                 }
1997                                                 else {
1998                                                         em = BKE_editmesh_from_object(dob);
1999                                                         dm = editbmesh_get_derived_cage(scene, obedit, em, CD_MASK_BAREMESH);
2000                                                         
2001                                                         val = peelDerivedMesh(dob, dm, dob->obmat, ray_start, ray_normal, mval, depth_peels);
2002                                                 }
2003
2004                                                 retval = retval || val;
2005                                                 
2006                                                 dm->release(dm);
2007                                         }
2008                                 }
2009                                 
2010                                 free_object_duplilist(lb);
2011                         }
2012                         
2013                         if (ob->type == OB_MESH) {
2014                                 bool val = false;
2015
2016                                 if (ob != obedit && ((mode == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL)) == 0) || ELEM(mode, SNAP_ALL, SNAP_NOT_OBEDIT))) {
2017                                         DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
2018                                         
2019                                         val = peelDerivedMesh(ob, dm, ob->obmat, ray_start, ray_normal, mval, depth_peels);
2020                                         dm->release(dm);
2021                                 }
2022                                 else if (ob == obedit && mode != SNAP_NOT_OBEDIT) {
2023                                         BMEditMesh *em = BKE_editmesh_from_object(ob);
2024                                         DerivedMesh *dm = editbmesh_get_derived_cage(scene, obedit, em, CD_MASK_BAREMESH);
2025                                         
2026                                         val = peelDerivedMesh(ob, dm, ob->obmat, ray_start, ray_normal, mval, depth_peels);
2027                                         dm->release(dm);
2028                                 }
2029                                         
2030                                 retval = retval || val;
2031                                 
2032                         }
2033                 }
2034         }
2035         
2036         BLI_sortlist(depth_peels, cmpPeel);
2037         removeDoublesPeel(depth_peels);
2038         
2039         return retval;
2040 }
2041
2042 bool peelObjectsTransForm(TransInfo *t, ListBase *depth_peels, const float mval[2], SnapMode mode)
2043 {
2044         return peelObjects(t->scene, t->view, t->ar, t->obedit, depth_peels, mval, mode);
2045 }
2046
2047 bool peelObjectsContext(bContext *C, ListBase *depth_peels, const float mval[2], SnapMode mode)
2048 {
2049         Scene *scene = CTX_data_scene(C);
2050         ScrArea *sa = CTX_wm_area(C);
2051         View3D *v3d = sa->spacedata.first;
2052         ARegion *ar = CTX_wm_region(C);
2053         Object *obedit = CTX_data_edit_object(C);
2054
2055         return peelObjects(scene, v3d, ar, obedit, depth_peels, mval, mode);
2056 }
2057
2058 /******************** NODES ***********************************/
2059
2060 static bool snapNodeTest(View2D *v2d, bNode *node, SnapMode mode)
2061 {
2062         /* node is use for snapping only if a) snap mode matches and b) node is inside the view */
2063         return ((mode == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
2064                 (mode == SNAP_ALL && !(node->flag & NODE_ACTIVE))) &&
2065                 (node->totr.xmin < v2d->cur.xmax && node->totr.xmax > v2d->cur.xmin &&
2066                  node->totr.ymin < v2d->cur.ymax && node->totr.ymax > v2d->cur.ymin);
2067 }
2068
2069 static NodeBorder snapNodeBorder(int snap_node_mode)
2070 {
2071         switch (snap_node_mode) {
2072                 case SCE_SNAP_MODE_NODE_X:
2073                         return NODE_LEFT | NODE_RIGHT;
2074                 case SCE_SNAP_MODE_NODE_Y:
2075                         return NODE_TOP | NODE_BOTTOM;
2076                 case SCE_SNAP_MODE_NODE_XY:
2077                         return NODE_LEFT | NODE_RIGHT | NODE_TOP | NODE_BOTTOM;
2078         }
2079         return 0;
2080 }
2081
2082 static bool snapNode(ToolSettings *ts, SpaceNode *UNUSED(snode), ARegion *ar, bNode *node, const int mval[2],
2083                      float r_loc[2], float *r_dist_px, char *r_node_border)
2084 {
2085         View2D *v2d = &ar->v2d;
2086         NodeBorder border = snapNodeBorder(ts->snap_node_mode);
2087         bool retval = false;
2088         rcti totr;
2089         int new_dist;
2090         
2091         UI_view2d_to_region_no_clip(v2d, node->totr.xmin, node->totr.ymin, &totr.xmin, &totr.ymin);
2092         UI_view2d_to_region_no_clip(v2d, node->totr.xmax, node->totr.ymax, &totr.xmax, &totr.ymax);
2093         
2094         if (border & NODE_LEFT) {
2095                 new_dist = abs(totr.xmin - mval[0]);
2096                 if (new_dist < *r_dist_px) {
2097                         UI_view2d_region_to_view(v2d, totr.xmin, mval[1], &r_loc[0], &r_loc[1]);
2098                         *r_dist_px = new_dist;
2099                         *r_node_border = NODE_LEFT;
2100                         retval = true;
2101                 }
2102         }
2103         
2104         if (border & NODE_RIGHT) {
2105                 new_dist = abs(totr.xmax - mval[0]);
2106                 if (new_dist < *r_dist_px) {
2107                         UI_view2d_region_to_view(v2d, totr.xmax, mval[1], &r_loc[0], &r_loc[1]);
2108                         *r_dist_px = new_dist;
2109                         *r_node_border = NODE_RIGHT;
2110                         retval = true;
2111                 }
2112         }
2113         
2114         if (border & NODE_BOTTOM) {
2115                 new_dist = abs(totr.ymin - mval[1]);
2116                 if (new_dist < *r_dist_px) {
2117                         UI_view2d_region_to_view(v2d, mval[0], totr.ymin, &r_loc[0], &r_loc[1]);
2118                         *r_dist_px = new_dist;
2119                         *r_node_border = NODE_BOTTOM;
2120                         retval = true;
2121                 }
2122         }
2123         
2124         if (border & NODE_TOP) {
2125                 new_dist = abs(totr.ymax - mval[1]);
2126                 if (new_dist < *r_dist_px) {
2127                         UI_view2d_region_to_view(v2d, mval[0], totr.ymax, &r_loc[0], &r_loc[1]);
2128                         *r_dist_px = new_dist;
2129                         *r_node_border = NODE_TOP;
2130                         retval = true;
2131                 }
2132         }
2133         
2134         return retval;
2135 }
2136
2137 static bool snapNodes(ToolSettings *ts, SpaceNode *snode, ARegion *ar, const int mval[2],
2138                      float *r_dist_px, float r_loc[2], char *r_node_border, SnapMode mode)
2139 {
2140         bNodeTree *ntree = snode->edittree;
2141         bNode *node;
2142         bool retval = false;
2143         
2144         *r_node_border = 0;
2145         
2146         for (node = ntree->nodes.first; node; node = node->next) {
2147                 if (snapNodeTest(&ar->v2d, node, mode))
2148                         retval |= snapNode(ts, snode, ar, node, mval, r_loc, r_dist_px, r_node_border);
2149         }
2150         
2151         return retval;
2152 }
2153
2154 bool snapNodesTransform(TransInfo *t, const int mval[2], float *r_dist_px, float r_loc[2], char *r_node_border, SnapMode mode)
2155 {
2156         return snapNodes(t->settings, t->sa->spacedata.first, t->ar, mval, r_dist_px, r_loc, r_node_border, mode);
2157 }
2158
2159 bool snapNodesContext(bContext *C, const int mval[2], float *r_dist_px, float r_loc[2], char *r_node_border, SnapMode mode)
2160 {
2161         Scene *scene = CTX_data_scene(C);
2162         ARegion *ar = CTX_wm_region(C);
2163         return snapNodes(scene->toolsettings, CTX_wm_space_node(C), ar, mval, r_dist_px, r_loc, r_node_border, mode);
2164 }
2165
2166 /*================================================================*/
2167
2168 static void applyGrid(TransInfo *t, float *val, int max_index, float fac[3], GearsType action);
2169
2170
2171 void snapGridAction(TransInfo *t, float *val, GearsType action)
2172 {
2173         float fac[3];
2174
2175         fac[NO_GEARS]    = t->snap[0];
2176         fac[BIG_GEARS]   = t->snap[1];
2177         fac[SMALL_GEARS] = t->snap[2];
2178         
2179         applyGrid(t, val, t->idx_max, fac, action);
2180 }
2181
2182
2183 void snapGrid(TransInfo *t, float *val)
2184 {
2185         GearsType action;
2186
2187         // Only do something if using Snap to Grid
2188         if (t->tsnap.mode != SCE_SNAP_MODE_INCREMENT)
2189                 return;
2190
2191         action = activeSnap(t) ? BIG_GEARS : NO_GEARS;
2192
2193         if (action == BIG_GEARS && (t->modifiers & MOD_PRECISION)) {
2194                 action = SMALL_GEARS;
2195         }
2196
2197         snapGridAction(t, val, action);
2198 }
2199
2200
2201 static void applyGrid(TransInfo *t, float *val, int max_index, float fac[3], GearsType action)
2202 {
2203         int i;
2204         float asp[3] = {1.0f, 1.0f, 1.0f}; // TODO: Remove hard coded limit here (3)
2205
2206         if (max_index > 2) {
2207                 printf("applyGrid: invalid index %d, clamping\n", max_index);
2208                 max_index = 2;
2209         }
2210
2211         // Early bailing out if no need to snap
2212         if (fac[action] == 0.0f)
2213                 return;
2214         
2215         /* evil hack - snapping needs to be adapted for image aspect ratio */
2216         if ((t->spacetype == SPACE_IMAGE) && (t->mode == TFM_TRANSLATION)) {
2217                 if (t->options & CTX_MASK) {
2218                         ED_space_image_get_aspect(t->sa->spacedata.first, asp, asp + 1);
2219                 }
2220                 else {
2221                         ED_space_image_get_uv_aspect(t->sa->spacedata.first, asp, asp + 1);
2222                 }
2223         }
2224
2225         for (i = 0; i <= max_index; i++) {
2226                 val[i] = fac[action] * asp[i] * (float)floor(val[i] / (fac[action] * asp[i]) + 0.5f);
2227         }
2228 }