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