[#20700] Transformation Increments
[blender.git] / source / blender / editors / transform / transform.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): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <math.h>
34 #include <float.h>
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "DNA_anim_types.h"
49 #include "DNA_armature_types.h"
50 #include "DNA_action_types.h"  /* for some special action-editor settings */
51 #include "DNA_constraint_types.h"
52 #include "DNA_ipo_types.h"              /* some silly ipo flag  */
53 #include "DNA_listBase.h"
54 #include "DNA_meshdata_types.h"
55 #include "DNA_mesh_types.h"
56 #include "DNA_object_types.h"
57 #include "DNA_scene_types.h"            /* PET modes                    */
58 #include "DNA_screen_types.h"   /* area dimensions              */
59 #include "DNA_texture_types.h"
60 #include "DNA_userdef_types.h"
61 #include "DNA_view3d_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_windowmanager_types.h"
64
65 #include "RNA_access.h"
66
67 //#include "BIF_editview.h"             /* arrows_move_cursor   */
68 #include "BIF_gl.h"
69 #include "BIF_glutil.h"
70 //#include "BIF_mywindow.h"
71 //#include "BIF_resources.h"
72 //#include "BIF_screen.h"
73 //#include "BIF_space.h"                        /* undo                                 */
74 //#include "BIF_toets.h"                        /* persptoetsen                 */
75 //#include "BIF_mywindow.h"             /* warp_pointer                 */
76 //#include "BIF_toolbox.h"                      /* notice                               */
77 //#include "BIF_editmesh.h"
78 //#include "BIF_editsima.h"
79 //#include "BIF_editparticle.h"
80
81 #include "BKE_action.h"
82 #include "BKE_nla.h"
83 //#include "BKE_bad_level_calls.h"/* popmenu and error  */
84 #include "BKE_bmesh.h"
85 #include "BKE_context.h"
86 #include "BKE_constraint.h"
87 #include "BKE_global.h"
88 #include "BKE_particle.h"
89 #include "BKE_pointcache.h"
90 #include "BKE_utildefines.h"
91 #include "BKE_context.h"
92 #include "BKE_unit.h"
93
94 //#include "BSE_view.h"
95
96 #include "ED_image.h"
97 #include "ED_keyframing.h"
98 #include "ED_screen.h"
99 #include "ED_space_api.h"
100 #include "ED_markers.h"
101 #include "ED_util.h"
102 #include "ED_view3d.h"
103 #include "ED_mesh.h"
104
105 #include "UI_view2d.h"
106 #include "WM_types.h"
107 #include "WM_api.h"
108
109 #include "BLI_math.h"
110 #include "BLI_blenlib.h"
111 #include "BLI_editVert.h"
112 #include "BLI_ghash.h"
113 #include "BLI_linklist.h"
114
115 #include "PIL_time.h"                   /* sleep                                */
116
117 #include "UI_resources.h"
118
119 //#include "blendef.h"
120 //
121 //#include "mydevice.h"
122
123 #include "transform.h"
124
125 /* ************************** SPACE DEPENDANT CODE **************************** */
126
127 void setTransformViewMatrices(TransInfo *t)
128 {
129         if(t->spacetype==SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
130                 RegionView3D *rv3d = t->ar->regiondata;
131
132                 copy_m4_m4(t->viewmat, rv3d->viewmat);
133                 copy_m4_m4(t->viewinv, rv3d->viewinv);
134                 copy_m4_m4(t->persmat, rv3d->persmat);
135                 copy_m4_m4(t->persinv, rv3d->persinv);
136                 t->persp = rv3d->persp;
137         }
138         else {
139                 unit_m4(t->viewmat);
140                 unit_m4(t->viewinv);
141                 unit_m4(t->persmat);
142                 unit_m4(t->persinv);
143                 t->persp = RV3D_ORTHO;
144         }
145
146         calculateCenter2D(t);
147 }
148
149 void convertViewVec(TransInfo *t, float *vec, short dx, short dy)
150 {
151         if (t->spacetype==SPACE_VIEW3D) {
152                 if (t->ar->regiontype == RGN_TYPE_WINDOW)
153                 {
154                         window_to_3d_delta(t->ar, vec, dx, dy);
155                 }
156         }
157         else if(t->spacetype==SPACE_IMAGE) {
158                 View2D *v2d = t->view;
159                 float divx, divy, aspx, aspy;
160
161                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
162
163                 divx= v2d->mask.xmax-v2d->mask.xmin;
164                 divy= v2d->mask.ymax-v2d->mask.ymin;
165
166                 vec[0]= aspx*(v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
167                 vec[1]= aspy*(v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
168                 vec[2]= 0.0f;
169         }
170         else if(ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)) {
171                 View2D *v2d = t->view;
172                 float divx, divy;
173
174                 divx= v2d->mask.xmax-v2d->mask.xmin;
175                 divy= v2d->mask.ymax-v2d->mask.ymin;
176
177                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx) / (divx);
178                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy) / (divy);
179                 vec[2]= 0.0f;
180         }
181         else if(t->spacetype==SPACE_NODE) {
182                 View2D *v2d = &t->ar->v2d;
183                 float divx, divy;
184
185                 divx= v2d->mask.xmax-v2d->mask.xmin;
186                 divy= v2d->mask.ymax-v2d->mask.ymin;
187
188                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
189                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
190                 vec[2]= 0.0f;
191         }
192         else if(t->spacetype==SPACE_SEQ) {
193                 View2D *v2d = &t->ar->v2d;
194                 float divx, divy;
195
196                 divx= v2d->mask.xmax-v2d->mask.xmin;
197                 divy= v2d->mask.ymax-v2d->mask.ymin;
198
199                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
200                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
201                 vec[2]= 0.0f;
202         }
203 }
204
205 void projectIntView(TransInfo *t, float *vec, int *adr)
206 {
207         if (t->spacetype==SPACE_VIEW3D) {
208                 if(t->ar->regiontype == RGN_TYPE_WINDOW)
209                         project_int_noclip(t->ar, vec, adr);
210         }
211         else if(t->spacetype==SPACE_IMAGE) {
212                 float aspx, aspy, v[2];
213
214                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
215                 v[0]= vec[0]/aspx;
216                 v[1]= vec[1]/aspy;
217
218                 UI_view2d_to_region_no_clip(t->view, v[0], v[1], adr, adr+1);
219         }
220         else if(ELEM3(t->spacetype, SPACE_IPO, SPACE_NLA, SPACE_ACTION)) {
221                 int out[2] = {0, 0};
222
223                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1);
224                 adr[0]= out[0];
225                 adr[1]= out[1];
226         }
227         else if(t->spacetype==SPACE_SEQ) { /* XXX not tested yet, but should work */
228                 int out[2] = {0, 0};
229
230                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1);
231                 adr[0]= out[0];
232                 adr[1]= out[1];
233         }
234 }
235
236 void projectFloatView(TransInfo *t, float *vec, float *adr)
237 {
238         if (t->spacetype==SPACE_VIEW3D) {
239                 if(t->ar->regiontype == RGN_TYPE_WINDOW)
240                         project_float_noclip(t->ar, vec, adr);
241         }
242         else if(t->spacetype==SPACE_IMAGE) {
243                 int a[2];
244
245                 projectIntView(t, vec, a);
246                 adr[0]= a[0];
247                 adr[1]= a[1];
248         }
249         else if(ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)) {
250                 int a[2];
251
252                 projectIntView(t, vec, a);
253                 adr[0]= a[0];
254                 adr[1]= a[1];
255         }
256 }
257
258 void applyAspectRatio(TransInfo *t, float *vec)
259 {
260         SpaceImage *sima= t->sa->spacedata.first;
261
262         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
263                 float aspx, aspy;
264
265                 if((sima->flag & SI_COORDFLOATS)==0) {
266                         int width, height;
267                         ED_space_image_size(sima, &width, &height);
268
269                         vec[0] *= width;
270                         vec[1] *= height;
271                 }
272
273                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
274                 vec[0] /= aspx;
275                 vec[1] /= aspy;
276         }
277 }
278
279 void removeAspectRatio(TransInfo *t, float *vec)
280 {
281         SpaceImage *sima= t->sa->spacedata.first;
282
283         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
284                 float aspx, aspy;
285
286                 if((sima->flag & SI_COORDFLOATS)==0) {
287                         int width, height;
288                         ED_space_image_size(sima, &width, &height);
289
290                         vec[0] /= width;
291                         vec[1] /= height;
292                 }
293
294                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
295                 vec[0] *= aspx;
296                 vec[1] *= aspy;
297         }
298 }
299
300 static void viewRedrawForce(bContext *C, TransInfo *t)
301 {
302         if (t->spacetype == SPACE_VIEW3D)
303         {
304                 /* Do we need more refined tags? */
305                 WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, NULL);
306                 
307                 /* for realtime animation record - send notifiers recognised by animation editors */
308                 if ((t->animtimer) && IS_AUTOKEY_ON(t->scene))
309                         WM_event_add_notifier(C, NC_OBJECT|ND_KEYS, NULL);
310         }
311         else if (t->spacetype == SPACE_ACTION) {
312                 //SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
313                 WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME_EDIT, NULL);
314         }
315         else if (t->spacetype == SPACE_IPO) {
316                 //SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
317                 WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME_EDIT, NULL);
318         }
319         else if (t->spacetype == SPACE_NLA) {
320                 WM_event_add_notifier(C, NC_ANIMATION|ND_NLA_EDIT, NULL);
321         }
322         else if(t->spacetype == SPACE_NODE)
323         {
324                 //ED_area_tag_redraw(t->sa);
325                 WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE_VIEW, NULL);
326         }
327         else if(t->spacetype == SPACE_SEQ)
328         {
329                 WM_event_add_notifier(C, NC_SCENE|ND_SEQUENCER, NULL);
330         }
331         else if (t->spacetype==SPACE_IMAGE) {
332                 // XXX how to deal with lock?
333                 SpaceImage *sima= (SpaceImage*)t->sa->spacedata.first;
334                 if(sima->lock) WM_event_add_notifier(C, NC_GEOM|ND_DATA, t->obedit->data);
335                 else ED_area_tag_redraw(t->sa);
336         }
337 }
338
339 static void viewRedrawPost(TransInfo *t)
340 {
341         ED_area_headerprint(t->sa, NULL);
342
343 #if 0 // TRANSFORM_FIX_ME
344         if(t->spacetype==SPACE_VIEW3D) {
345                 allqueue(REDRAWBUTSOBJECT, 0);
346                 allqueue(REDRAWVIEW3D, 0);
347         }
348         else if(t->spacetype==SPACE_IMAGE) {
349                 allqueue(REDRAWIMAGE, 0);
350                 allqueue(REDRAWVIEW3D, 0);
351         }
352         else if(ELEM3(t->spacetype, SPACE_ACTION, SPACE_NLA, SPACE_IPO)) {
353                 allqueue(REDRAWVIEW3D, 0);
354                 allqueue(REDRAWACTION, 0);
355                 allqueue(REDRAWNLA, 0);
356                 allqueue(REDRAWIPO, 0);
357                 allqueue(REDRAWTIME, 0);
358                 allqueue(REDRAWBUTSOBJECT, 0);
359         }
360
361         scrarea_queue_headredraw(curarea);
362 #endif
363 }
364
365 /* ************************** TRANSFORMATIONS **************************** */
366
367 void BIF_selectOrientation() {
368 #if 0 // TRANSFORM_FIX_ME
369         short val;
370         char *str_menu = BIF_menustringTransformOrientation("Orientation");
371         val= pupmenu(str_menu);
372         MEM_freeN(str_menu);
373
374         if(val >= 0) {
375                 G.vd->twmode = val;
376         }
377 #endif
378 }
379
380 static void view_editmove(unsigned short event)
381 {
382 #if 0 // TRANSFORM_FIX_ME
383         int refresh = 0;
384         /* Regular:   Zoom in */
385         /* Shift:     Scroll up */
386         /* Ctrl:      Scroll right */
387         /* Alt-Shift: Rotate up */
388         /* Alt-Ctrl:  Rotate right */
389
390         /* only work in 3D window for now
391          * In the end, will have to send to event to a 2D window handler instead
392          */
393         if (Trans.flag & T_2D_EDIT)
394                 return;
395
396         switch(event) {
397                 case WHEELUPMOUSE:
398
399                         if( G.qual & LR_SHIFTKEY ) {
400                                 if( G.qual & LR_ALTKEY ) {
401                                         G.qual &= ~LR_SHIFTKEY;
402                                         persptoetsen(PAD2);
403                                         G.qual |= LR_SHIFTKEY;
404                                 } else {
405                                         persptoetsen(PAD2);
406                                 }
407                         } else if( G.qual & LR_CTRLKEY ) {
408                                 if( G.qual & LR_ALTKEY ) {
409                                         G.qual &= ~LR_CTRLKEY;
410                                         persptoetsen(PAD4);
411                                         G.qual |= LR_CTRLKEY;
412                                 } else {
413                                         persptoetsen(PAD4);
414                                 }
415                         } else if(U.uiflag & USER_WHEELZOOMDIR)
416                                 persptoetsen(PADMINUS);
417                         else
418                                 persptoetsen(PADPLUSKEY);
419
420                         refresh = 1;
421                         break;
422                 case WHEELDOWNMOUSE:
423                         if( G.qual & LR_SHIFTKEY ) {
424                                 if( G.qual & LR_ALTKEY ) {
425                                         G.qual &= ~LR_SHIFTKEY;
426                                         persptoetsen(PAD8);
427                                         G.qual |= LR_SHIFTKEY;
428                                 } else {
429                                         persptoetsen(PAD8);
430                                 }
431                         } else if( G.qual & LR_CTRLKEY ) {
432                                 if( G.qual & LR_ALTKEY ) {
433                                         G.qual &= ~LR_CTRLKEY;
434                                         persptoetsen(PAD6);
435                                         G.qual |= LR_CTRLKEY;
436                                 } else {
437                                         persptoetsen(PAD6);
438                                 }
439                         } else if(U.uiflag & USER_WHEELZOOMDIR)
440                                 persptoetsen(PADPLUSKEY);
441                         else
442                                 persptoetsen(PADMINUS);
443
444                         refresh = 1;
445                         break;
446         }
447
448         if (refresh)
449                 setTransformViewMatrices(&Trans);
450 #endif
451 }
452
453 /* ************************************************* */
454
455 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
456 #define TFM_MODAL_CANCEL                1
457 #define TFM_MODAL_CONFIRM               2
458 #define TFM_MODAL_TRANSLATE             3
459 #define TFM_MODAL_ROTATE                4
460 #define TFM_MODAL_RESIZE                5
461 #define TFM_MODAL_SNAP_INV_ON   6
462 #define TFM_MODAL_SNAP_INV_OFF  7
463 #define TFM_MODAL_SNAP_TOGGLE   8
464 #define TFM_MODAL_AXIS_X                9
465 #define TFM_MODAL_AXIS_Y                10
466 #define TFM_MODAL_AXIS_Z                11
467 #define TFM_MODAL_PLANE_X               12
468 #define TFM_MODAL_PLANE_Y               13
469 #define TFM_MODAL_PLANE_Z               14
470 #define TFM_MODAL_CONS_OFF              15
471 #define TFM_MODAL_ADD_SNAP              16
472 #define TFM_MODAL_REMOVE_SNAP   17
473
474 /* called in transform_ops.c, on each regeneration of keymaps */
475 wmKeyMap* transform_modal_keymap(wmKeyConfig *keyconf)
476 {
477         static EnumPropertyItem modal_items[] = {
478         {TFM_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
479         {TFM_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
480         {TFM_MODAL_TRANSLATE, "TRANSLATE", 0, "Translate", ""},
481         {TFM_MODAL_ROTATE, "ROTATE", 0, "Rotate", ""},
482         {TFM_MODAL_RESIZE, "RESIZE", 0, "Resize", ""},
483         {TFM_MODAL_SNAP_INV_ON, "SNAP_INV_ON", 0, "Invert Snap On", ""},
484         {TFM_MODAL_SNAP_INV_OFF, "SNAP_INV_OFF", 0, "Invert Snap Off", ""},
485         {TFM_MODAL_SNAP_TOGGLE, "SNAP_TOGGLE", 0, "Snap Toggle", ""},
486         {TFM_MODAL_AXIS_X, "AXIS_X", 0, "Orientation X axis", ""},
487         {TFM_MODAL_AXIS_Y, "AXIS_Y", 0, "Orientation Y axis", ""},
488         {TFM_MODAL_AXIS_Z, "AXIS_Z", 0, "Orientation Z axis", ""},
489         {TFM_MODAL_PLANE_X, "PLANE_X", 0, "Orientation X plane", ""},
490         {TFM_MODAL_PLANE_Y, "PLANE_Y", 0, "Orientation Y plane", ""},
491         {TFM_MODAL_PLANE_Z, "PLANE_Z", 0, "Orientation Z plane", ""},
492         {TFM_MODAL_CONS_OFF, "CONS_OFF", 0, "Remove Constraints", ""},
493         {TFM_MODAL_ADD_SNAP, "ADD_SNAP", 0, "Add Snap Point", ""},
494         {TFM_MODAL_REMOVE_SNAP, "REMOVE_SNAP", 0, "Remove Last Snap Point", ""},
495         {0, NULL, 0, NULL, NULL}};
496         
497         wmKeyMap *keymap= WM_modalkeymap_get(keyconf, "Transform Modal Map");
498         
499         /* this function is called for each spacetype, only needs to add map once */
500         if(keymap) return NULL;
501         
502         keymap= WM_modalkeymap_add(keyconf, "Transform Modal Map", modal_items);
503         
504         /* items for modal map */
505         WM_modalkeymap_add_item(keymap, ESCKEY,    KM_PRESS, KM_ANY, 0, TFM_MODAL_CANCEL);
506         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM);
507         WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM);
508         WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, TFM_MODAL_CONFIRM);
509
510         WM_modalkeymap_add_item(keymap, GKEY, KM_PRESS, 0, 0, TFM_MODAL_TRANSLATE);
511         WM_modalkeymap_add_item(keymap, RKEY, KM_PRESS, 0, 0, TFM_MODAL_ROTATE);
512         WM_modalkeymap_add_item(keymap, SKEY, KM_PRESS, 0, 0, TFM_MODAL_RESIZE);
513         
514         WM_modalkeymap_add_item(keymap, TABKEY, KM_PRESS, KM_SHIFT, 0, TFM_MODAL_SNAP_TOGGLE);
515
516         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, TFM_MODAL_SNAP_INV_ON);
517         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, TFM_MODAL_SNAP_INV_OFF);
518         
519         WM_modalkeymap_add_item(keymap, AKEY, KM_PRESS, 0, 0, TFM_MODAL_ADD_SNAP);
520         WM_modalkeymap_add_item(keymap, AKEY, KM_PRESS, KM_ALT, 0, TFM_MODAL_REMOVE_SNAP);
521
522         return keymap;
523 }
524
525
526 int transformEvent(TransInfo *t, wmEvent *event)
527 {
528         float mati[3][3] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}};
529         char cmode = constraintModeToChar(t);
530         int handled = 1;
531
532         t->redraw |= handleMouseInput(t, &t->mouse, event);
533
534         if (event->type == MOUSEMOVE)
535         {
536                 if (t->modifiers & MOD_CONSTRAINT_SELECT)
537                         t->con.mode |= CON_SELECT;
538
539                 t->mval[0] = event->x - t->ar->winrct.xmin;
540                 t->mval[1] = event->y - t->ar->winrct.ymin;
541
542                 t->redraw = 1;
543
544                 if (t->state == TRANS_STARTING) {
545                     t->state = TRANS_RUNNING;
546                 }
547
548                 applyMouseInput(t, &t->mouse, t->mval, t->values);
549         }
550
551         /* handle modal keymap first */
552         if (event->type == EVT_MODAL_MAP) {
553                 switch (event->val) {
554                         case TFM_MODAL_CANCEL:
555                                 t->state = TRANS_CANCEL;
556                                 break;
557                         case TFM_MODAL_CONFIRM:
558                                 t->state = TRANS_CONFIRM;
559                                 break;
560                         case TFM_MODAL_TRANSLATE:
561                                 /* only switch when... */
562                                 if( ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL) ) {
563                                         resetTransRestrictions(t);
564                                         restoreTransObjects(t);
565                                         initTranslation(t);
566                                         initSnapping(t, NULL); // need to reinit after mode change
567                                         t->redraw = 1;
568                                 }
569                                 break;
570                         case TFM_MODAL_ROTATE:
571                                 /* only switch when... */
572                                 if( ELEM4(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL, TFM_TRANSLATION) ) {
573                                         
574                                         resetTransRestrictions(t);
575                                         
576                                         if (t->mode == TFM_ROTATION) {
577                                                 restoreTransObjects(t);
578                                                 initTrackball(t);
579                                         }
580                                         else {
581                                                 restoreTransObjects(t);
582                                                 initRotation(t);
583                                         }
584                                         initSnapping(t, NULL); // need to reinit after mode change
585                                         t->redraw = 1;
586                                 }
587                                 break;
588                         case TFM_MODAL_RESIZE:
589                                 /* only switch when... */
590                                 if( ELEM3(t->mode, TFM_ROTATION, TFM_TRANSLATION, TFM_TRACKBALL) ) {
591                                         resetTransRestrictions(t);
592                                         restoreTransObjects(t);
593                                         initResize(t);
594                                         initSnapping(t, NULL); // need to reinit after mode change
595                                         t->redraw = 1;
596                                 }
597                                 break;
598                                 
599                         case TFM_MODAL_SNAP_INV_ON:
600                                 t->modifiers |= MOD_SNAP_INVERT;
601                                 t->redraw = 1;
602                                 break;
603                         case TFM_MODAL_SNAP_INV_OFF:
604                                 t->modifiers &= ~MOD_SNAP_INVERT;
605                                 t->redraw = 1;
606                                 break;
607                         case TFM_MODAL_SNAP_TOGGLE:
608                                 t->modifiers ^= MOD_SNAP;
609                                 t->redraw = 1;
610                                 break;
611                         case TFM_MODAL_AXIS_X:
612                                 if ((t->flag & T_NO_CONSTRAINT)==0) {
613                                         if (cmode == 'X') {
614                                                 stopConstraint(t);
615                                         }
616                                         else {
617                                                 if (t->flag & T_2D_EDIT) {
618                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0), "along X");
619                                                 }
620                                                 else {
621                                                         setUserConstraint(t, t->current_orientation, (CON_AXIS0), "along %s X");
622                                                 }
623                                         }
624                                         t->redraw = 1;
625                                 }
626                                 break;
627                         case TFM_MODAL_AXIS_Y:
628                                 if ((t->flag & T_NO_CONSTRAINT)==0) {
629                                         if (cmode == 'Y') {
630                                                 stopConstraint(t);
631                                         }
632                                         else {
633                                                 if (t->flag & T_2D_EDIT) {
634                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS1), "along Y");
635                                                 }
636                                                 else {
637                                                         setUserConstraint(t, t->current_orientation, (CON_AXIS1), "along %s Y");
638                                                 }
639                                         }
640                                         t->redraw = 1;
641                                 }
642                                 break;
643                         case TFM_MODAL_AXIS_Z:
644                                 if ((t->flag & (T_NO_CONSTRAINT|T_2D_EDIT))== 0) {
645                                         if (cmode == 'Z') {
646                                                 stopConstraint(t);
647                                         }
648                                         else {
649                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS2), "along %s Z");
650                                         }
651                                         t->redraw = 1;
652                                 }
653                                 break;
654                         case TFM_MODAL_PLANE_X:
655                                 if ((t->flag & (T_NO_CONSTRAINT|T_2D_EDIT))== 0) {
656                                         if (cmode == 'X') {
657                                                 stopConstraint(t);
658                                         }
659                                         else {
660                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS1|CON_AXIS2), "locking %s X");
661                                         }
662                                         t->redraw = 1;
663                                 }
664                                 break;
665                         case TFM_MODAL_PLANE_Y:
666                                 if ((t->flag & (T_NO_CONSTRAINT|T_2D_EDIT))== 0) {
667                                         if (cmode == 'Y') {
668                                                 stopConstraint(t);
669                                         }
670                                         else {
671                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS0|CON_AXIS2), "locking %s Y");
672                                         }
673                                         t->redraw = 1;
674                                 }
675                                 break;
676                         case TFM_MODAL_PLANE_Z:
677                                 if ((t->flag & (T_NO_CONSTRAINT|T_2D_EDIT))== 0) {
678                                         if (cmode == 'Z') {
679                                                 stopConstraint(t);
680                                         }
681                                         else {
682                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS0|CON_AXIS1), "locking %s Z");
683                                         }
684                                         t->redraw = 1;
685                                 }
686                                 break;
687                         case TFM_MODAL_CONS_OFF:
688                                 if ((t->flag & T_NO_CONSTRAINT)==0) {
689                                         stopConstraint(t);
690                                         t->redraw = 1;
691                                 }
692                                 break;
693                         case TFM_MODAL_ADD_SNAP:
694                                 addSnapPoint(t);
695                                 t->redraw = 1;
696                                 break;
697                         case TFM_MODAL_REMOVE_SNAP:
698                                 removeSnapPoint(t);
699                                 t->redraw = 1;
700                                 break;
701                         default:
702                                 handled = 0;
703                                 break;
704                 }
705         }
706         /* else do non-mapped events */
707         else if (event->val==KM_PRESS) {
708                 switch (event->type){
709                 case RIGHTMOUSE:
710                         t->state = TRANS_CANCEL;
711                         break;
712                 /* enforce redraw of transform when modifiers are used */
713                 case LEFTSHIFTKEY:
714                 case RIGHTSHIFTKEY:
715                         t->modifiers |= MOD_CONSTRAINT_PLANE;
716                         t->redraw = 1;
717                         break;
718
719                 case SPACEKEY:
720                         if ((t->spacetype==SPACE_VIEW3D) && event->alt) {
721 #if 0 // TRANSFORM_FIX_ME
722                                 short mval[2];
723
724                                 getmouseco_sc(mval);
725                                 BIF_selectOrientation();
726                                 calc_manipulator_stats(curarea);
727                                 copy_m3_m4(t->spacemtx, G.vd->twmat);
728                                 warp_pointer(mval[0], mval[1]);
729 #endif
730                         }
731                         else {
732                                 t->state = TRANS_CONFIRM;
733                         }
734                         break;
735
736                 case MIDDLEMOUSE:
737                         if ((t->flag & T_NO_CONSTRAINT)==0) {
738                                 /* exception for switching to dolly, or trackball, in camera view */
739                                 if (t->flag & T_CAMERA) {
740                                         if (t->mode==TFM_TRANSLATION)
741                                                 setLocalConstraint(t, (CON_AXIS2), "along local Z");
742                                         else if (t->mode==TFM_ROTATION) {
743                                                 restoreTransObjects(t);
744                                                 initTrackball(t);
745                                         }
746                                 }
747                                 else {
748                                         t->modifiers |= MOD_CONSTRAINT_SELECT;
749                                         if (t->con.mode & CON_APPLY) {
750                                                 stopConstraint(t);
751                                         }
752                                         else {
753                                                 if (event->shift) {
754                                                         initSelectConstraint(t, t->spacemtx);
755                                                 }
756                                                 else {
757                                                         /* bit hackish... but it prevents mmb select to print the orientation from menu */
758                                                         strcpy(t->spacename, "global");
759                                                         initSelectConstraint(t, mati);
760                                                 }
761                                                 postSelectConstraint(t);
762                                         }
763                                 }
764                                 t->redraw = 1;
765                         }
766                         break;
767                 case ESCKEY:
768                         t->state = TRANS_CANCEL;
769                         break;
770                 case PADENTER:
771                 case RETKEY:
772                         t->state = TRANS_CONFIRM;
773                         break;
774                 case GKEY:
775                         /* only switch when... */
776                         if( ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL) ) {
777                                 resetTransRestrictions(t);
778                                 restoreTransObjects(t);
779                                 initTranslation(t);
780                                 initSnapping(t, NULL); // need to reinit after mode change
781                                 t->redraw = 1;
782                         }
783                         break;
784                 case SKEY:
785                         /* only switch when... */
786                         if( ELEM3(t->mode, TFM_ROTATION, TFM_TRANSLATION, TFM_TRACKBALL) ) {
787                                 resetTransRestrictions(t);
788                                 restoreTransObjects(t);
789                                 initResize(t);
790                                 initSnapping(t, NULL); // need to reinit after mode change
791                                 t->redraw = 1;
792                         }
793                         break;
794                 case RKEY:
795                         /* only switch when... */
796                         if( ELEM4(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL, TFM_TRANSLATION) ) {
797
798                                 resetTransRestrictions(t);
799
800                                 if (t->mode == TFM_ROTATION) {
801                                         restoreTransObjects(t);
802                                         initTrackball(t);
803                                 }
804                                 else {
805                                         restoreTransObjects(t);
806                                         initRotation(t);
807                                 }
808                                 initSnapping(t, NULL); // need to reinit after mode change
809                                 t->redraw = 1;
810                         }
811                         break;
812                 case CKEY:
813                         if (event->alt) {
814                                 t->flag ^= T_PROP_CONNECTED;
815                                 sort_trans_data_dist(t);
816                                 calculatePropRatio(t);
817                                 t->redraw= 1;
818                         }
819                         else {
820                                 stopConstraint(t);
821                                 t->redraw = 1;
822                         }
823                         break;
824                 case XKEY:
825                         if ((t->flag & T_NO_CONSTRAINT)==0) {
826                                 if (t->flag & T_2D_EDIT) {
827                                         if (cmode == 'X') {
828                                                 stopConstraint(t);
829                                         } else {
830                                                 setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0), "along X");
831                                         }
832                                 } else {
833                                         if (cmode == 'X') {
834                                                 if (t->con.orientation != V3D_MANIP_GLOBAL) {
835                                                         stopConstraint(t);
836                                                 } else {
837                                                         short orientation = t->current_orientation != V3D_MANIP_GLOBAL ? t->current_orientation : V3D_MANIP_LOCAL;
838                                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
839                                                                 setUserConstraint(t, orientation, (CON_AXIS0), "along %s X");
840                                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
841                                                                 setUserConstraint(t, orientation, (CON_AXIS1|CON_AXIS2), "locking %s X");
842                                                 }
843                                         } else {
844                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
845                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0), "along %s X");
846                                                 else if (t->modifiers & MOD_CONSTRAINT_PLANE)
847                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS1|CON_AXIS2), "locking %s X");
848                                         }
849                                 }
850                                 t->redraw = 1;
851                         }
852                         break;
853                 case YKEY:
854                         if ((t->flag & T_NO_CONSTRAINT)==0) {
855                                 if (t->flag & T_2D_EDIT) {
856                                         if (cmode == 'Y') {
857                                                 stopConstraint(t);
858                                         } else {
859                                                 setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS1), "along Y");
860                                         }
861                                 } else {
862                                         if (cmode == 'Y') {
863                                                 if (t->con.orientation != V3D_MANIP_GLOBAL) {
864                                                         stopConstraint(t);
865                                                 } else {
866                                                         short orientation = t->current_orientation != V3D_MANIP_GLOBAL ? t->current_orientation : V3D_MANIP_LOCAL;
867                                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
868                                                                 setUserConstraint(t, orientation, (CON_AXIS1), "along %s Y");
869                                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
870                                                                 setUserConstraint(t, orientation, (CON_AXIS0|CON_AXIS2), "locking %s Y");
871                                                 }
872                                         } else {
873                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
874                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS1), "along %s Y");
875                                                 else if (t->modifiers & MOD_CONSTRAINT_PLANE)
876                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0|CON_AXIS2), "locking %s Y");
877                                         }
878                                 }
879                                 t->redraw = 1;
880                         }
881                         break;
882                 case ZKEY:
883                         if ((t->flag & (T_NO_CONSTRAINT|T_2D_EDIT))==0) {
884                                 if (cmode == 'Z') {
885                                         if (t->con.orientation != V3D_MANIP_GLOBAL) {
886                                                 stopConstraint(t);
887                                         } else {
888                                                 short orientation = t->current_orientation != V3D_MANIP_GLOBAL ? t->current_orientation : V3D_MANIP_LOCAL;
889                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
890                                                         setUserConstraint(t, orientation, (CON_AXIS2), "along %s Z");
891                                                 else if (t->modifiers & MOD_CONSTRAINT_PLANE)
892                                                         setUserConstraint(t, orientation, (CON_AXIS0|CON_AXIS1), "locking %s Z");
893                                         }
894                                 } else {
895                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
896                                                 setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS2), "along %s Z");
897                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
898                                                 setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0|CON_AXIS1), "locking %s Z");
899                                 }
900                                 t->redraw = 1;
901                         }
902                         break;
903                 case OKEY:
904                         if (t->flag & T_PROP_EDIT && event->shift) {
905                                 t->prop_mode = (t->prop_mode + 1) % 6;
906                                 calculatePropRatio(t);
907                                 t->redraw = 1;
908                         }
909                         break;
910                 case PADPLUSKEY:
911                         if(event->alt && t->flag & T_PROP_EDIT) {
912                                 t->prop_size *= 1.1f;
913                                 calculatePropRatio(t);
914                         }
915                         t->redraw= 1;
916                         break;
917                 case PAGEUPKEY:
918                 case WHEELDOWNMOUSE:
919                         if (t->flag & T_AUTOIK) {
920                                 transform_autoik_update(t, 1);
921                         }
922                         else if(t->flag & T_PROP_EDIT) {
923                                 t->prop_size*= 1.1f;
924                                 calculatePropRatio(t);
925                         }
926                         else view_editmove(event->type);
927                         t->redraw= 1;
928                         break;
929                 case PADMINUS:
930                         if(event->alt && t->flag & T_PROP_EDIT) {
931                                 t->prop_size*= 0.90909090f;
932                                 calculatePropRatio(t);
933                         }
934                         t->redraw= 1;
935                         break;
936                 case PAGEDOWNKEY:
937                 case WHEELUPMOUSE:
938                         if (t->flag & T_AUTOIK) {
939                                 transform_autoik_update(t, -1);
940                         }
941                         else if (t->flag & T_PROP_EDIT) {
942                                 t->prop_size*= 0.90909090f;
943                                 calculatePropRatio(t);
944                         }
945                         else view_editmove(event->type);
946                         t->redraw= 1;
947                         break;
948 //              case NDOFMOTION:
949 //            viewmoveNDOF(1);
950   //         break;
951                 default:
952                         handled = 0;
953                         break;
954                 }
955
956                 // Numerical input events
957                 t->redraw |= handleNumInput(&(t->num), event, t->snap[1]);
958
959                 // NDof input events
960                 switch(handleNDofInput(&(t->ndof), event))
961                 {
962                         case NDOF_CONFIRM:
963                                 if ((t->options & CTX_NDOF) == 0)
964                                 {
965                                         /* Confirm on normal transform only */
966                                         t->state = TRANS_CONFIRM;
967                                 }
968                                 break;
969                         case NDOF_CANCEL:
970                                 if (t->options & CTX_NDOF)
971                                 {
972                                         /* Cancel on pure NDOF transform */
973                                         t->state = TRANS_CANCEL;
974                                 }
975                                 else
976                                 {
977                                         /* Otherwise, just redraw, NDof input was cancelled */
978                                         t->redraw = 1;
979                                 }
980                                 break;
981                         case NDOF_NOMOVE:
982                                 if (t->options & CTX_NDOF)
983                                 {
984                                         /* Confirm on pure NDOF transform */
985                                         t->state = TRANS_CONFIRM;
986                                 }
987                                 break;
988                         case NDOF_REFRESH:
989                                 t->redraw = 1;
990                                 break;
991                         default:
992                                 handled = 0;
993                                 break;
994                 }
995
996                 // Snapping events
997                 t->redraw |= handleSnapping(t, event);
998
999                 //arrows_move_cursor(event->type);
1000         }
1001         else if (event->val==KM_RELEASE) {
1002                 switch (event->type){
1003                 case LEFTSHIFTKEY:
1004                 case RIGHTSHIFTKEY:
1005                         t->modifiers &= ~MOD_CONSTRAINT_PLANE;
1006                         t->redraw = 1;
1007                         break;
1008
1009                 case MIDDLEMOUSE:
1010                         if ((t->flag & T_NO_CONSTRAINT)==0) {
1011                                 t->modifiers &= ~MOD_CONSTRAINT_SELECT;
1012                                 postSelectConstraint(t);
1013                                 t->redraw = 1;
1014                         }
1015                         break;
1016 //              case LEFTMOUSE:
1017 //              case RIGHTMOUSE:
1018 //                      if(WM_modal_tweak_exit(event, t->event_type))
1019 ////                    if (t->options & CTX_TWEAK)
1020 //                              t->state = TRANS_CONFIRM;
1021 //                      break;
1022                 default:
1023                         handled = 0;
1024                         break;
1025                 }
1026
1027                 /* confirm transform if launch key is released after mouse move */
1028                 /* XXX Keyrepeat bug in Xorg fucks this up, will test when fixed */
1029                 if (event->type == LEFTMOUSE /*t->launch_event*/ && t->state != TRANS_STARTING)
1030                 {
1031                         t->state = TRANS_CONFIRM;
1032                 }
1033         }
1034
1035         // Per transform event, if present
1036         if (t->handleEvent)
1037                 t->redraw |= t->handleEvent(t, event);
1038
1039         if (handled || t->redraw)
1040                 return 0;
1041         else
1042                 return OPERATOR_PASS_THROUGH;
1043 }
1044
1045 int calculateTransformCenter(bContext *C, int centerMode, float *vec)
1046 {
1047         TransInfo *t = MEM_callocN(sizeof(TransInfo), "TransInfo data");
1048         int success = 1;
1049
1050         t->state = TRANS_RUNNING;
1051
1052         t->options = CTX_NONE;
1053
1054         t->mode = TFM_DUMMY;
1055
1056         initTransInfo(C, t, NULL, NULL);        // internal data, mouse, vectors
1057
1058         createTransData(C, t);                          // make TransData structs from selection
1059
1060         t->around = centerMode;                         // override userdefined mode
1061
1062         if (t->total == 0) {
1063                 success = 0;
1064         }
1065         else {
1066                 success = 1;
1067
1068                 calculateCenter(t);
1069
1070                 // Copy center from constraint center. Transform center can be local
1071                 VECCOPY(vec, t->con.center);
1072         }
1073
1074
1075         /* aftertrans does insert ipos and action channels, and clears base flags, doesnt read transdata */
1076         special_aftertrans_update(C, t);
1077
1078         postTrans(C, t);
1079
1080         MEM_freeN(t);
1081
1082         return success;
1083 }
1084
1085 typedef enum {
1086         UP,
1087         DOWN,
1088         LEFT,
1089         RIGHT
1090 } ArrowDirection;
1091 static void drawArrow(ArrowDirection d, short offset, short length, short size)
1092 {
1093         switch(d)
1094         {
1095                 case LEFT:
1096                         offset = -offset;
1097                         length = -length;
1098                         size = -size;
1099                 case RIGHT:
1100                         glBegin(GL_LINES);
1101                         glVertex2s( offset, 0);
1102                         glVertex2s( offset + length, 0);
1103                         glVertex2s( offset + length, 0);
1104                         glVertex2s( offset + length - size, -size);
1105                         glVertex2s( offset + length, 0);
1106                         glVertex2s( offset + length - size,  size);
1107                         glEnd();
1108                         break;
1109                 case DOWN:
1110                         offset = -offset;
1111                         length = -length;
1112                         size = -size;
1113                 case UP:
1114                         glBegin(GL_LINES);
1115                         glVertex2s( 0, offset);
1116                         glVertex2s( 0, offset + length);
1117                         glVertex2s( 0, offset + length);
1118                         glVertex2s(-size, offset + length - size);
1119                         glVertex2s( 0, offset + length);
1120                         glVertex2s( size, offset + length - size);
1121                         glEnd();
1122                         break;
1123         }
1124 }
1125
1126 static void drawArrowHead(ArrowDirection d, short size)
1127 {
1128         switch(d)
1129         {
1130                 case LEFT:
1131                         size = -size;
1132                 case RIGHT:
1133                         glBegin(GL_LINES);
1134                         glVertex2s( 0, 0);
1135                         glVertex2s( -size, -size);
1136                         glVertex2s( 0, 0);
1137                         glVertex2s( -size,  size);
1138                         glEnd();
1139                         break;
1140                 case DOWN:
1141                         size = -size;
1142                 case UP:
1143                         glBegin(GL_LINES);
1144                         glVertex2s( 0, 0);
1145                         glVertex2s(-size, -size);
1146                         glVertex2s( 0, 0);
1147                         glVertex2s( size, -size);
1148                         glEnd();
1149                         break;
1150         }
1151 }
1152
1153 static void drawArc(float size, float angle_start, float angle_end, int segments)
1154 {
1155         float delta = (angle_end - angle_start) / segments;
1156         float angle;
1157
1158         glBegin(GL_LINE_STRIP);
1159
1160         for( angle = angle_start; angle < angle_end; angle += delta)
1161         {
1162                 glVertex2f( cosf(angle) * size, sinf(angle) * size);
1163         }
1164         glVertex2f( cosf(angle_end) * size, sinf(angle_end) * size);
1165
1166         glEnd();
1167 }
1168
1169 static void drawHelpline(bContext *C, int x, int y, void *customdata)
1170 {
1171         TransInfo *t = (TransInfo*)customdata;
1172
1173         if (t->helpline != HLP_NONE && !(t->flag & T_USES_MANIPULATOR))
1174         {
1175                 float vecrot[3], cent[2];
1176                 int mval[2] = {x, y};
1177
1178                 VECCOPY(vecrot, t->center);
1179                 if(t->flag & T_EDIT) {
1180                         Object *ob= t->obedit;
1181                         if(ob) mul_m4_v3(ob->obmat, vecrot);
1182                 }
1183                 else if(t->flag & T_POSE) {
1184                         Object *ob=t->poseobj;
1185                         if(ob) mul_m4_v3(ob->obmat, vecrot);
1186                 }
1187
1188                 projectFloatView(t, vecrot, cent);      // no overflow in extreme cases
1189
1190                 glPushMatrix();
1191
1192                 switch(t->helpline)
1193                 {
1194                         case HLP_SPRING:
1195                                 UI_ThemeColor(TH_WIRE);
1196
1197                                 setlinestyle(3);
1198                                 glBegin(GL_LINE_STRIP);
1199                                 glVertex2sv(t->mval);
1200                                 glVertex2fv(cent);
1201                                 glEnd();
1202
1203                                 glTranslatef(mval[0], mval[1], 0);
1204                                 glRotatef(-180 / M_PI * atan2f(cent[0] - t->mval[0], cent[1] - t->mval[1]), 0, 0, 1);
1205
1206                                 setlinestyle(0);
1207                                 glLineWidth(3.0);
1208                                 drawArrow(UP, 5, 10, 5);
1209                                 drawArrow(DOWN, 5, 10, 5);
1210                                 glLineWidth(1.0);
1211                                 break;
1212                         case HLP_HARROW:
1213                                 UI_ThemeColor(TH_WIRE);
1214
1215                                 glTranslatef(mval[0], mval[1], 0);
1216
1217                                 glLineWidth(3.0);
1218                                 drawArrow(RIGHT, 5, 10, 5);
1219                                 drawArrow(LEFT, 5, 10, 5);
1220                                 glLineWidth(1.0);
1221                                 break;
1222                         case HLP_VARROW:
1223                                 UI_ThemeColor(TH_WIRE);
1224
1225                                 glTranslatef(mval[0], mval[1], 0);
1226
1227                                 glLineWidth(3.0);
1228                                 glBegin(GL_LINES);
1229                                 drawArrow(UP, 5, 10, 5);
1230                                 drawArrow(DOWN, 5, 10, 5);
1231                                 glLineWidth(1.0);
1232                                 break;
1233                         case HLP_ANGLE:
1234                                 {
1235                                         float dx = t->mval[0] - cent[0], dy = t->mval[1] - cent[1];
1236                                         float angle = atan2f(dy, dx);
1237                                         float dist = sqrtf(dx*dx + dy*dy);
1238                                         float delta_angle = MIN2(15 / dist, M_PI/4);
1239                                         float spacing_angle = MIN2(5 / dist, M_PI/12);
1240                                         UI_ThemeColor(TH_WIRE);
1241
1242                                         setlinestyle(3);
1243                                         glBegin(GL_LINE_STRIP);
1244                                         glVertex2sv(t->mval);
1245                                         glVertex2fv(cent);
1246                                         glEnd();
1247
1248                                         glTranslatef(cent[0] - t->mval[0] + mval[0], cent[1] - t->mval[1] + mval[1], 0);
1249
1250                                         setlinestyle(0);
1251                                         glLineWidth(3.0);
1252                                         drawArc(dist, angle - delta_angle, angle - spacing_angle, 10);
1253                                         drawArc(dist, angle + spacing_angle, angle + delta_angle, 10);
1254
1255                                         glPushMatrix();
1256
1257                                         glTranslatef(cosf(angle - delta_angle) * dist, sinf(angle - delta_angle) * dist, 0);
1258                                         glRotatef(180 / M_PI * (angle - delta_angle), 0, 0, 1);
1259
1260                                         drawArrowHead(DOWN, 5);
1261
1262                                         glPopMatrix();
1263
1264                                         glTranslatef(cosf(angle + delta_angle) * dist, sinf(angle + delta_angle) * dist, 0);
1265                                         glRotatef(180 / M_PI * (angle + delta_angle), 0, 0, 1);
1266
1267                                         drawArrowHead(UP, 5);
1268
1269                                         glLineWidth(1.0);
1270                                         break;
1271                                 }
1272                                 case HLP_TRACKBALL:
1273                                 {
1274                                         char col[3], col2[3];
1275                                         UI_GetThemeColor3ubv(TH_GRID, col);
1276
1277                                         glTranslatef(mval[0], mval[1], 0);
1278
1279                                         glLineWidth(3.0);
1280
1281                                         UI_make_axis_color(col, col2, 'x');
1282                                         glColor3ubv((GLubyte *)col2);
1283
1284                                         drawArrow(RIGHT, 5, 10, 5);
1285                                         drawArrow(LEFT, 5, 10, 5);
1286
1287                                         UI_make_axis_color(col, col2, 'y');
1288                                         glColor3ubv((GLubyte *)col2);
1289
1290                                         drawArrow(UP, 5, 10, 5);
1291                                         drawArrow(DOWN, 5, 10, 5);
1292                                         glLineWidth(1.0);
1293                                         break;
1294                                 }
1295                 }
1296
1297                 glPopMatrix();
1298         }
1299 }
1300
1301 void drawTransformView(const struct bContext *C, struct ARegion *ar, void *arg)
1302 {
1303         TransInfo *t = arg;
1304
1305         drawConstraint(C, t);
1306         drawPropCircle(C, t);
1307         drawSnapping(C, t);
1308 }
1309
1310 void drawTransformPixel(const struct bContext *C, struct ARegion *ar, void *arg)
1311 {
1312 //      TransInfo *t = arg;
1313 //
1314 //      drawHelpline(C, t->mval[0], t->mval[1], t);
1315 }
1316
1317 void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
1318 {
1319         ToolSettings *ts = CTX_data_tool_settings(C);
1320         int constraint_axis[3] = {0, 0, 0};
1321         int proportional = 0;
1322
1323         if (RNA_struct_find_property(op->ptr, "value"))
1324         {
1325                 if (t->flag & T_AUTOVALUES)
1326                 {
1327                         RNA_float_set_array(op->ptr, "value", t->auto_values);
1328                 }
1329                 else
1330                 {
1331                         RNA_float_set_array(op->ptr, "value", t->values);
1332                 }
1333         }
1334
1335         /* XXX convert stupid flag to enum */
1336         switch(t->flag & (T_PROP_EDIT|T_PROP_CONNECTED))
1337         {
1338         case (T_PROP_EDIT|T_PROP_CONNECTED):
1339                 proportional = 2;
1340                 break;
1341         case T_PROP_EDIT:
1342                 proportional = 1;
1343                 break;
1344         default:
1345                 proportional = 0;
1346         }
1347
1348         // If modal, save settings back in scene if not set as operator argument
1349         if (t->flag & T_MODAL) {
1350
1351                 /* save settings if not set in operator */
1352                 if (RNA_struct_find_property(op->ptr, "proportional") && !RNA_property_is_set(op->ptr, "proportional")) {
1353                         ts->proportional = proportional;
1354                 }
1355
1356                 if (RNA_struct_find_property(op->ptr, "proportional_size") && !RNA_property_is_set(op->ptr, "proportional_size")) {
1357                         ts->proportional_size = t->prop_size;
1358                 }
1359                         
1360                 if (RNA_struct_find_property(op->ptr, "proportional_editing_falloff") && !RNA_property_is_set(op->ptr, "proportional_editing_falloff")) {
1361                         ts->prop_mode = t->prop_mode;
1362                 }
1363                 
1364                 /* do we check for parameter? */
1365                 if (t->modifiers & MOD_SNAP) {
1366                         ts->snap_flag |= SCE_SNAP;
1367                 } else {
1368                         ts->snap_flag &= ~SCE_SNAP;
1369                 }
1370
1371                 if(t->spacetype == SPACE_VIEW3D) {
1372                         if (RNA_struct_find_property(op->ptr, "constraint_orientation") && !RNA_property_is_set(op->ptr, "constraint_orientation")) {
1373                                 View3D *v3d = t->view;
1374         
1375                                 v3d->twmode = t->current_orientation;
1376                         }
1377                 }
1378         }
1379         
1380         if (RNA_struct_find_property(op->ptr, "proportional"))
1381         {
1382                 RNA_enum_set(op->ptr, "proportional", proportional);
1383                 RNA_enum_set(op->ptr, "proportional_editing_falloff", t->prop_mode);
1384                 RNA_float_set(op->ptr, "proportional_size", t->prop_size);
1385         }
1386
1387         if (RNA_struct_find_property(op->ptr, "axis"))
1388         {
1389                 RNA_float_set_array(op->ptr, "axis", t->axis);
1390         }
1391
1392         if (RNA_struct_find_property(op->ptr, "mirror"))
1393         {
1394                 RNA_boolean_set(op->ptr, "mirror", t->flag & T_MIRROR);
1395         }
1396
1397         if (RNA_struct_find_property(op->ptr, "constraint_axis"))
1398         {
1399                 /* constraint orientation can be global, event if user selects something else
1400                  * so use the orientation in the constraint if set
1401                  * */
1402                 if (t->con.mode & CON_APPLY) {
1403                         RNA_enum_set(op->ptr, "constraint_orientation", t->con.orientation);
1404                 } else {
1405                         RNA_enum_set(op->ptr, "constraint_orientation", t->current_orientation);
1406                 }
1407
1408                 if (t->con.mode & CON_APPLY)
1409                 {
1410                         if (t->con.mode & CON_AXIS0) {
1411                                 constraint_axis[0] = 1;
1412                         }
1413                         if (t->con.mode & CON_AXIS1) {
1414                                 constraint_axis[1] = 1;
1415                         }
1416                         if (t->con.mode & CON_AXIS2) {
1417                                 constraint_axis[2] = 1;
1418                         }
1419                 }
1420
1421                 RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
1422         }
1423 }
1424
1425 int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int mode)
1426 {
1427         int options = 0;
1428
1429         /* added initialize, for external calls to set stuff in TransInfo, like undo string */
1430
1431         t->state = TRANS_STARTING;
1432
1433         t->options = options;
1434
1435         t->mode = mode;
1436
1437         t->launch_event = event ? event->type : -1;
1438
1439         if (!initTransInfo(C, t, op, event))                                    // internal data, mouse, vectors
1440         {
1441                 return 0;
1442         }
1443
1444         if(t->spacetype == SPACE_VIEW3D)
1445         {
1446                 //calc_manipulator_stats(curarea);
1447                 initTransformOrientation(C, t);
1448
1449                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1450                 //t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1451                 t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), NULL, drawHelpline, t);
1452         }
1453         else if(t->spacetype == SPACE_IMAGE) {
1454                 unit_m3(t->spacemtx);
1455                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1456                 //t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1457         }
1458         else
1459                 unit_m3(t->spacemtx);
1460
1461         createTransData(C, t);                  // make TransData structs from selection
1462
1463         if (t->total == 0) {
1464                 postTrans(C, t);
1465                 return 0;
1466         }
1467
1468         initSnapping(t, op); // Initialize snapping data AFTER mode flags
1469
1470         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1471         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1472         /* EVIL3: extend mode for animation editors also switches modes... but is best way to avoid duplicate code */
1473         mode = t->mode;
1474
1475         calculatePropRatio(t);
1476         calculateCenter(t);
1477
1478         initMouseInput(t, &t->mouse, t->center2d, t->imval);
1479
1480         switch (mode) {
1481         case TFM_TRANSLATION:
1482                 initTranslation(t);
1483                 break;
1484         case TFM_ROTATION:
1485                 initRotation(t);
1486                 break;
1487         case TFM_RESIZE:
1488                 initResize(t);
1489                 break;
1490         case TFM_TOSPHERE:
1491                 initToSphere(t);
1492                 break;
1493         case TFM_SHEAR:
1494                 initShear(t);
1495                 break;
1496         case TFM_WARP:
1497                 initWarp(t);
1498                 break;
1499         case TFM_SHRINKFATTEN:
1500                 initShrinkFatten(t);
1501                 break;
1502         case TFM_TILT:
1503                 initTilt(t);
1504                 break;
1505         case TFM_CURVE_SHRINKFATTEN:
1506                 initCurveShrinkFatten(t);
1507                 break;
1508         case TFM_TRACKBALL:
1509                 initTrackball(t);
1510                 break;
1511         case TFM_PUSHPULL:
1512                 initPushPull(t);
1513                 break;
1514         case TFM_CREASE:
1515                 initCrease(t);
1516                 break;
1517         case TFM_BONESIZE:
1518                 {       /* used for both B-Bone width (bonesize) as for deform-dist (envelope) */
1519                         bArmature *arm= t->poseobj->data;
1520                         if(arm->drawtype==ARM_ENVELOPE)
1521                                 initBoneEnvelope(t);
1522                         else
1523                                 initBoneSize(t);
1524                 }
1525                 break;
1526         case TFM_BONE_ENVELOPE:
1527                 initBoneEnvelope(t);
1528                 break;
1529         case TFM_EDGE_SLIDE:
1530                 initEdgeSlide(t);
1531                 break;
1532         case TFM_BONE_ROLL:
1533                 initBoneRoll(t);
1534                 break;
1535         case TFM_TIME_TRANSLATE:
1536                 initTimeTranslate(t);
1537                 break;
1538         case TFM_TIME_SLIDE:
1539                 initTimeSlide(t);
1540                 break;
1541         case TFM_TIME_SCALE:
1542                 initTimeScale(t);
1543                 break;
1544         case TFM_TIME_EXTEND:
1545                 /* now that transdata has been made, do like for TFM_TIME_TRANSLATE (for most Animation
1546                  * Editors because they have only 1D transforms for time values) or TFM_TRANSLATION
1547                  * (for Graph/NLA Editors only since they uses 'standard' transforms to get 2D movement)
1548                  * depending on which editor this was called from
1549                  */
1550                 if ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)
1551                         initTranslation(t);
1552                 else
1553                         initTimeTranslate(t);
1554                 break;
1555         case TFM_BAKE_TIME:
1556                 initBakeTime(t);
1557                 break;
1558         case TFM_MIRROR:
1559                 initMirror(t);
1560                 break;
1561         case TFM_BEVEL:
1562                 initBevel(t);
1563                 break;
1564         case TFM_BWEIGHT:
1565                 initBevelWeight(t);
1566                 break;
1567         case TFM_ALIGN:
1568                 initAlign(t);
1569                 break;
1570         case TFM_SEQ_SLIDE:
1571                 initSeqSlide(t);
1572                 break;
1573         }
1574
1575         /* overwrite initial values if operator supplied a non-null vector */
1576         if (RNA_property_is_set(op->ptr, "value"))
1577         {
1578                 float values[4];
1579                 RNA_float_get_array(op->ptr, "value", values);
1580                 QUATCOPY(t->values, values);
1581                 QUATCOPY(t->auto_values, values);
1582                 t->flag |= T_AUTOVALUES;
1583         }
1584
1585         /* Transformation axis from operator */
1586         if (RNA_struct_find_property(op->ptr, "axis") && RNA_property_is_set(op->ptr, "axis"))
1587         {
1588                 RNA_float_get_array(op->ptr, "axis", t->axis);
1589                 normalize_v3(t->axis);
1590         }
1591
1592         /* Constraint init from operator */
1593         if (RNA_struct_find_property(op->ptr, "constraint_axis") && RNA_property_is_set(op->ptr, "constraint_axis"))
1594         {
1595                 int constraint_axis[3];
1596
1597                 RNA_boolean_get_array(op->ptr, "constraint_axis", constraint_axis);
1598
1599                 if (constraint_axis[0] || constraint_axis[1] || constraint_axis[2])
1600                 {
1601                         t->con.mode |= CON_APPLY;
1602
1603                         if (constraint_axis[0]) {
1604                                 t->con.mode |= CON_AXIS0;
1605                         }
1606                         if (constraint_axis[1]) {
1607                                 t->con.mode |= CON_AXIS1;
1608                         }
1609                         if (constraint_axis[2]) {
1610                                 t->con.mode |= CON_AXIS2;
1611                         }
1612
1613                         setUserConstraint(t, t->current_orientation, t->con.mode, "%s");
1614                 }
1615         }
1616
1617         return 1;
1618 }
1619
1620 void transformApply(bContext *C, TransInfo *t)
1621 {
1622         if (t->redraw)
1623         {
1624                 selectConstraint(t);
1625                 if (t->transform) {
1626                         t->transform(t, t->mval);  // calls recalcData()
1627                         viewRedrawForce(C, t);
1628                 }
1629                 t->redraw = 0;
1630         }
1631
1632         /* If auto confirm is on, break after one pass */
1633         if (t->options & CTX_AUTOCONFIRM)
1634         {
1635                 t->state = TRANS_CONFIRM;
1636         }
1637
1638         if (BKE_ptcache_get_continue_physics())
1639         {
1640                 // TRANSFORM_FIX_ME
1641                 //do_screenhandlers(G.curscreen);
1642                 t->redraw = 1;
1643         }
1644 }
1645
1646 int transformEnd(bContext *C, TransInfo *t)
1647 {
1648         int exit_code = OPERATOR_RUNNING_MODAL;
1649
1650         if (t->state != TRANS_STARTING && t->state != TRANS_RUNNING)
1651         {
1652                 /* handle restoring objects */
1653                 if(t->state == TRANS_CANCEL)
1654                 {
1655                         exit_code = OPERATOR_CANCELLED;
1656                         restoreTransObjects(t); // calls recalcData()
1657                 }
1658                 else
1659                 {
1660                         exit_code = OPERATOR_FINISHED;
1661                 }
1662
1663                 /* aftertrans does insert keyframes, and clears base flags, doesnt read transdata */
1664                 special_aftertrans_update(C, t);
1665
1666                 /* free data */
1667                 postTrans(C, t);
1668
1669                 /* send events out for redraws */
1670                 viewRedrawPost(t);
1671
1672                 /*  Undo as last, certainly after special_trans_update! */
1673
1674                 if(t->state == TRANS_CANCEL) {
1675 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1676                 }
1677                 else {
1678 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1679 //                      else ED_undo_push(C, transform_to_undostr(t));
1680                 }
1681                 t->undostr= NULL;
1682
1683                 viewRedrawForce(C, t);
1684         }
1685
1686         return exit_code;
1687 }
1688
1689 /* ************************** TRANSFORM LOCKS **************************** */
1690
1691 static void protectedTransBits(short protectflag, float *vec)
1692 {
1693         if(protectflag & OB_LOCK_LOCX)
1694                 vec[0]= 0.0f;
1695         if(protectflag & OB_LOCK_LOCY)
1696                 vec[1]= 0.0f;
1697         if(protectflag & OB_LOCK_LOCZ)
1698                 vec[2]= 0.0f;
1699 }
1700
1701 static void protectedSizeBits(short protectflag, float *size)
1702 {
1703         if(protectflag & OB_LOCK_SCALEX)
1704                 size[0]= 1.0f;
1705         if(protectflag & OB_LOCK_SCALEY)
1706                 size[1]= 1.0f;
1707         if(protectflag & OB_LOCK_SCALEZ)
1708                 size[2]= 1.0f;
1709 }
1710
1711 static void protectedRotateBits(short protectflag, float *eul, float *oldeul)
1712 {
1713         if(protectflag & OB_LOCK_ROTX)
1714                 eul[0]= oldeul[0];
1715         if(protectflag & OB_LOCK_ROTY)
1716                 eul[1]= oldeul[1];
1717         if(protectflag & OB_LOCK_ROTZ)
1718                 eul[2]= oldeul[2];
1719 }
1720
1721
1722 /* this function only does the delta rotation */
1723 /* axis-angle is usually internally stored as quats... */
1724 static void protectedAxisAngleBits(short protectflag, float axis[3], float *angle, float oldAxis[3], float oldAngle)
1725 {
1726         /* check that protection flags are set */
1727         if ((protectflag & (OB_LOCK_ROTX|OB_LOCK_ROTY|OB_LOCK_ROTZ|OB_LOCK_ROTW)) == 0)
1728                 return;
1729         
1730         if (protectflag & OB_LOCK_ROT4D) {
1731                 /* axis-angle getting limited as 4D entities that they are... */
1732                 if (protectflag & OB_LOCK_ROTW)
1733                         *angle= oldAngle;
1734                 if (protectflag & OB_LOCK_ROTX)
1735                         axis[0]= oldAxis[0];
1736                 if (protectflag & OB_LOCK_ROTY)
1737                         axis[1]= oldAxis[1];
1738                 if (protectflag & OB_LOCK_ROTZ)
1739                         axis[2]= oldAxis[2];
1740         }
1741         else {
1742                 /* axis-angle get limited with euler... */
1743                 float eul[3], oldeul[3];
1744                 
1745                 axis_angle_to_eulO( eul, EULER_ORDER_DEFAULT,axis, *angle);
1746                 axis_angle_to_eulO( oldeul, EULER_ORDER_DEFAULT,oldAxis, oldAngle);
1747                 
1748                 if (protectflag & OB_LOCK_ROTX)
1749                         eul[0]= oldeul[0];
1750                 if (protectflag & OB_LOCK_ROTY)
1751                         eul[1]= oldeul[1];
1752                 if (protectflag & OB_LOCK_ROTZ)
1753                         eul[2]= oldeul[2];
1754                 
1755                 eulO_to_axis_angle( axis, angle,eul, EULER_ORDER_DEFAULT);
1756                 
1757                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1758                 if (IS_EQ(axis[0], axis[1]) && IS_EQ(axis[1], axis[2])) {
1759                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1760                         axis[1]= 1.0f;
1761                 }
1762         }
1763 }
1764
1765 /* this function only does the delta rotation */
1766 static void protectedQuaternionBits(short protectflag, float *quat, float *oldquat)
1767 {
1768         /* check that protection flags are set */
1769         if ((protectflag & (OB_LOCK_ROTX|OB_LOCK_ROTY|OB_LOCK_ROTZ|OB_LOCK_ROTW)) == 0)
1770                 return;
1771         
1772         if (protectflag & OB_LOCK_ROT4D) {
1773                 /* quaternions getting limited as 4D entities that they are... */
1774                 if (protectflag & OB_LOCK_ROTW)
1775                         quat[0]= oldquat[0];
1776                 if (protectflag & OB_LOCK_ROTX)
1777                         quat[1]= oldquat[1];
1778                 if (protectflag & OB_LOCK_ROTY)
1779                         quat[2]= oldquat[2];
1780                 if (protectflag & OB_LOCK_ROTZ)
1781                         quat[3]= oldquat[3];
1782         }
1783         else {
1784                 /* quaternions get limited with euler... (compatability mode) */
1785                 float eul[3], oldeul[3], quat1[4];
1786                 
1787                 QUATCOPY(quat1, quat);
1788                 quat_to_eul( eul,quat);
1789                 quat_to_eul( oldeul,oldquat);
1790                 
1791                 if (protectflag & OB_LOCK_ROTX)
1792                         eul[0]= oldeul[0];
1793                 if (protectflag & OB_LOCK_ROTY)
1794                         eul[1]= oldeul[1];
1795                 if (protectflag & OB_LOCK_ROTZ)
1796                         eul[2]= oldeul[2];
1797                 
1798                 eul_to_quat( quat,eul);
1799                 
1800                 /* quaternions flip w sign to accumulate rotations correctly */
1801                 if ( (quat1[0]<0.0f && quat[0]>0.0f) || (quat1[0]>0.0f && quat[0]<0.0f) ) {
1802                         mul_qt_fl(quat, -1.0f);
1803                 }
1804         }
1805 }
1806
1807 /* ******************* TRANSFORM LIMITS ********************** */
1808
1809 static void constraintTransLim(TransInfo *t, TransData *td)
1810 {
1811         if (td->con) {
1812                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_LOCLIMIT);
1813                 bConstraintOb cob;
1814                 bConstraint *con;
1815                 
1816                 /* Make a temporary bConstraintOb for using these limit constraints
1817                  *      - they only care that cob->matrix is correctly set ;-)
1818                  *      - current space should be local
1819                  */
1820                 memset(&cob, 0, sizeof(bConstraintOb));
1821                 unit_m4(cob.matrix);
1822                 VECCOPY(cob.matrix[3], td->loc);
1823                 
1824                 /* Evaluate valid constraints */
1825                 for (con= td->con; con; con= con->next) {
1826                         float tmat[4][4];
1827                         
1828                         /* only consider constraint if enabled */
1829                         if (con->flag & CONSTRAINT_DISABLE) continue;
1830                         if (con->enforce == 0.0f) continue;
1831                         
1832                         /* only use it if it's tagged for this purpose (and the right type) */
1833                         if (con->type == CONSTRAINT_TYPE_LOCLIMIT) {
1834                                 bLocLimitConstraint *data= con->data;
1835                                 
1836                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1837                                         continue;
1838                                 
1839                                 /* do space conversions */
1840                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1841                                         /* just multiply by td->mtx (this should be ok) */
1842                                         copy_m4_m4(tmat, cob.matrix);
1843                                         mul_m4_m3m4(cob.matrix, td->mtx, tmat);
1844                                 }
1845                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1846                                         /* skip... incompatable spacetype */
1847                                         continue;
1848                                 }
1849                                 
1850                                 /* do constraint */
1851                                 cti->evaluate_constraint(con, &cob, NULL);
1852                                 
1853                                 /* convert spaces again */
1854                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1855                                         /* just multiply by td->mtx (this should be ok) */
1856                                         copy_m4_m4(tmat, cob.matrix);
1857                                         mul_m4_m3m4(cob.matrix, td->smtx, tmat);
1858                                 }
1859                         }
1860                 }
1861                 
1862                 /* copy results from cob->matrix */
1863                 VECCOPY(td->loc, cob.matrix[3]);
1864         }
1865 }
1866
1867 static void constraintRotLim(TransInfo *t, TransData *td)
1868 {
1869         if (td->con) {
1870                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_ROTLIMIT);
1871                 bConstraintOb cob;
1872                 bConstraint *con;
1873
1874                 /* Make a temporary bConstraintOb for using these limit constraints
1875                  *      - they only care that cob->matrix is correctly set ;-)
1876                  *      - current space should be local
1877                  */
1878                 memset(&cob, 0, sizeof(bConstraintOb));
1879                 if (td->rotOrder == ROT_MODE_QUAT) {
1880                         /* quats */
1881                         if (td->ext)
1882                                 quat_to_mat4( cob.matrix,td->ext->quat);
1883                         else
1884                                 return;
1885                 }
1886                 else if (td->rotOrder == ROT_MODE_AXISANGLE) {
1887                         /* axis angle */
1888                         if (td->ext)
1889                                 axis_angle_to_mat4( cob.matrix,&td->ext->quat[1], td->ext->quat[0]);
1890                         else
1891                                 return;
1892                 }
1893                 else {
1894                         /* eulers */
1895                         if (td->ext)
1896                                 eulO_to_mat4( cob.matrix,td->ext->rot, td->rotOrder);
1897                         else
1898                                 return;
1899                 }
1900                 
1901                 /* Evaluate valid constraints */
1902                 for (con= td->con; con; con= con->next) {
1903                         /* only consider constraint if enabled */
1904                         if (con->flag & CONSTRAINT_DISABLE) continue;
1905                         if (con->enforce == 0.0f) continue;
1906                         
1907                         /* we're only interested in Limit-Rotation constraints */
1908                         if (con->type == CONSTRAINT_TYPE_ROTLIMIT) {
1909                                 bRotLimitConstraint *data= con->data;
1910                                 float tmat[4][4];
1911                                 
1912                                 /* only use it if it's tagged for this purpose */
1913                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1914                                         continue;
1915                                 
1916                                 /* do space conversions */
1917                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1918                                         /* just multiply by td->mtx (this should be ok) */
1919                                         copy_m4_m4(tmat, cob.matrix);
1920                                         mul_m4_m3m4(cob.matrix, td->mtx, tmat);
1921                                 }
1922                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1923                                         /* skip... incompatable spacetype */
1924                                         continue;
1925                                 }
1926                                 
1927                                 /* do constraint */
1928                                 cti->evaluate_constraint(con, &cob, NULL);
1929                                 
1930                                 /* convert spaces again */
1931                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1932                                         /* just multiply by td->mtx (this should be ok) */
1933                                         copy_m4_m4(tmat, cob.matrix);
1934                                         mul_m4_m3m4(cob.matrix, td->smtx, tmat);
1935                                 }
1936                         }
1937                 }
1938                 
1939                 /* copy results from cob->matrix */
1940                 if (td->rotOrder == ROT_MODE_QUAT) {
1941                         /* quats */
1942                         mat4_to_quat( td->ext->quat,cob.matrix);
1943                 }
1944                 else if (td->rotOrder == ROT_MODE_AXISANGLE) {
1945                         /* axis angle */
1946                         mat4_to_axis_angle( &td->ext->quat[1], &td->ext->quat[0],cob.matrix);
1947                 }
1948                 else {
1949                         /* eulers */
1950                         mat4_to_eulO( td->ext->rot, td->rotOrder,cob.matrix);
1951                 }
1952         }
1953 }
1954
1955 static void constraintSizeLim(TransInfo *t, TransData *td)
1956 {
1957         if (td->con && td->ext) {
1958                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_SIZELIMIT);
1959                 bConstraintOb cob;
1960                 bConstraint *con;
1961                 
1962                 /* Make a temporary bConstraintOb for using these limit constraints
1963                  *      - they only care that cob->matrix is correctly set ;-)
1964                  *      - current space should be local
1965                  */
1966                 memset(&cob, 0, sizeof(bConstraintOb));
1967                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
1968                         /* scale val and reset size */
1969                         return; // TODO: fix this case
1970                 }
1971                 else {
1972                         /* Reset val if SINGLESIZE but using a constraint */
1973                         if (td->flag & TD_SINGLESIZE)
1974                                 return;
1975                         
1976                         size_to_mat4( cob.matrix,td->ext->size);
1977                 }
1978                 
1979                 /* Evaluate valid constraints */
1980                 for (con= td->con; con; con= con->next) {
1981                         /* only consider constraint if enabled */
1982                         if (con->flag & CONSTRAINT_DISABLE) continue;
1983                         if (con->enforce == 0.0f) continue;
1984                         
1985                         /* we're only interested in Limit-Scale constraints */
1986                         if (con->type == CONSTRAINT_TYPE_SIZELIMIT) {
1987                                 bSizeLimitConstraint *data= con->data;
1988                                 float tmat[4][4];
1989                                 
1990                                 /* only use it if it's tagged for this purpose */
1991                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1992                                         continue;
1993                                 
1994                                 /* do space conversions */
1995                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1996                                         /* just multiply by td->mtx (this should be ok) */
1997                                         copy_m4_m4(tmat, cob.matrix);
1998                                         mul_m4_m3m4(cob.matrix, td->mtx, tmat);
1999                                 }
2000                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
2001                                         /* skip... incompatable spacetype */
2002                                         continue;
2003                                 }
2004                                 
2005                                 /* do constraint */
2006                                 cti->evaluate_constraint(con, &cob, NULL);
2007                                 
2008                                 /* convert spaces again */
2009                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2010                                         /* just multiply by td->mtx (this should be ok) */
2011                                         copy_m4_m4(tmat, cob.matrix);
2012                                         mul_m4_m3m4(cob.matrix, td->smtx, tmat);
2013                                 }
2014                         }
2015                 }
2016                 
2017                 /* copy results from cob->matrix */
2018                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
2019                         /* scale val and reset size */
2020                         return; // TODO: fix this case
2021                 }
2022                 else {
2023                         /* Reset val if SINGLESIZE but using a constraint */
2024                         if (td->flag & TD_SINGLESIZE)
2025                                 return;
2026                         
2027                         mat4_to_size( td->ext->size,cob.matrix);
2028                 }
2029         }
2030 }
2031
2032 /* ************************** WARP *************************** */
2033
2034 void initWarp(TransInfo *t)
2035 {
2036         float max[3], min[3];
2037         int i;
2038         
2039         t->mode = TFM_WARP;
2040         t->transform = Warp;
2041         t->handleEvent = handleEventWarp;
2042         
2043         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
2044         
2045         t->idx_max = 0;
2046         t->num.idx_max = 0;
2047         t->snap[0] = 0.0f;
2048         t->snap[1] = 5.0f;
2049         t->snap[2] = 1.0f;
2050         
2051         t->flag |= T_NO_CONSTRAINT;
2052         
2053         /* we need min/max in view space */
2054         for(i = 0; i < t->total; i++) {
2055                 float center[3];
2056                 VECCOPY(center, t->data[i].center);
2057                 mul_m3_v3(t->data[i].mtx, center);
2058                 mul_m4_v3(t->viewmat, center);
2059                 sub_v3_v3v3(center, center, t->viewmat[3]);
2060                 if (i)
2061                         minmax_v3_v3v3(min, max, center);
2062                 else {
2063                         VECCOPY(max, center);
2064                         VECCOPY(min, center);
2065                 }
2066         }
2067         
2068         t->center[0]= (min[0]+max[0])/2.0f;
2069         t->center[1]= (min[1]+max[1])/2.0f;
2070         t->center[2]= (min[2]+max[2])/2.0f;
2071
2072         if (max[0] == min[0]) max[0] += 0.1; /* not optimal, but flipping is better than invalid garbage (i.e. division by zero!) */
2073         t->val= (max[0]-min[0])/2.0f; /* t->val is X dimension projected boundbox */
2074 }
2075
2076 int handleEventWarp(TransInfo *t, wmEvent *event)
2077 {
2078         int status = 0;
2079         
2080         if (event->type == MIDDLEMOUSE && event->val==KM_PRESS)
2081         {
2082                 // Use customData pointer to signal warp direction
2083                 if      (t->customData == 0)
2084                         t->customData = (void*)1;
2085                 else
2086                         t->customData = 0;
2087                 
2088                 status = 1;
2089         }
2090         
2091         return status;
2092 }
2093
2094 int Warp(TransInfo *t, short mval[2])
2095 {
2096         TransData *td = t->data;
2097         float vec[3], circumfac, dist, phi0, co, si, *curs, cursor[3], gcursor[3];
2098         int i;
2099         char str[50];
2100         
2101         curs= give_cursor(t->scene, t->view);
2102         /*
2103          * gcursor is the one used for helpline.
2104          * It has to be in the same space as the drawing loop
2105          * (that means it needs to be in the object's space when in edit mode and
2106          *  in global space in object mode)
2107          *
2108          * cursor is used for calculations.
2109          * It needs to be in view space, but we need to take object's offset
2110          * into account if in Edit mode.
2111          */
2112         VECCOPY(cursor, curs);
2113         VECCOPY(gcursor, cursor);
2114         if (t->flag & T_EDIT) {
2115                 sub_v3_v3v3(cursor, cursor, t->obedit->obmat[3]);
2116                 sub_v3_v3v3(gcursor, gcursor, t->obedit->obmat[3]);
2117                 mul_m3_v3(t->data->smtx, gcursor);
2118         }
2119         mul_m4_v3(t->viewmat, cursor);
2120         sub_v3_v3v3(cursor, cursor, t->viewmat[3]);
2121         
2122         /* amount of degrees for warp */
2123         circumfac = 360.0f * t->values[0];
2124         
2125         if (t->customData) /* non-null value indicates reversed input */
2126         {
2127                 circumfac *= -1;
2128         }
2129         
2130         snapGrid(t, &circumfac);
2131         applyNumInput(&t->num, &circumfac);
2132         
2133         /* header print for NumInput */
2134         if (hasNumInput(&t->num)) {
2135                 char c[20];
2136                 
2137                 outputNumInput(&(t->num), c);
2138                 
2139                 sprintf(str, "Warp: %s", c);
2140         }
2141         else {
2142                 /* default header print */
2143                 sprintf(str, "Warp: %.3f", circumfac);
2144         }
2145         
2146         circumfac*= (float)(-M_PI/360.0);
2147         
2148         for(i = 0; i < t->total; i++, td++) {
2149                 float loc[3];
2150                 if (td->flag & TD_NOACTION)
2151                         break;
2152                 
2153                 if (td->flag & TD_SKIP)
2154                         continue;
2155                 
2156                 /* translate point to center, rotate in such a way that outline==distance */
2157                 VECCOPY(vec, td->iloc);
2158                 mul_m3_v3(td->mtx, vec);
2159                 mul_m4_v3(t->viewmat, vec);
2160                 sub_v3_v3v3(vec, vec, t->viewmat[3]);
2161                 
2162                 dist= vec[0]-cursor[0];
2163                 
2164                 /* t->val is X dimension projected boundbox */
2165                 phi0= (circumfac*dist/t->val);
2166                 
2167                 vec[1]= (vec[1]-cursor[1]);
2168                 
2169                 co= (float)cos(phi0);
2170                 si= (float)sin(phi0);
2171                 loc[0]= -si*vec[1]+cursor[0];
2172                 loc[1]= co*vec[1]+cursor[1];
2173                 loc[2]= vec[2];
2174                 
2175                 mul_m4_v3(t->viewinv, loc);
2176                 sub_v3_v3v3(loc, loc, t->viewinv[3]);
2177                 mul_m3_v3(td->smtx, loc);
2178                 
2179                 sub_v3_v3v3(loc, loc, td->iloc);
2180                 mul_v3_fl(loc, td->factor);
2181                 add_v3_v3v3(td->loc, td->iloc, loc);
2182         }
2183         
2184         recalcData(t);
2185         
2186         ED_area_headerprint(t->sa, str);
2187         
2188         return 1;
2189 }
2190
2191 /* ************************** SHEAR *************************** */
2192
2193 void initShear(TransInfo *t)
2194 {
2195         t->mode = TFM_SHEAR;
2196         t->transform = Shear;
2197         t->handleEvent = handleEventShear;
2198         
2199         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2200         
2201         t->idx_max = 0;
2202         t->num.idx_max = 0;
2203         t->snap[0] = 0.0f;
2204         t->snap[1] = 0.1f;
2205         t->snap[2] = t->snap[1] * 0.1f;
2206         
2207         t->flag |= T_NO_CONSTRAINT;
2208 }
2209
2210 int handleEventShear(TransInfo *t, wmEvent *event)
2211 {
2212         int status = 0;
2213         
2214         if (event->type == MIDDLEMOUSE && event->val==KM_PRESS)
2215         {
2216                 // Use customData pointer to signal Shear direction
2217                 if      (t->customData == 0)
2218                 {
2219                         initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
2220                         t->customData = (void*)1;
2221                 }
2222                 else
2223                 {
2224                         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2225                         t->customData = 0;
2226                 }
2227                 
2228                 status = 1;
2229         }
2230         
2231         return status;
2232 }
2233
2234
2235 int Shear(TransInfo *t, short mval[2])
2236 {
2237         TransData *td = t->data;
2238         float vec[3];
2239         float smat[3][3], tmat[3][3], totmat[3][3], persmat[3][3], persinv[3][3];
2240         float value;
2241         int i;
2242         char str[50];
2243         
2244         copy_m3_m4(persmat, t->viewmat);
2245         invert_m3_m3(persinv, persmat);
2246         
2247         value = 0.05f * t->values[0];
2248         
2249         snapGrid(t, &value);
2250         
2251         applyNumInput(&t->num, &value);
2252         
2253         /* header print for NumInput */
2254         if (hasNumInput(&t->num)) {
2255                 char c[20];
2256                 
2257                 outputNumInput(&(t->num), c);
2258                 
2259                 sprintf(str, "Shear: %s %s", c, t->proptext);
2260         }
2261         else {
2262                 /* default header print */
2263                 sprintf(str, "Shear: %.3f %s", value, t->proptext);
2264         }
2265         
2266         unit_m3(smat);
2267         
2268         // Custom data signals shear direction
2269         if (t->customData == 0)
2270                 smat[1][0] = value;
2271         else
2272                 smat[0][1] = value;
2273         
2274         mul_m3_m3m3(tmat, smat, persmat);
2275         mul_m3_m3m3(totmat, persinv, tmat);
2276         
2277         for(i = 0 ; i < t->total; i++, td++) {
2278                 if (td->flag & TD_NOACTION)
2279                         break;
2280                 
2281                 if (td->flag & TD_SKIP)
2282                         continue;
2283                 
2284                 if (t->obedit) {
2285                         float mat3[3][3];
2286                         mul_m3_m3m3(mat3, totmat, td->mtx);
2287                         mul_m3_m3m3(tmat, td->smtx, mat3);
2288                 }
2289                 else {
2290                         copy_m3_m3(tmat, totmat);
2291                 }
2292                 sub_v3_v3v3(vec, td->center, t->center);
2293                 
2294                 mul_m3_v3(tmat, vec);
2295                 
2296                 add_v3_v3v3(vec, vec, t->center);
2297                 sub_v3_v3v3(vec, vec, td->center);
2298                 
2299                 mul_v3_fl(vec, td->factor);
2300                 
2301                 add_v3_v3v3(td->loc, td->iloc, vec);
2302         }
2303         
2304         recalcData(t);
2305         
2306         ED_area_headerprint(t->sa, str);
2307
2308         return 1;
2309 }
2310
2311 /* ************************** RESIZE *************************** */
2312
2313 void initResize(TransInfo *t)
2314 {
2315         t->mode = TFM_RESIZE;
2316         t->transform = Resize;
2317         
2318         initMouseInputMode(t, &t->mouse, INPUT_SPRING_FLIP);
2319         
2320         t->flag |= T_NULL_ONE;
2321         t->num.flag |= NUM_NULL_ONE;
2322         t->num.flag |= NUM_AFFECT_ALL;
2323         if (!t->obedit) {
2324                 t->flag |= T_NO_ZERO;
2325                 t->num.flag |= NUM_NO_ZERO;
2326         }
2327         
2328         t->idx_max = 2;
2329         t->num.idx_max = 2;
2330         t->snap[0] = 0.0f;
2331         t->snap[1] = 0.1f;
2332         t->snap[2] = t->snap[1] * 0.1f;
2333 }
2334
2335 static void headerResize(TransInfo *t, float vec[3], char *str) {
2336         char tvec[60];
2337         if (hasNumInput(&t->num)) {
2338                 outputNumInput(&(t->num), tvec);
2339         }
2340         else {
2341                 sprintf(&tvec[0], "%.4f", vec[0]);
2342                 sprintf(&tvec[20], "%.4f", vec[1]);
2343                 sprintf(&tvec[40], "%.4f", vec[2]);
2344         }
2345         
2346         if (t->con.mode & CON_APPLY) {
2347                 switch(t->num.idx_max) {
2348                 case 0:
2349                         sprintf(str, "Scale: %s%s %s", &tvec[0], t->con.text, t->proptext);
2350                         break;
2351                 case 1:
2352                         sprintf(str, "Scale: %s : %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2353                         break;
2354                 case 2:
2355                         sprintf(str, "Scale: %s : %s : %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2356                 }
2357         }
2358         else {
2359                 if (t->flag & T_2D_EDIT)
2360                         sprintf(str, "Scale X: %s   Y: %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2361                 else
2362                         sprintf(str, "Scale X: %s   Y: %s  Z: %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2363         }
2364 }
2365
2366 #define SIGN(a)         (a<-FLT_EPSILON?1:a>FLT_EPSILON?2:3)
2367 #define VECSIGNFLIP(a, b) ((SIGN(a[0]) & SIGN(b[0]))==0 || (SIGN(a[1]) & SIGN(b[1]))==0 || (SIGN(a[2]) & SIGN(b[2]))==0)
2368
2369 /* smat is reference matrix, only scaled */
2370 static void TransMat3ToSize( float mat[][3], float smat[][3], float *size)
2371 {
2372         float vec[3];
2373         
2374         copy_v3_v3(vec, mat[0]);
2375         size[0]= normalize_v3(vec);
2376         copy_v3_v3(vec, mat[1]);
2377         size[1]= normalize_v3(vec);
2378         copy_v3_v3(vec, mat[2]);
2379         size[2]= normalize_v3(vec);
2380         
2381         /* first tried with dotproduct... but the sign flip is crucial */
2382         if( VECSIGNFLIP(mat[0], smat[0]) ) size[0]= -size[0];
2383         if( VECSIGNFLIP(mat[1], smat[1]) ) size[1]= -size[1];
2384         if( VECSIGNFLIP(mat[2], smat[2]) ) size[2]= -size[2];
2385 }
2386
2387
2388 static void ElementResize(TransInfo *t, TransData *td, float mat[3][3]) {
2389         float tmat[3][3], smat[3][3], center[3];
2390         float vec[3];
2391         
2392         if (t->flag & T_EDIT) {
2393                 mul_m3_m3m3(smat, mat, td->mtx);
2394                 mul_m3_m3m3(tmat, td->smtx, smat);
2395         }
2396         else {
2397                 copy_m3_m3(tmat, mat);
2398         }
2399         
2400         if (t->con.applySize) {
2401                 t->con.applySize(t, td, tmat);
2402         }
2403         
2404         /* local constraint shouldn't alter center */
2405         if (t->around == V3D_LOCAL) {
2406                 if (t->flag & T_OBJECT) {
2407                         VECCOPY(center, td->center);
2408                 }
2409                 else if (t->flag & T_EDIT) {
2410                         
2411                         if(t->around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
2412                                 VECCOPY(center, td->center);
2413                         }
2414                         else {
2415                                 VECCOPY(center, t->center);
2416                         }
2417                 }
2418                 else {
2419                         VECCOPY(center, t->center);
2420                 }
2421         }
2422         else {
2423                 VECCOPY(center, t->center);
2424         }
2425         
2426         if (td->ext) {
2427                 float fsize[3];
2428                 
2429                 if (t->flag & (T_OBJECT|T_TEXTURE|T_POSE)) {
2430                         float obsizemat[3][3];
2431                         // Reorient the size mat to fit the oriented object.
2432                         mul_m3_m3m3(obsizemat, tmat, td->axismtx);
2433                         //print_m3("obsizemat", obsizemat);
2434                         TransMat3ToSize(obsizemat, td->axismtx, fsize);
2435                         //print_v3("fsize", fsize);
2436                 }
2437                 else {
2438                         mat3_to_size( fsize,tmat);
2439                 }
2440                 
2441                 protectedSizeBits(td->protectflag, fsize);
2442                 
2443                 if ((t->flag & T_V3D_ALIGN)==0) {       // align mode doesn't resize objects itself
2444                         if((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)){
2445                                 /* scale val and reset size */
2446                                 *td->val = td->ival * (1 + (fsize[0] - 1) * td->factor);
2447                                 
2448                                 td->ext->size[0] = td->ext->isize[0];
2449                                 td->ext->size[1] = td->ext->isize[1];
2450                                 td->ext->size[2] = td->ext->isize[2];
2451                         }
2452                         else {
2453                                 /* Reset val if SINGLESIZE but using a constraint */
2454                                 if (td->flag & TD_SINGLESIZE)
2455                                         *td->val = td->ival;
2456                                 
2457                                 td->ext->size[0] = td->ext->isize[0] * (1 + (fsize[0] - 1) * td->factor);
2458                                 td->ext->size[1] = td->ext->isize[1] * (1 + (fsize[1] - 1) * td->factor);
2459                                 td->ext->size[2] = td->ext->isize[2] * (1 + (fsize[2] - 1) * td->factor);
2460                         }
2461                 }
2462                 
2463                 constraintSizeLim(t, td);
2464         }
2465         
2466         /* For individual element center, Editmode need to use iloc */
2467         if (t->flag & T_POINTS)
2468                 sub_v3_v3v3(vec, td->iloc, center);
2469         else
2470                 sub_v3_v3v3(vec, td->center, center);
2471         
2472         mul_m3_v3(tmat, vec);
2473         
2474         add_v3_v3v3(vec, vec, center);
2475         if (t->flag & T_POINTS)
2476                 sub_v3_v3v3(vec, vec, td->iloc);
2477         else
2478                 sub_v3_v3v3(vec, vec, td->center);
2479         
2480         mul_v3_fl(vec, td->factor);
2481         
2482         if (t->flag & (T_OBJECT|T_POSE)) {
2483                 mul_m3_v3(td->smtx, vec);
2484         }
2485         
2486         protectedTransBits(td->protectflag, vec);
2487         add_v3_v3v3(td->loc, td->iloc, vec);
2488         
2489         constraintTransLim(t, td);
2490 }
2491
2492 int Resize(TransInfo *t, short mval[2])
2493 {
2494         TransData *td;
2495         float size[3], mat[3][3];
2496         float ratio;
2497         int i;
2498         char str[200];
2499         
2500         /* for manipulator, center handle, the scaling can't be done relative to center */
2501         if( (t->flag & T_USES_MANIPULATOR) && t->con.mode==0)
2502         {
2503                 ratio = 1.0f - ((t->imval[0] - mval[0]) + (t->imval[1] - mval[1]))/100.0f;
2504         }
2505         else
2506         {
2507                 ratio = t->values[0];
2508         }
2509         
2510         size[0] = size[1] = size[2] = ratio;
2511         
2512         snapGrid(t, size);
2513         
2514         if (hasNumInput(&t->num)) {
2515                 applyNumInput(&t->num, size);
2516                 constraintNumInput(t, size);
2517         }
2518         
2519         applySnapping(t, size);
2520         
2521         if (t->flag & T_AUTOVALUES)
2522         {
2523                 VECCOPY(size, t->auto_values);
2524         }
2525         
2526         VECCOPY(t->values, size);
2527         
2528         size_to_mat3( mat,size);
2529         
2530         if (t->con.applySize) {
2531                 t->con.applySize(t, NULL, mat);
2532         }
2533         
2534         copy_m3_m3(t->mat, mat);        // used in manipulator
2535         
2536         headerResize(t, size, str);
2537         
2538         for(i = 0, td=t->data; i < t->total; i++, td++) {
2539                 if (td->flag & TD_NOACTION)
2540                         break;
2541                 
2542                 if (td->flag & TD_SKIP)
2543                         continue;
2544                 
2545                 ElementResize(t, td, mat);
2546         }
2547         
2548         /* evil hack - redo resize if cliping needed */
2549         if (t->flag & T_CLIP_UV && clipUVTransform(t, size, 1)) {
2550                 size_to_mat3( mat,size);
2551                 
2552                 if (t->con.applySize)
2553                         t->con.applySize(t, NULL, mat);
2554                 
2555                 for(i = 0, td=t->data; i < t->total; i++, td++)
2556                         ElementResize(t, td, mat);
2557         }
2558         
2559         recalcData(t);
2560         
2561         ED_area_headerprint(t->sa, str);
2562         
2563         return 1;
2564 }
2565
2566 /* ************************** TOSPHERE *************************** */
2567
2568 void initToSphere(TransInfo *t)
2569 {
2570         TransData *td = t->data;
2571         int i;
2572         
2573         t->mode = TFM_TOSPHERE;
2574         t->transform = ToSphere;
2575         
2576         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
2577         
2578         t->idx_max = 0;
2579         t->num.idx_max = 0;
2580         t->snap[0] = 0.0f;
2581         t->snap[1] = 0.1f;
2582         t->snap[2] = t->snap[1] * 0.1f;
2583         
2584         t->num.flag |= NUM_NULL_ONE | NUM_NO_NEGATIVE;
2585         t->flag |= T_NO_CONSTRAINT;
2586         
2587         // Calculate average radius
2588         for(i = 0 ; i < t->total; i++, td++) {
2589                 t->val += len_v3v3(t->center, td->iloc);
2590         }
2591         
2592         t->val /= (float)t->total;
2593 }
2594
2595 int ToSphere(TransInfo *t, short mval[2])
2596 {
2597         float vec[3];
2598         float ratio, radius;
2599         int i;
2600         char str[64];
2601         TransData *td = t->data;
2602         
2603         ratio = t->values[0];
2604         
2605         snapGrid(t, &ratio);
2606         
2607         applyNumInput(&t->num, &ratio);
2608         
2609         if (ratio < 0)
2610                 ratio = 0.0f;
2611         else if (ratio > 1)
2612                 ratio = 1.0f;
2613         
2614         /* header print for NumInput */
2615         if (hasNumInput(&t->num)) {
2616                 char c[20];
2617                 
2618                 outputNumInput(&(t->num), c);
2619                 
2620                 sprintf(str, "To Sphere: %s %s", c, t->proptext);
2621         }
2622         else {
2623                 /* default header print */
2624                 sprintf(str, "To Sphere: %.4f %s", ratio, t->proptext);
2625         }
2626         
2627         
2628         for(i = 0 ; i < t->total; i++, td++) {
2629                 float tratio;
2630                 if (td->flag & TD_NOACTION)
2631                         break;
2632                 
2633                 if (td->flag & TD_SKIP)
2634                         continue;
2635                 
2636                 sub_v3_v3v3(vec, td->iloc, t->center);
2637                 
2638                 radius = normalize_v3(vec);
2639                 
2640                 tratio = ratio * td->factor;
2641                 
2642                 mul_v3_fl(vec, radius * (1.0f - tratio) + t->val * tratio);
2643                 
2644                 add_v3_v3v3(td->loc, t->center, vec);
2645         }
2646         
2647         
2648         recalcData(t);
2649         
2650         ED_area_headerprint(t->sa, str);
2651         
2652         return 1;
2653 }
2654
2655 /* ************************** ROTATION *************************** */
2656
2657
2658 void initRotation(TransInfo *t)
2659 {
2660         t->mode = TFM_ROTATION;
2661         t->transform = Rotation;
2662         
2663         initMouseInputMode(t, &t->mouse, INPUT_ANGLE);
2664         
2665         t->ndof.axis = 16;
2666         /* Scale down and flip input for rotation */
2667         t->ndof.factor[0] = -0.2f;
2668         
2669         t->idx_max = 0;
2670         t->num.idx_max = 0;
2671         t->snap[0] = 0.0f;
2672         t->snap[1] = (float)((5.0/180)*M_PI);
2673         t->snap[2] = t->snap[1] * 0.2f;
2674         
2675         if (t->flag & T_2D_EDIT)
2676                 t->flag |= T_NO_CONSTRAINT;
2677
2678         VECCOPY(t->axis, t->viewinv[2]);
2679         mul_v3_fl(t->axis, -1.0f);
2680         normalize_v3(t->axis);
2681 }
2682
2683 static void ElementRotation(TransInfo *t, TransData *td, float mat[3][3], short around) {
2684         float vec[3], totmat[3][3], smat[3][3];
2685         float eul[3], fmat[3][3], quat[4];
2686         float *center = t->center;
2687         
2688         /* local constraint shouldn't alter center */
2689         if (around == V3D_LOCAL) {
2690                 if (t->flag & (T_OBJECT|T_POSE)) {
2691                         center = td->center;
2692                 }
2693                 else {
2694                         if(around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
2695                                 center = td->center;
2696                         }
2697                 }
2698         }
2699         
2700         if (t->flag & T_POINTS) {
2701                 mul_m3_m3m3(totmat, mat, td->mtx);
2702                 mul_m3_m3m3(smat, td->smtx, totmat);
2703                 
2704                 sub_v3_v3v3(vec, td->iloc, center);
2705                 mul_m3_v3(smat, vec);
2706                 
2707                 add_v3_v3v3(td->loc, vec, center);
2708                 
2709                 sub_v3_v3v3(vec,td->loc,td->iloc);
2710                 protectedTransBits(td->protectflag, vec);
2711                 add_v3_v3v3(td->loc, td->iloc, vec);
2712                 
2713                 
2714                 if(td->flag & TD_USEQUAT) {
2715                         mul_serie_m3(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2716                         mat3_to_quat( quat,fmat);       // Actual transform
2717                         
2718                         if(td->ext->quat){
2719                                 mul_qt_qtqt(td->ext->quat, quat, td->ext->iquat);
2720                                 
2721                                 /* is there a reason not to have this here? -jahka */
2722                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2723                         }
2724                 }
2725         }
2726         /**
2727          * HACK WARNING
2728          *
2729          * This is some VERY ugly special case to deal with pose mode.
2730          *
2731          * The problem is that mtx and smtx include each bone orientation.
2732          *
2733          * That is needed to rotate each bone properly, HOWEVER, to calculate
2734          * the translation component, we only need the actual armature object's
2735          * matrix (and inverse). That is not all though. Once the proper translation
2736          * has been computed, it has to be converted back into the bone's space.
2737          */
2738         else if (t->flag & T_POSE) {
2739                 float pmtx[3][3], imtx[3][3];
2740                 
2741                 // Extract and invert armature object matrix
2742                 copy_m3_m4(pmtx, t->poseobj->obmat);
2743                 invert_m3_m3(imtx, pmtx);
2744                 
2745                 if ((td->flag & TD_NO_LOC) == 0)
2746                 {
2747                         sub_v3_v3v3(vec, td->center, center);
2748                         
2749                         mul_m3_v3(pmtx, vec);   // To Global space
2750                         mul_m3_v3(mat, vec);            // Applying rotation
2751                         mul_m3_v3(imtx, vec);   // To Local space
2752                         
2753                         add_v3_v3v3(vec, vec, center);
2754                         /* vec now is the location where the object has to be */
2755                         
2756                         sub_v3_v3v3(vec, vec, td->center); // Translation needed from the initial location
2757                         
2758                         mul_m3_v3(pmtx, vec);   // To Global space
2759                         mul_m3_v3(td->smtx, vec);// To Pose space
2760                         
2761                         protectedTransBits(td->protectflag, vec);
2762                         
2763                         add_v3_v3v3(td->loc, td->iloc, vec);
2764                         
2765                         constraintTransLim(t, td);
2766                 }
2767                 
2768                 /* rotation */
2769                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2770                         /* euler or quaternion/axis-angle? */
2771                         if (td->rotOrder == ROT_MODE_QUAT) {
2772                                 mul_serie_m3(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2773                                 
2774                                 mat3_to_quat( quat,fmat);       // Actual transform
2775                                 
2776                                 mul_qt_qtqt(td->ext->quat, quat, td->ext->iquat);
2777                                 /* this function works on end result */
2778                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2779                                 
2780                         }
2781                         else if (td->rotOrder == ROT_MODE_AXISANGLE) {
2782                                 /* calculate effect based on quats */
2783                                 float iquat[4], tquat[4];
2784                                 
2785                                 axis_angle_to_quat(iquat, td->ext->irotAxis, td->ext->irotAngle);
2786                                 
2787                                 mul_serie_m3(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2788                                 mat3_to_quat( quat,fmat);       // Actual transform
2789                                 mul_qt_qtqt(tquat, quat, iquat);
2790                                 
2791                                 quat_to_axis_angle( td->ext->rotAxis, td->ext->rotAngle,tquat); 
2792                                 
2793                                 /* this function works on end result */
2794                                 protectedAxisAngleBits(td->protectflag, td->ext->rotAxis, td->ext->rotAngle, td->ext->irotAxis, td->ext->irotAngle);
2795                         }
2796                         else { 
2797                                 float eulmat[3][3];
2798                                 
2799                                 mul_m3_m3m3(totmat, mat, td->mtx);
2800                                 mul_m3_m3m3(smat, td->smtx, totmat);
2801                                 
2802                                 /* calculate the total rotatation in eulers */
2803                                 VECCOPY(eul, td->ext->irot);
2804                                 eulO_to_mat3( eulmat,eul, td->rotOrder);
2805                                 
2806                                 /* mat = transform, obmat = bone rotation */
2807                                 mul_m3_m3m3(fmat, smat, eulmat);
2808                                 
2809                                 mat3_to_compatible_eulO( eul, td->ext->rot, td->rotOrder,fmat);
2810                                 
2811                                 /* and apply (to end result only) */
2812                                 protectedRotateBits(td->protectflag, eul, td->ext->irot);
2813                                 VECCOPY(td->ext->rot, eul);
2814                         }
2815                         
2816                         constraintRotLim(t, td);
2817                 }
2818         }
2819         else {
2820                 if ((td->flag & TD_NO_LOC) == 0)
2821                 {
2822                         /* translation */
2823                         sub_v3_v3v3(vec, td->center, center);
2824                         mul_m3_v3(mat, vec);
2825                         add_v3_v3v3(vec, vec, center);
2826                         /* vec now is the location where the object has to be */
2827                         sub_v3_v3v3(vec, vec, td->center);
2828                         mul_m3_v3(td->smtx, vec);
2829                         
2830                         protectedTransBits(td->protectflag, vec);
2831                         
2832                         add_v3_v3v3(td->loc, td->iloc, vec);
2833                 }
2834                 
2835                 
2836                 constraintTransLim(t, td);
2837                 
2838                 /* rotation */
2839                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2840                         /* euler or quaternion? */
2841                     if ((td->rotOrder == ROT_MODE_QUAT) || (td->flag & TD_USEQUAT)) {
2842                                 mul_serie_m3(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2843                                 mat3_to_quat( quat,fmat);       // Actual transform
2844                                 
2845                                 mul_qt_qtqt(td->ext->quat, quat, td->ext->iquat);
2846                                 /* this function works on end result */
2847                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2848                         }
2849                         else if (td->rotOrder == ROT_MODE_AXISANGLE) {
2850                                 /* calculate effect based on quats */
2851                                 float iquat[4], tquat[4];
2852                                 
2853                                 axis_angle_to_quat(iquat, td->ext->irotAxis, td->ext->irotAngle);
2854                                 
2855                                 mul_serie_m3(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2856                                 mat3_to_quat( quat,fmat);       // Actual transform
2857                                 mul_qt_qtqt(tquat, quat, iquat);
2858                                 
2859                                 quat_to_axis_angle( td->ext->rotAxis, td->ext->rotAngle,quat); 
2860                                 
2861                                 /* this function works on end result */
2862                                 protectedAxisAngleBits(td->protectflag, td->ext->rotAxis, td->ext->rotAngle, td->ext->irotAxis, td->ext->irotAngle);
2863                         }
2864                         else {
2865                                 float obmat[3][3];
2866                                 
2867                                 mul_m3_m3m3(totmat, mat, td->mtx);
2868                                 mul_m3_m3m3(smat, td->smtx, totmat);
2869                                 
2870                                 /* calculate the total rotatation in eulers */
2871                                 add_v3_v3v3(eul, td->ext->irot, td->ext->drot); /* we have to correct for delta rot */
2872                                 eulO_to_mat3( obmat,eul, td->rotOrder);
2873                                 /* mat = transform, obmat = object rotation */
2874                                 mul_m3_m3m3(fmat, smat, obmat);
2875                                 
2876                                 mat3_to_compatible_eulO( eul, td->ext->rot, td->rotOrder,fmat);
2877                                 
2878                                 /* correct back for delta rot */
2879                                 sub_v3_v3v3(eul, eul, td->ext->drot);
2880                                 
2881                                 /* and apply */
2882                                 protectedRotateBits(td->protectflag, eul, td->ext->irot);
2883                                 VECCOPY(td->ext->rot, eul);
2884                         }
2885                         
2886                         constraintRotLim(t, td);
2887                 }
2888         }
2889 }
2890
2891 static void applyRotation(TransInfo *t, float angle, float axis[3])
2892 {
2893         TransData *td = t->data;
2894         float mat[3][3];
2895         int i;
2896         
2897         vec_rot_to_mat3( mat,axis, angle);
2898         
2899         for(i = 0 ; i < t->total; i++, td++) {
2900                 
2901                 if (td->flag & TD_NOACTION)
2902                         break;
2903                 
2904                 if (td->flag & TD_SKIP)
2905                         continue;
2906                 
2907                 if (t->con.applyRot) {
2908                         t->con.applyRot(t, td, axis, NULL);
2909                         vec_rot_to_mat3( mat,axis, angle * td->factor);
2910                 }
2911                 else if (t->flag & T_PROP_EDIT) {
2912                         vec_rot_to_mat3( mat,axis, angle * td->factor);
2913                 }
2914                 
2915                 ElementRotation(t, td, mat, t->around);
2916         }
2917 }
2918
2919 int Rotation(TransInfo *t, short mval[2])
2920 {
2921         char str[64];
2922         
2923         float final;
2924         
2925         float mat[3][3];
2926         
2927         final = t->values[0];
2928         
2929         applyNDofInput(&t->ndof, &final);
2930         
2931         snapGrid(t, &final);
2932         
2933         if (t->con.applyRot) {
2934                 t->con.applyRot(t, NULL, t->axis, &final);
2935         }
2936         
2937         applySnapping(t, &final);
2938         
2939         if (hasNumInput(&t->num)) {
2940                 char c[20];
2941                 
2942                 applyNumInput(&t->num, &final);
2943                 
2944                 outputNumInput(&(t->num),