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