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