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