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