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