minor improvement to vector api use, replace add, multiply by 0.5 with mid_v3_v3v3
[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                 if (t->modifiers & MOD_CONSTRAINT_SELECT)
836                         t->con.mode |= CON_SELECT;
837
838                 copy_v2_v2_int(t->mval, event->mval);
839
840                 // t->redraw |= TREDRAW_SOFT; /* Use this for soft redraw. Might cause flicker in object mode */
841                 t->redraw |= TREDRAW_HARD;
842
843
844                 if (t->state == TRANS_STARTING) {
845                         t->state = TRANS_RUNNING;
846                 }
847
848                 applyMouseInput(t, &t->mouse, t->mval, t->values);
849
850                 // Snapping mouse move events
851                 t->redraw |= handleSnapping(t, event);
852         }
853
854         /* handle modal keymap first */
855         if (event->type == EVT_MODAL_MAP) {
856                 switch (event->val) {
857                         case TFM_MODAL_CANCEL:
858                                 t->state = TRANS_CANCEL;
859                                 break;
860                         case TFM_MODAL_CONFIRM:
861                                 t->state = TRANS_CONFIRM;
862                                 break;
863                         case TFM_MODAL_TRANSLATE:
864                                 /* only switch when... */
865                                 if (ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL) ) {
866                                         resetTransRestrictions(t);
867                                         restoreTransObjects(t);
868                                         initTranslation(t);
869                                         initSnapping(t, NULL); // need to reinit after mode change
870                                         t->redraw |= TREDRAW_HARD;
871                                 }
872                                 else if (t->mode == TFM_TRANSLATION) {
873                                         if (t->options & (CTX_MOVIECLIP | CTX_MASK)) {
874                                                 restoreTransObjects(t);
875
876                                                 t->flag ^= T_ALT_TRANSFORM;
877                                                 t->redraw |= TREDRAW_HARD;
878                                         }
879                                 }
880                                 break;
881                         case TFM_MODAL_ROTATE:
882                                 /* only switch when... */
883                                 if (!(t->options & CTX_TEXTURE) && !(t->options & (CTX_MOVIECLIP | CTX_MASK))) {
884                                         if (ELEM4(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL, TFM_TRANSLATION) ) {
885                                                 
886                                                 resetTransRestrictions(t);
887                                                 
888                                                 if (t->mode == TFM_ROTATION) {
889                                                         restoreTransObjects(t);
890                                                         initTrackball(t);
891                                                 }
892                                                 else {
893                                                         restoreTransObjects(t);
894                                                         initRotation(t);
895                                                 }
896                                                 initSnapping(t, NULL); // need to reinit after mode change
897                                                 t->redraw |= TREDRAW_HARD;
898                                         }
899                                 }
900                                 break;
901                         case TFM_MODAL_RESIZE:
902                                 /* only switch when... */
903                                 if (ELEM3(t->mode, TFM_ROTATION, TFM_TRANSLATION, TFM_TRACKBALL) ) {
904                                         resetTransRestrictions(t);
905                                         restoreTransObjects(t);
906                                         initResize(t);
907                                         initSnapping(t, NULL); // need to reinit after mode change
908                                         t->redraw |= TREDRAW_HARD;
909                                 }
910                                 else if (t->mode == TFM_RESIZE) {
911                                         if (t->options & CTX_MOVIECLIP) {
912                                                 restoreTransObjects(t);
913
914                                                 t->flag ^= T_ALT_TRANSFORM;
915                                                 t->redraw |= TREDRAW_HARD;
916                                         }
917                                 }
918                                 break;
919                                 
920                         case TFM_MODAL_SNAP_INV_ON:
921                                 t->modifiers |= MOD_SNAP_INVERT;
922                                 t->redraw |= TREDRAW_HARD;
923                                 break;
924                         case TFM_MODAL_SNAP_INV_OFF:
925                                 t->modifiers &= ~MOD_SNAP_INVERT;
926                                 t->redraw |= TREDRAW_HARD;
927                                 break;
928                         case TFM_MODAL_SNAP_TOGGLE:
929                                 t->modifiers ^= MOD_SNAP;
930                                 t->redraw |= TREDRAW_HARD;
931                                 break;
932                         case TFM_MODAL_AXIS_X:
933                                 if ((t->flag & T_NO_CONSTRAINT) == 0) {
934                                         if (cmode == 'X') {
935                                                 stopConstraint(t);
936                                         }
937                                         else {
938                                                 if (t->flag & T_2D_EDIT) {
939                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS0), "along X");
940                                                 }
941                                                 else {
942                                                         setUserConstraint(t, t->current_orientation, (CON_AXIS0), "along %s X");
943                                                 }
944                                         }
945                                         t->redraw |= TREDRAW_HARD;
946                                 }
947                                 break;
948                         case TFM_MODAL_AXIS_Y:
949                                 if ((t->flag & T_NO_CONSTRAINT) == 0) {
950                                         if (cmode == 'Y') {
951                                                 stopConstraint(t);
952                                         }
953                                         else {
954                                                 if (t->flag & T_2D_EDIT) {
955                                                         setUserConstraint(t, V3D_MANIP_GLOBAL, (CON_AXIS1), "along Y");
956                                                 }
957                                                 else {
958                                                         setUserConstraint(t, t->current_orientation, (CON_AXIS1), "along %s Y");
959                                                 }
960                                         }
961                                         t->redraw |= TREDRAW_HARD;
962                                 }
963                                 break;
964                         case TFM_MODAL_AXIS_Z:
965                                 if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) {
966                                         if (cmode == 'Z') {
967                                                 stopConstraint(t);
968                                         }
969                                         else {
970                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS2), "along %s Z");
971                                         }
972                                         t->redraw |= TREDRAW_HARD;
973                                 }
974                                 break;
975                         case TFM_MODAL_PLANE_X:
976                                 if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) {
977                                         if (cmode == 'X') {
978                                                 stopConstraint(t);
979                                         }
980                                         else {
981                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS1 | CON_AXIS2), "locking %s X");
982                                         }
983                                         t->redraw |= TREDRAW_HARD;
984                                 }
985                                 break;
986                         case TFM_MODAL_PLANE_Y:
987                                 if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) {
988                                         if (cmode == 'Y') {
989                                                 stopConstraint(t);
990                                         }
991                                         else {
992                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS0 | CON_AXIS2), "locking %s Y");
993                                         }
994                                         t->redraw |= TREDRAW_HARD;
995                                 }
996                                 break;
997                         case TFM_MODAL_PLANE_Z:
998                                 if ((t->flag & (T_NO_CONSTRAINT | T_2D_EDIT)) == 0) {
999                                         if (cmode == 'Z') {
1000                                                 stopConstraint(t);
1001                                         }
1002                                         else {
1003                                                 setUserConstraint(t, t->current_orientation, (CON_AXIS0 | CON_AXIS1), "locking %s Z");
1004                                         }
1005                                         t->redraw |= TREDRAW_HARD;
1006                                 }
1007                                 break;
1008                         case TFM_MODAL_CONS_OFF:
1009                                 if ((t->flag & T_NO_CONSTRAINT) == 0) {
1010                                         stopConstraint(t);
1011                                         t->redraw |= TREDRAW_HARD;
1012                                 }
1013                                 break;
1014                         case TFM_MODAL_ADD_SNAP:
1015                                 addSnapPoint(t);
1016                                 t->redraw |= TREDRAW_HARD;
1017                                 break;
1018                         case TFM_MODAL_REMOVE_SNAP:
1019                                 removeSnapPoint(t);
1020                                 t->redraw |= TREDRAW_HARD;
1021                                 break;
1022                         case TFM_MODAL_PROPSIZE_UP:
1023                                 if (t->flag & T_PROP_EDIT) {
1024                                         t->prop_size *= 1.1f;
1025                                         if (t->spacetype == SPACE_VIEW3D && t->persp != RV3D_ORTHO)
1026                                                 t->prop_size = min_ff(t->prop_size, ((View3D *)t->view)->far);
1027                                         calculatePropRatio(t);
1028                                 }
1029                                 t->redraw |= TREDRAW_HARD;
1030                                 break;
1031                         case TFM_MODAL_PROPSIZE_DOWN:
1032                                 if (t->flag & T_PROP_EDIT) {
1033                                         t->prop_size *= 0.90909090f;
1034                                         calculatePropRatio(t);
1035                                 }
1036                                 t->redraw |= TREDRAW_HARD;
1037                                 break;
1038                         case TFM_MODAL_EDGESLIDE_UP:
1039                         case TFM_MODAL_EDGESLIDE_DOWN:
1040                                 t->redraw |= TREDRAW_HARD;
1041                                 break;
1042                         case TFM_MODAL_AUTOIK_LEN_INC:
1043                                 if (t->flag & T_AUTOIK)
1044                                         transform_autoik_update(t, 1);
1045                                 t->redraw |= TREDRAW_HARD;
1046                                 break;
1047                         case TFM_MODAL_AUTOIK_LEN_DEC:
1048                                 if (t->flag & T_AUTOIK) 
1049                                         transform_autoik_update(t, -1);
1050                                 t->redraw |= TREDRAW_HARD;
1051                                 break;
1052                         default:
1053                                 handled = 0;
1054                                 break;
1055                 }
1056
1057                 // Modal numinput events
1058                 t->redraw |= handleNumInput(&(t->num), event);
1059         }
1060         /* else do non-mapped events */
1061         else if (event->val == KM_PRESS) {
1062                 switch (event->type) {
1063                         case RIGHTMOUSE:
1064                                 t->state = TRANS_CANCEL;
1065                                 break;
1066                         /* enforce redraw of transform when modifiers are used */
1067                         case LEFTSHIFTKEY:
1068                         case RIGHTSHIFTKEY:
1069                                 t->modifiers |= MOD_CONSTRAINT_PLANE;
1070                                 t->redraw |= TREDRAW_HARD;
1071                                 break;
1072
1073                         case SPACEKEY:
1074                                 if ((t->spacetype == SPACE_VIEW3D) && event->alt) {
1075 #if 0 // TRANSFORM_FIX_ME
1076                                         int mval[2];
1077
1078                                         getmouseco_sc(mval);
1079                                         BIF_selectOrientation();
1080                                         calc_manipulator_stats(curarea);
1081                                         copy_m3_m4(t->spacemtx, G.vd->twmat);
1082                                         warp_pointer(mval[0], mval[1]);
1083 #endif
1084                                 }
1085                                 else {
1086                                         t->state = TRANS_CONFIRM;
1087                                 }
1088                                 break;
1089
1090                         case MIDDLEMOUSE:
1091                                 if ((t->flag & T_NO_CONSTRAINT) == 0) {
1092                                         /* exception for switching to dolly, or trackball, in camera view */
1093                                         if (t->flag & T_CAMERA) {
1094                                                 if (t->mode == TFM_TRANSLATION)
1095                                                         setLocalConstraint(t, (CON_AXIS2), "along local Z");
1096                                                 else if (t->mode == TFM_ROTATION) {
1097                                                         restoreTransObjects(t);
1098                                                         initTrackball(t);
1099                                                 }
1100                                         }
1101                                         else {
1102                                                 t->modifiers |= MOD_CONSTRAINT_SELECT;
1103                                                 if (t->con.mode & CON_APPLY) {
1104                                                         stopConstraint(t);
1105                                                 }
1106                                                 else {
1107                                                         if (event->shift) {
1108                                                                 initSelectConstraint(t, t->spacemtx);
1109                                                         }
1110                                                         else {
1111                                                                 /* bit hackish... but it prevents mmb select to print the orientation from menu */
1112                                                                 strcpy(t->spacename, "global");
1113                                                                 initSelectConstraint(t, mati);
1114                                                         }
1115                                                         postSelectConstraint(t);
1116                                                 }
1117                                         }
1118                                         t->redraw |= TREDRAW_HARD;
1119                                 }
1120                                 break;
1121                         case ESCKEY:
1122                                 t->state = TRANS_CANCEL;
1123                                 break;
1124                         case PADENTER:
1125                         case RETKEY:
1126                                 t->state = TRANS_CONFIRM;
1127                                 break;
1128                         case GKEY:
1129                                 /* only switch when... */
1130                                 if (ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL) ) {
1131                                         resetTransRestrictions(t);
1132                                         restoreTransObjects(t);
1133                                         initTranslation(t);
1134                                         initSnapping(t, NULL); // need to reinit after mode change
1135                                         t->redraw |= TREDRAW_HARD;
1136                                 }
1137                                 break;
1138                         case SKEY:
1139                                 /* only switch when... */
1140                                 if (ELEM3(t->mode, TFM_ROTATION, TFM_TRANSLATION, TFM_TRACKBALL) ) {
1141                                         resetTransRestrictions(t);
1142                                         restoreTransObjects(t);
1143                                         initResize(t);
1144                                         initSnapping(t, NULL); // need to reinit after mode change
1145                                         t->redraw |= TREDRAW_HARD;
1146                                 }
1147                                 break;
1148                         case RKEY:
1149                                 /* only switch when... */
1150                                 if (!(t->options & CTX_TEXTURE)) {
1151                                         if (ELEM4(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL, TFM_TRANSLATION) ) {
1152
1153                                                 resetTransRestrictions(t);
1154
1155                                                 if (t->mode == TFM_ROTATION) {
1156                                                         restoreTransObjects(t);
1157                                                         initTrackball(t);
1158                                                 }
1159                                                 else {
1160                                                         restoreTransObjects(t);
1161                                                         initRotation(t);
1162                                                 }
1163                                                 initSnapping(t, NULL); // need to reinit after mode change
1164                                                 t->redraw |= TREDRAW_HARD;
1165                                         }
1166                                 }
1167                                 break;
1168                         case CKEY:
1169                                 if (event->alt) {
1170                                         t->flag ^= T_PROP_CONNECTED;
1171                                         sort_trans_data_dist(t);
1172                                         calculatePropRatio(t);
1173                                         t->redraw = 1;
1174                                 }
1175                                 else {
1176                                         stopConstraint(t);
1177                                         t->redraw |= TREDRAW_HARD;
1178                                 }
1179                                 break;
1180                         case XKEY:
1181                         case YKEY:
1182                         case ZKEY:
1183                                 transform_event_xyz_constraint(t, event->type, cmode);
1184                                 break;
1185                         case OKEY:
1186                                 if (t->flag & T_PROP_EDIT && event->shift) {
1187                                         t->prop_mode = (t->prop_mode + 1) % PROP_MODE_MAX;
1188                                         calculatePropRatio(t);
1189                                         t->redraw |= TREDRAW_HARD;
1190                                 }
1191                                 break;
1192                         case PADPLUSKEY:
1193                                 if (event->alt && t->flag & T_PROP_EDIT) {
1194                                         t->prop_size *= 1.1f;
1195                                         if (t->spacetype == SPACE_VIEW3D && t->persp != RV3D_ORTHO)
1196                                                 t->prop_size = min_ff(t->prop_size, ((View3D *)t->view)->far);
1197                                         calculatePropRatio(t);
1198                                 }
1199                                 t->redraw = 1;
1200                                 break;
1201                         case PAGEUPKEY:
1202                         case WHEELDOWNMOUSE:
1203                                 if (t->flag & T_AUTOIK) {
1204                                         transform_autoik_update(t, 1);
1205                                 }
1206                                 else view_editmove(event->type);
1207                                 t->redraw = 1;
1208                                 break;
1209                         case PADMINUS:
1210                                 if (event->alt && t->flag & T_PROP_EDIT) {
1211                                         t->prop_size *= 0.90909090f;
1212                                         calculatePropRatio(t);
1213                                 }
1214                                 t->redraw = 1;
1215                                 break;
1216                         case PAGEDOWNKEY:
1217                         case WHEELUPMOUSE:
1218                                 if (t->flag & T_AUTOIK) {
1219                                         transform_autoik_update(t, -1);
1220                                 }
1221                                 else view_editmove(event->type);
1222                                 t->redraw = 1;
1223                                 break;
1224                         default:
1225                                 handled = 0;
1226                                 break;
1227                 }
1228
1229                 // Numerical input events
1230                 t->redraw |= handleNumInput(&(t->num), event);
1231
1232                 // Snapping key events
1233                 t->redraw |= handleSnapping(t, event);
1234
1235         }
1236         else if (event->val == KM_RELEASE) {
1237                 switch (event->type) {
1238                         case LEFTSHIFTKEY:
1239                         case RIGHTSHIFTKEY:
1240                                 t->modifiers &= ~MOD_CONSTRAINT_PLANE;
1241                                 t->redraw |= TREDRAW_HARD;
1242                                 break;
1243
1244                         case MIDDLEMOUSE:
1245                                 if ((t->flag & T_NO_CONSTRAINT) == 0) {
1246                                         t->modifiers &= ~MOD_CONSTRAINT_SELECT;
1247                                         postSelectConstraint(t);
1248                                         t->redraw |= TREDRAW_HARD;
1249                                 }
1250                                 break;
1251 //              case LEFTMOUSE:
1252 //              case RIGHTMOUSE:
1253 //                      if (WM_modal_tweak_exit(event, t->event_type))
1254 ////                    if (t->options & CTX_TWEAK)
1255 //                              t->state = TRANS_CONFIRM;
1256 //                      break;
1257                         default:
1258                                 handled = 0;
1259                                 break;
1260                 }
1261
1262                 /* confirm transform if launch key is released after mouse move */
1263                 if (t->flag & T_RELEASE_CONFIRM) {
1264                         /* XXX Keyrepeat bug in Xorg fucks this up, will test when fixed */
1265                         if (event->type == t->launch_event && (t->launch_event == LEFTMOUSE || t->launch_event == RIGHTMOUSE)) {
1266                                 t->state = TRANS_CONFIRM;
1267                         }
1268                 }
1269         }
1270         else
1271                 handled = 0;
1272
1273         // Per transform event, if present
1274         if (t->handleEvent)
1275                 t->redraw |= t->handleEvent(t, event);
1276
1277         if (handled || t->redraw) {
1278                 return 0;
1279         }
1280         else {
1281                 return OPERATOR_PASS_THROUGH;
1282         }
1283 }
1284
1285 int calculateTransformCenter(bContext *C, int centerMode, float cent3d[3], int cent2d[2])
1286 {
1287         TransInfo *t = MEM_callocN(sizeof(TransInfo), "TransInfo data");
1288         int success;
1289
1290         t->state = TRANS_RUNNING;
1291
1292         t->options = CTX_NONE;
1293
1294         t->mode = TFM_DUMMY;
1295
1296         initTransInfo(C, t, NULL, NULL);    // internal data, mouse, vectors
1297
1298         createTransData(C, t);              // make TransData structs from selection
1299
1300         t->around = centerMode;             // override userdefined mode
1301
1302         if (t->total == 0) {
1303                 success = FALSE;
1304         }
1305         else {
1306                 success = TRUE;
1307
1308                 calculateCenter(t);
1309
1310                 if (cent2d) {
1311                         copy_v2_v2_int(cent2d, t->center2d);
1312                 }
1313
1314                 if (cent3d) {
1315                         // Copy center from constraint center. Transform center can be local
1316                         copy_v3_v3(cent3d, t->con.center);
1317                 }
1318         }
1319
1320
1321         /* aftertrans does insert ipos and action channels, and clears base flags, doesnt read transdata */
1322         special_aftertrans_update(C, t);
1323
1324         postTrans(C, t);
1325
1326         MEM_freeN(t);
1327
1328         return success;
1329 }
1330
1331 typedef enum {
1332         UP,
1333         DOWN,
1334         LEFT,
1335         RIGHT
1336 } ArrowDirection;
1337 static void drawArrow(ArrowDirection d, short offset, short length, short size)
1338 {
1339         switch (d) {
1340                 case LEFT:
1341                         offset = -offset;
1342                         length = -length;
1343                         size = -size;
1344                 case RIGHT:
1345                         glBegin(GL_LINES);
1346                         glVertex2s(offset, 0);
1347                         glVertex2s(offset + length, 0);
1348                         glVertex2s(offset + length, 0);
1349                         glVertex2s(offset + length - size, -size);
1350                         glVertex2s(offset + length, 0);
1351                         glVertex2s(offset + length - size,  size);
1352                         glEnd();
1353                         break;
1354                 case DOWN:
1355                         offset = -offset;
1356                         length = -length;
1357                         size = -size;
1358                 case UP:
1359                         glBegin(GL_LINES);
1360                         glVertex2s(0, offset);
1361                         glVertex2s(0, offset + length);
1362                         glVertex2s(0, offset + length);
1363                         glVertex2s(-size, offset + length - size);
1364                         glVertex2s(0, offset + length);
1365                         glVertex2s(size, offset + length - size);
1366                         glEnd();
1367                         break;
1368         }
1369 }
1370
1371 static void drawArrowHead(ArrowDirection d, short size)
1372 {
1373         switch (d) {
1374                 case LEFT:
1375                         size = -size;
1376                 case RIGHT:
1377                         glBegin(GL_LINES);
1378                         glVertex2s(0, 0);
1379                         glVertex2s(-size, -size);
1380                         glVertex2s(0, 0);
1381                         glVertex2s(-size,  size);
1382                         glEnd();
1383                         break;
1384                 case DOWN:
1385                         size = -size;
1386                 case UP:
1387                         glBegin(GL_LINES);
1388                         glVertex2s(0, 0);
1389                         glVertex2s(-size, -size);
1390                         glVertex2s(0, 0);
1391                         glVertex2s(size, -size);
1392                         glEnd();
1393                         break;
1394         }
1395 }
1396
1397 static void drawArc(float size, float angle_start, float angle_end, int segments)
1398 {
1399         float delta = (angle_end - angle_start) / segments;
1400         float angle;
1401         int a;
1402
1403         glBegin(GL_LINE_STRIP);
1404
1405         for (angle = angle_start, a = 0; a < segments; angle += delta, a++) {
1406                 glVertex2f(cosf(angle) * size, sinf(angle) * size);
1407         }
1408         glVertex2f(cosf(angle_end) * size, sinf(angle_end) * size);
1409
1410         glEnd();
1411 }
1412
1413 static int helpline_poll(bContext *C)
1414 {
1415         ARegion *ar = CTX_wm_region(C);
1416         
1417         if (ar && ar->regiontype == RGN_TYPE_WINDOW)
1418                 return 1;
1419         return 0;
1420 }
1421
1422 static void drawHelpline(bContext *UNUSED(C), int x, int y, void *customdata)
1423 {
1424         TransInfo *t = (TransInfo *)customdata;
1425
1426         if (t->helpline != HLP_NONE && !(t->flag & T_USES_MANIPULATOR)) {
1427                 float vecrot[3], cent[2];
1428                 int mval[2];
1429
1430                 mval[0] = x;
1431                 mval[1] = y;
1432
1433                 copy_v3_v3(vecrot, t->center);
1434                 if (t->flag & T_EDIT) {
1435                         Object *ob = t->obedit;
1436                         if (ob) mul_m4_v3(ob->obmat, vecrot);
1437                 }
1438                 else if (t->flag & T_POSE) {
1439                         Object *ob = t->poseobj;
1440                         if (ob) mul_m4_v3(ob->obmat, vecrot);
1441                 }
1442
1443                 projectFloatView(t, vecrot, cent);  // no overflow in extreme cases
1444
1445                 glPushMatrix();
1446
1447                 switch (t->helpline) {
1448                         case HLP_SPRING:
1449                                 UI_ThemeColor(TH_WIRE);
1450
1451                                 setlinestyle(3);
1452                                 glBegin(GL_LINE_STRIP);
1453                                 glVertex2iv(t->mval);
1454                                 glVertex2fv(cent);
1455                                 glEnd();
1456
1457                                 glTranslatef(mval[0], mval[1], 0);
1458                                 glRotatef(-RAD2DEGF(atan2f(cent[0] - t->mval[0], cent[1] - t->mval[1])), 0, 0, 1);
1459
1460                                 setlinestyle(0);
1461                                 glLineWidth(3.0);
1462                                 drawArrow(UP, 5, 10, 5);
1463                                 drawArrow(DOWN, 5, 10, 5);
1464                                 glLineWidth(1.0);
1465                                 break;
1466                         case HLP_HARROW:
1467                                 UI_ThemeColor(TH_WIRE);
1468
1469                                 glTranslatef(mval[0], mval[1], 0);
1470
1471                                 glLineWidth(3.0);
1472                                 drawArrow(RIGHT, 5, 10, 5);
1473                                 drawArrow(LEFT, 5, 10, 5);
1474                                 glLineWidth(1.0);
1475                                 break;
1476                         case HLP_VARROW:
1477                                 UI_ThemeColor(TH_WIRE);
1478
1479                                 glTranslatef(mval[0], mval[1], 0);
1480
1481                                 glLineWidth(3.0);
1482                                 glBegin(GL_LINES);
1483                                 drawArrow(UP, 5, 10, 5);
1484                                 drawArrow(DOWN, 5, 10, 5);
1485                                 glLineWidth(1.0);
1486                                 break;
1487                         case HLP_ANGLE:
1488                         {
1489                                 float dx = t->mval[0] - cent[0], dy = t->mval[1] - cent[1];
1490                                 float angle = atan2f(dy, dx);
1491                                 float dist = sqrtf(dx * dx + dy * dy);
1492                                 float delta_angle = min_ff(15.0f / dist, (float)M_PI / 4.0f);
1493                                 float spacing_angle = min_ff(5.0f / dist, (float)M_PI / 12.0f);
1494                                 UI_ThemeColor(TH_WIRE);
1495
1496                                 setlinestyle(3);
1497                                 glBegin(GL_LINE_STRIP);
1498                                 glVertex2iv(t->mval);
1499                                 glVertex2fv(cent);
1500                                 glEnd();
1501
1502                                 glTranslatef(cent[0] - t->mval[0] + mval[0], cent[1] - t->mval[1] + mval[1], 0);
1503
1504                                 setlinestyle(0);
1505                                 glLineWidth(3.0);
1506                                 drawArc(dist, angle - delta_angle, angle - spacing_angle, 10);
1507                                 drawArc(dist, angle + spacing_angle, angle + delta_angle, 10);
1508
1509                                 glPushMatrix();
1510
1511                                 glTranslatef(cosf(angle - delta_angle) * dist, sinf(angle - delta_angle) * dist, 0);
1512                                 glRotatef(RAD2DEGF(angle - delta_angle), 0, 0, 1);
1513
1514                                 drawArrowHead(DOWN, 5);
1515
1516                                 glPopMatrix();
1517
1518                                 glTranslatef(cosf(angle + delta_angle) * dist, sinf(angle + delta_angle) * dist, 0);
1519                                 glRotatef(RAD2DEGF(angle + delta_angle), 0, 0, 1);
1520
1521                                 drawArrowHead(UP, 5);
1522
1523                                 glLineWidth(1.0);
1524                                 break;
1525                         }
1526                         case HLP_TRACKBALL:
1527                         {
1528                                 unsigned char col[3], col2[3];
1529                                 UI_GetThemeColor3ubv(TH_GRID, col);
1530
1531                                 glTranslatef(mval[0], mval[1], 0);
1532
1533                                 glLineWidth(3.0);
1534
1535                                 UI_make_axis_color(col, col2, 'X');
1536                                 glColor3ubv((GLubyte *)col2);
1537
1538                                 drawArrow(RIGHT, 5, 10, 5);
1539                                 drawArrow(LEFT, 5, 10, 5);
1540
1541                                 UI_make_axis_color(col, col2, 'Y');
1542                                 glColor3ubv((GLubyte *)col2);
1543
1544                                 drawArrow(UP, 5, 10, 5);
1545                                 drawArrow(DOWN, 5, 10, 5);
1546                                 glLineWidth(1.0);
1547                                 break;
1548                         }
1549                 }
1550
1551                 glPopMatrix();
1552         }
1553 }
1554
1555 static void drawTransformView(const struct bContext *C, ARegion *UNUSED(ar), void *arg)
1556 {
1557         TransInfo *t = arg;
1558
1559         drawConstraint(t);
1560         drawPropCircle(C, t);
1561         drawSnapping(C, t);
1562         drawNonPropEdge(C, t);
1563 }
1564
1565 /* just draw a little warning message in the top-right corner of the viewport to warn that autokeying is enabled */
1566 static void drawAutoKeyWarning(TransInfo *UNUSED(t), ARegion *ar)
1567 {
1568         const char printable[] = "Auto Keying On";
1569         float      printable_size[2];
1570         int xco, yco;
1571
1572         BLF_width_and_height_default(printable, &printable_size[0], &printable_size[1]);
1573         
1574         xco = ar->winx - (int)printable_size[0] - 10;
1575         yco = ar->winy - (int)printable_size[1] - 10;
1576         
1577         /* warning text (to clarify meaning of overlays)
1578          * - original color was red to match the icon, but that clashes badly with a less nasty border
1579          */
1580         UI_ThemeColorShade(TH_TEXT_HI, -50);
1581         BLF_draw_default_ascii(xco, ar->winy - 17, 0.0f, printable, sizeof(printable));
1582         
1583         /* autokey recording icon... */
1584         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1585         glEnable(GL_BLEND);
1586         
1587         xco -= (ICON_DEFAULT_WIDTH + 2);
1588         UI_icon_draw(xco, yco, ICON_REC);
1589         
1590         glDisable(GL_BLEND);
1591 }
1592
1593 static void drawTransformPixel(const struct bContext *UNUSED(C), ARegion *ar, void *arg)
1594 {       
1595         TransInfo *t = arg;
1596         Scene *scene = t->scene;
1597         Object *ob = OBACT;
1598         
1599         /* draw autokeyframing hint in the corner 
1600          * - only draw if enabled (advanced users may be distracted/annoyed), 
1601          *   for objects that will be autokeyframed (no point ohterwise),
1602          *   AND only for the active region (as showing all is too overwhelming)
1603          */
1604         if ((U.autokey_flag & AUTOKEY_FLAG_NOWARNING) == 0) {
1605                 if (ar == t->ar) {
1606                         if (t->flag & (T_OBJECT | T_POSE)) {
1607                                 if (ob && autokeyframe_cfra_can_key(scene, &ob->id)) {
1608                                         drawAutoKeyWarning(t, ar);
1609                                 }
1610                         }
1611                 }
1612         }
1613 }
1614
1615 void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
1616 {
1617         ToolSettings *ts = CTX_data_tool_settings(C);
1618         int constraint_axis[3] = {0, 0, 0};
1619         int proportional = 0;
1620         PropertyRNA *prop;
1621
1622         // Save back mode in case we're in the generic operator
1623         if ((prop = RNA_struct_find_property(op->ptr, "mode"))) {
1624                 RNA_property_enum_set(op->ptr, prop, t->mode);
1625         }
1626
1627         if ((prop = RNA_struct_find_property(op->ptr, "value"))) {
1628                 float *values = (t->flag & T_AUTOVALUES) ? t->auto_values : t->values;
1629                 if (RNA_property_array_check(prop)) {
1630                         RNA_property_float_set_array(op->ptr, prop, values);
1631                 }
1632                 else {
1633                         RNA_property_float_set(op->ptr, prop, values[0]);
1634                 }
1635         }
1636
1637         /* convert flag to enum */
1638         switch (t->flag & (T_PROP_EDIT | T_PROP_CONNECTED)) {
1639                 case (T_PROP_EDIT | T_PROP_CONNECTED):
1640                         proportional = PROP_EDIT_CONNECTED;
1641                         break;
1642                 case T_PROP_EDIT:
1643                         proportional = PROP_EDIT_ON;
1644                         break;
1645                 default:
1646                         proportional = PROP_EDIT_OFF;
1647         }
1648
1649         // If modal, save settings back in scene if not set as operator argument
1650         if (t->flag & T_MODAL) {
1651
1652                 /* save settings if not set in operator */
1653                 if ((prop = RNA_struct_find_property(op->ptr, "proportional")) &&
1654                     !RNA_property_is_set(op->ptr, prop))
1655                 {
1656                         if (t->obedit)
1657                                 ts->proportional = proportional;
1658                         else if (t->options & CTX_MASK)
1659                                 ts->proportional_mask = (proportional != PROP_EDIT_OFF);
1660                         else
1661                                 ts->proportional_objects = (proportional != PROP_EDIT_OFF);
1662                 }
1663
1664                 if ((prop = RNA_struct_find_property(op->ptr, "proportional_size")) &&
1665                     !RNA_property_is_set(op->ptr, prop))
1666                 {
1667                         ts->proportional_size = t->prop_size;
1668                 }
1669
1670                 if ((prop = RNA_struct_find_property(op->ptr, "proportional_edit_falloff")) &&
1671                     !RNA_property_is_set(op->ptr, prop))
1672                 {
1673                         ts->prop_mode = t->prop_mode;
1674                 }
1675                 
1676                 /* do we check for parameter? */
1677                 if (t->modifiers & MOD_SNAP) {
1678                         ts->snap_flag |= SCE_SNAP;
1679                 }
1680                 else {
1681                         ts->snap_flag &= ~SCE_SNAP;
1682                 }
1683
1684                 if (t->spacetype == SPACE_VIEW3D) {
1685                         if ((prop = RNA_struct_find_property(op->ptr, "constraint_orientation")) &&
1686                             !RNA_property_is_set(op->ptr, prop))
1687                         {
1688                                 View3D *v3d = t->view;
1689
1690                                 v3d->twmode = t->current_orientation;
1691                         }
1692                 }
1693         }
1694         
1695         if (RNA_struct_find_property(op->ptr, "proportional")) {
1696                 RNA_enum_set(op->ptr, "proportional", proportional);
1697                 RNA_enum_set(op->ptr, "proportional_edit_falloff", t->prop_mode);
1698                 RNA_float_set(op->ptr, "proportional_size", t->prop_size);
1699         }
1700
1701         if ((prop = RNA_struct_find_property(op->ptr, "axis"))) {
1702                 RNA_property_float_set_array(op->ptr, prop, t->axis);
1703         }
1704
1705         if ((prop = RNA_struct_find_property(op->ptr, "mirror"))) {
1706                 RNA_property_boolean_set(op->ptr, prop, t->flag & T_MIRROR);
1707         }
1708
1709         if ((prop = RNA_struct_find_property(op->ptr, "constraint_axis"))) {
1710                 /* constraint orientation can be global, event if user selects something else
1711                  * so use the orientation in the constraint if set
1712                  * */
1713                 if (t->con.mode & CON_APPLY) {
1714                         RNA_enum_set(op->ptr, "constraint_orientation", t->con.orientation);
1715                 }
1716                 else {
1717                         RNA_enum_set(op->ptr, "constraint_orientation", t->current_orientation);
1718                 }
1719
1720                 if (t->con.mode & CON_APPLY) {
1721                         if (t->con.mode & CON_AXIS0) {
1722                                 constraint_axis[0] = 1;
1723                         }
1724                         if (t->con.mode & CON_AXIS1) {
1725                                 constraint_axis[1] = 1;
1726                         }
1727                         if (t->con.mode & CON_AXIS2) {
1728                                 constraint_axis[2] = 1;
1729                         }
1730                 }
1731
1732                 RNA_property_boolean_set_array(op->ptr, prop, constraint_axis);
1733         }
1734 }
1735
1736 /* note: caller needs to free 't' on a 0 return */
1737 int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int mode)
1738 {
1739         int options = 0;
1740         PropertyRNA *prop;
1741
1742         t->context = C;
1743
1744         /* added initialize, for external calls to set stuff in TransInfo, like undo string */
1745
1746         t->state = TRANS_STARTING;
1747
1748         if ((prop = RNA_struct_find_property(op->ptr, "texture_space")) && RNA_property_is_set(op->ptr, prop)) {
1749                 if (RNA_property_boolean_get(op->ptr, prop)) {
1750                         options |= CTX_TEXTURE;
1751                 }
1752         }
1753         
1754         t->options = options;
1755
1756         t->mode = mode;
1757
1758         t->launch_event = event ? event->type : -1;
1759
1760         if (t->launch_event == EVT_TWEAK_R) {
1761                 t->launch_event = RIGHTMOUSE;
1762         }
1763         else if (t->launch_event == EVT_TWEAK_L) {
1764                 t->launch_event = LEFTMOUSE;
1765         }
1766
1767         // XXX Remove this when wm_operator_call_internal doesn't use window->eventstate (which can have type = 0)
1768         // For manipulator only, so assume LEFTMOUSE
1769         if (t->launch_event == 0) {
1770                 t->launch_event = LEFTMOUSE;
1771         }
1772
1773         if (!initTransInfo(C, t, op, event)) {  /* internal data, mouse, vectors */
1774                 return 0;
1775         }
1776
1777         if (t->spacetype == SPACE_VIEW3D) {
1778                 //calc_manipulator_stats(curarea);
1779                 initTransformOrientation(C, t);
1780
1781                 t->draw_handle_apply = ED_region_draw_cb_activate(t->ar->type, drawTransformApply, t, REGION_DRAW_PRE_VIEW);
1782                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1783                 t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1784                 t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);
1785         }
1786         else if (t->spacetype == SPACE_IMAGE) {
1787                 unit_m3(t->spacemtx);
1788                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1789                 //t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1790                 t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);
1791         }
1792         else if (t->spacetype == SPACE_CLIP) {
1793                 unit_m3(t->spacemtx);
1794                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1795         }
1796         else if (t->spacetype == SPACE_NODE) {
1797                 unit_m3(t->spacemtx);
1798                 /*t->draw_handle_apply = ED_region_draw_cb_activate(t->ar->type, drawTransformApply, t, REGION_DRAW_PRE_VIEW);*/
1799                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1800                 /*t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);*/
1801         }
1802         else
1803                 unit_m3(t->spacemtx);
1804
1805         createTransData(C, t);          // make TransData structs from selection
1806
1807         if (t->total == 0) {
1808                 postTrans(C, t);
1809                 return 0;
1810         }
1811
1812         /* Stupid code to have Ctrl-Click on manipulator work ok */
1813         if (event) {
1814                 /* do this only for translation/rotation/resize due to only this
1815                  * moded are available from manipulator and doing such check could
1816                  * lead to keymap conflicts for other modes (see #31584)
1817                  */
1818                 if (ELEM3(mode, TFM_TRANSLATION, TFM_ROTATION, TFM_RESIZE)) {
1819                         wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1820                         wmKeyMapItem *kmi;
1821
1822                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1823                                 if (kmi->propvalue == TFM_MODAL_SNAP_INV_ON && kmi->val == KM_PRESS) {
1824                                         if ((ELEM(kmi->type, LEFTCTRLKEY, RIGHTCTRLKEY) &&   event->ctrl)  ||
1825                                             (ELEM(kmi->type, LEFTSHIFTKEY, RIGHTSHIFTKEY) && event->shift) ||
1826                                             (ELEM(kmi->type, LEFTALTKEY, RIGHTALTKEY) &&     event->alt)   ||
1827                                             ((kmi->type == OSKEY) &&                         event->oskey) )
1828                                         {
1829                                                 t->modifiers |= MOD_SNAP_INVERT;
1830                                         }
1831                                         break;
1832                                 }
1833                         }
1834                 }
1835
1836         }
1837
1838         initSnapping(t, op); // Initialize snapping data AFTER mode flags
1839
1840         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1841         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1842         /* EVIL3: extend mode for animation editors also switches modes... but is best way to avoid duplicate code */
1843         mode = t->mode;
1844
1845         calculatePropRatio(t);
1846         calculateCenter(t);
1847
1848         initMouseInput(t, &t->mouse, t->center2d, t->imval);
1849
1850         switch (mode) {
1851                 case TFM_TRANSLATION:
1852                         initTranslation(t);
1853                         break;
1854                 case TFM_ROTATION:
1855                         initRotation(t);
1856                         break;
1857                 case TFM_RESIZE:
1858                         initResize(t);
1859                         break;
1860                 case TFM_SKIN_RESIZE:
1861                         initSkinResize(t);
1862                         break;
1863                 case TFM_TOSPHERE:
1864                         initToSphere(t);
1865                         break;
1866                 case TFM_SHEAR:
1867                         initShear(t);
1868                         break;
1869                 case TFM_WARP:
1870                         initWarp(t);
1871                         break;
1872                 case TFM_SHRINKFATTEN:
1873                         initShrinkFatten(t);
1874                         break;
1875                 case TFM_TILT:
1876                         initTilt(t);
1877                         break;
1878                 case TFM_CURVE_SHRINKFATTEN:
1879                         initCurveShrinkFatten(t);
1880                         break;
1881                 case TFM_MASK_SHRINKFATTEN:
1882                         initMaskShrinkFatten(t);
1883                         break;
1884                 case TFM_TRACKBALL:
1885                         initTrackball(t);
1886                         break;
1887                 case TFM_PUSHPULL:
1888                         initPushPull(t);
1889                         break;
1890                 case TFM_CREASE:
1891                         initCrease(t);
1892                         break;
1893                 case TFM_BONESIZE:
1894                 {   /* used for both B-Bone width (bonesize) as for deform-dist (envelope) */
1895                         bArmature *arm = t->poseobj->data;
1896                         if (arm->drawtype == ARM_ENVELOPE)
1897                                 initBoneEnvelope(t);
1898                         else
1899                                 initBoneSize(t);
1900                 }
1901                 break;
1902                 case TFM_BONE_ENVELOPE:
1903                         initBoneEnvelope(t);
1904                         break;
1905                 case TFM_EDGE_SLIDE:
1906                         initEdgeSlide(t);
1907                         break;
1908                 case TFM_BONE_ROLL:
1909                         initBoneRoll(t);
1910                         break;
1911                 case TFM_TIME_TRANSLATE:
1912                         initTimeTranslate(t);
1913                         break;
1914                 case TFM_TIME_SLIDE:
1915                         initTimeSlide(t);
1916                         break;
1917                 case TFM_TIME_SCALE:
1918                         initTimeScale(t);
1919                         break;
1920                 case TFM_TIME_DUPLICATE:
1921                         /* same as TFM_TIME_EXTEND, but we need the mode info for later
1922                          * so that duplicate-culling will work properly
1923                          */
1924                         if (ELEM(t->spacetype, SPACE_IPO, SPACE_NLA))
1925                                 initTranslation(t);
1926                         else
1927                                 initTimeTranslate(t);
1928                         t->mode = mode;
1929                         break;
1930                 case TFM_TIME_EXTEND:
1931                         /* now that transdata has been made, do like for TFM_TIME_TRANSLATE (for most Animation
1932                          * Editors because they have only 1D transforms for time values) or TFM_TRANSLATION
1933                          * (for Graph/NLA Editors only since they uses 'standard' transforms to get 2D movement)
1934                          * depending on which editor this was called from
1935                          */
1936                         if (ELEM(t->spacetype, SPACE_IPO, SPACE_NLA))
1937                                 initTranslation(t);
1938                         else
1939                                 initTimeTranslate(t);
1940                         break;
1941                 case TFM_BAKE_TIME:
1942                         initBakeTime(t);
1943                         break;
1944                 case TFM_MIRROR:
1945                         initMirror(t);
1946                         break;
1947                 case TFM_BEVEL:
1948                         initBevel(t);
1949                         break;
1950                 case TFM_BWEIGHT:
1951                         initBevelWeight(t);
1952                         break;
1953                 case TFM_ALIGN:
1954                         initAlign(t);
1955                         break;
1956                 case TFM_SEQ_SLIDE:
1957                         initSeqSlide(t);
1958                         break;
1959         }
1960
1961         if (t->state == TRANS_CANCEL) {
1962                 postTrans(C, t);
1963                 return 0;
1964         }
1965
1966
1967         /* overwrite initial values if operator supplied a non-null vector */
1968         if ((prop = RNA_struct_find_property(op->ptr, "value")) && RNA_property_is_set(op->ptr, prop)) {
1969                 float values[4] = {0}; /* in case value isn't length 4, avoid uninitialized memory  */
1970
1971                 if (RNA_property_array_check(prop)) {
1972                         RNA_float_get_array(op->ptr, "value", values);
1973                 }
1974                 else {
1975                         values[0] = RNA_float_get(op->ptr, "value");
1976                 }
1977
1978                 copy_v4_v4(t->values, values);
1979                 copy_v4_v4(t->auto_values, values);
1980                 t->flag |= T_AUTOVALUES;
1981         }
1982
1983         /* Transformation axis from operator */
1984         if ((prop = RNA_struct_find_property(op->ptr, "axis")) && RNA_property_is_set(op->ptr, prop)) {
1985                 RNA_property_float_get_array(op->ptr, prop, t->axis);
1986                 normalize_v3(t->axis);
1987                 copy_v3_v3(t->axis_orig, t->axis);
1988         }
1989
1990         /* Constraint init from operator */
1991         if ((prop = RNA_struct_find_property(op->ptr, "constraint_axis")) && RNA_property_is_set(op->ptr, prop)) {
1992                 int constraint_axis[3];
1993
1994                 RNA_property_boolean_get_array(op->ptr, prop, constraint_axis);
1995
1996                 if (constraint_axis[0] || constraint_axis[1] || constraint_axis[2]) {
1997                         t->con.mode |= CON_APPLY;
1998
1999                         if (constraint_axis[0]) {
2000                                 t->con.mode |= CON_AXIS0;
2001                         }
2002                         if (constraint_axis[1]) {
2003                                 t->con.mode |= CON_AXIS1;
2004                         }
2005                         if (constraint_axis[2]) {
2006                                 t->con.mode |= CON_AXIS2;
2007                         }
2008
2009                         setUserConstraint(t, t->current_orientation, t->con.mode, "%s");
2010                 }
2011         }
2012
2013         t->context = NULL;
2014
2015         return 1;
2016 }
2017
2018 void transformApply(bContext *C, TransInfo *t)
2019 {
2020         t->context = C;
2021
2022         if ((t->redraw & TREDRAW_HARD) || (t->draw_handle_apply == NULL && (t->redraw & TREDRAW_SOFT))) {
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