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