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