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