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