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