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