use min/max inline functions where MIN2/MAX2 were doing type conversion.
[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                 printf("handled %d redraw %d\n", handled, t->redraw);
1279                 return 0;
1280         }
1281         else {
1282                 return OPERATOR_PASS_THROUGH;
1283         }
1284 }
1285
1286 int calculateTransformCenter(bContext *C, int centerMode, float cent3d[3], int cent2d[2])
1287 {
1288         TransInfo *t = MEM_callocN(sizeof(TransInfo), "TransInfo data");
1289         int success;
1290
1291         t->state = TRANS_RUNNING;
1292
1293         t->options = CTX_NONE;
1294
1295         t->mode = TFM_DUMMY;
1296
1297         initTransInfo(C, t, NULL, NULL);    // internal data, mouse, vectors
1298
1299         createTransData(C, t);              // make TransData structs from selection
1300
1301         t->around = centerMode;             // override userdefined mode
1302
1303         if (t->total == 0) {
1304                 success = FALSE;
1305         }
1306         else {
1307                 success = TRUE;
1308
1309                 calculateCenter(t);
1310
1311                 if (cent2d) {
1312                         copy_v2_v2_int(cent2d, t->center2d);
1313                 }
1314
1315                 if (cent3d) {
1316                         // Copy center from constraint center. Transform center can be local
1317                         copy_v3_v3(cent3d, t->con.center);
1318                 }
1319         }
1320
1321
1322         /* aftertrans does insert ipos and action channels, and clears base flags, doesnt read transdata */
1323         special_aftertrans_update(C, t);
1324
1325         postTrans(C, t);
1326
1327         MEM_freeN(t);
1328
1329         return success;
1330 }
1331
1332 typedef enum {
1333         UP,
1334         DOWN,
1335         LEFT,
1336         RIGHT
1337 } ArrowDirection;
1338 static void drawArrow(ArrowDirection d, short offset, short length, short size)
1339 {
1340         switch (d) {
1341                 case LEFT:
1342                         offset = -offset;
1343                         length = -length;
1344                         size = -size;
1345                 case RIGHT:
1346                         glBegin(GL_LINES);
1347                         glVertex2s(offset, 0);
1348                         glVertex2s(offset + length, 0);
1349                         glVertex2s(offset + length, 0);
1350                         glVertex2s(offset + length - size, -size);
1351                         glVertex2s(offset + length, 0);
1352                         glVertex2s(offset + length - size,  size);
1353                         glEnd();
1354                         break;
1355                 case DOWN:
1356                         offset = -offset;
1357                         length = -length;
1358                         size = -size;
1359                 case UP:
1360                         glBegin(GL_LINES);
1361                         glVertex2s(0, offset);
1362                         glVertex2s(0, offset + length);
1363                         glVertex2s(0, offset + length);
1364                         glVertex2s(-size, offset + length - size);
1365                         glVertex2s(0, offset + length);
1366                         glVertex2s(size, offset + length - size);
1367                         glEnd();
1368                         break;
1369         }
1370 }
1371
1372 static void drawArrowHead(ArrowDirection d, short size)
1373 {
1374         switch (d) {
1375                 case LEFT:
1376                         size = -size;
1377                 case RIGHT:
1378                         glBegin(GL_LINES);
1379                         glVertex2s(0, 0);
1380                         glVertex2s(-size, -size);
1381                         glVertex2s(0, 0);
1382                         glVertex2s(-size,  size);
1383                         glEnd();
1384                         break;
1385                 case DOWN:
1386                         size = -size;
1387                 case UP:
1388                         glBegin(GL_LINES);
1389                         glVertex2s(0, 0);
1390                         glVertex2s(-size, -size);
1391                         glVertex2s(0, 0);
1392                         glVertex2s(size, -size);
1393                         glEnd();
1394                         break;
1395         }
1396 }
1397
1398 static void drawArc(float size, float angle_start, float angle_end, int segments)
1399 {
1400         float delta = (angle_end - angle_start) / segments;
1401         float angle;
1402         int a;
1403
1404         glBegin(GL_LINE_STRIP);
1405
1406         for (angle = angle_start, a = 0; a < segments; angle += delta, a++) {
1407                 glVertex2f(cosf(angle) * size, sinf(angle) * size);
1408         }
1409         glVertex2f(cosf(angle_end) * size, sinf(angle_end) * size);
1410
1411         glEnd();
1412 }
1413
1414 static int helpline_poll(bContext *C)
1415 {
1416         ARegion *ar = CTX_wm_region(C);
1417         
1418         if (ar && ar->regiontype == RGN_TYPE_WINDOW)
1419                 return 1;
1420         return 0;
1421 }
1422
1423 static void drawHelpline(bContext *UNUSED(C), int x, int y, void *customdata)
1424 {
1425         TransInfo *t = (TransInfo *)customdata;
1426
1427         if (t->helpline != HLP_NONE && !(t->flag & T_USES_MANIPULATOR)) {
1428                 float vecrot[3], cent[2];
1429                 int mval[2];
1430
1431                 mval[0] = x;
1432                 mval[1] = y;
1433
1434                 copy_v3_v3(vecrot, t->center);
1435                 if (t->flag & T_EDIT) {
1436                         Object *ob = t->obedit;
1437                         if (ob) mul_m4_v3(ob->obmat, vecrot);
1438                 }
1439                 else if (t->flag & T_POSE) {
1440                         Object *ob = t->poseobj;
1441                         if (ob) mul_m4_v3(ob->obmat, vecrot);
1442                 }
1443
1444                 projectFloatView(t, vecrot, cent);  // no overflow in extreme cases
1445
1446                 glPushMatrix();
1447
1448                 switch (t->helpline) {
1449                         case HLP_SPRING:
1450                                 UI_ThemeColor(TH_WIRE);
1451
1452                                 setlinestyle(3);
1453                                 glBegin(GL_LINE_STRIP);
1454                                 glVertex2iv(t->mval);
1455                                 glVertex2fv(cent);
1456                                 glEnd();
1457
1458                                 glTranslatef(mval[0], mval[1], 0);
1459                                 glRotatef(-RAD2DEGF(atan2f(cent[0] - t->mval[0], cent[1] - t->mval[1])), 0, 0, 1);
1460
1461                                 setlinestyle(0);
1462                                 glLineWidth(3.0);
1463                                 drawArrow(UP, 5, 10, 5);
1464                                 drawArrow(DOWN, 5, 10, 5);
1465                                 glLineWidth(1.0);
1466                                 break;
1467                         case HLP_HARROW:
1468                                 UI_ThemeColor(TH_WIRE);
1469
1470                                 glTranslatef(mval[0], mval[1], 0);
1471
1472                                 glLineWidth(3.0);
1473                                 drawArrow(RIGHT, 5, 10, 5);
1474                                 drawArrow(LEFT, 5, 10, 5);
1475                                 glLineWidth(1.0);
1476                                 break;
1477                         case HLP_VARROW:
1478                                 UI_ThemeColor(TH_WIRE);
1479
1480                                 glTranslatef(mval[0], mval[1], 0);
1481
1482                                 glLineWidth(3.0);
1483                                 glBegin(GL_LINES);
1484                                 drawArrow(UP, 5, 10, 5);
1485                                 drawArrow(DOWN, 5, 10, 5);
1486                                 glLineWidth(1.0);
1487                                 break;
1488                         case HLP_ANGLE:
1489                         {
1490                                 float dx = t->mval[0] - cent[0], dy = t->mval[1] - cent[1];
1491                                 float angle = atan2f(dy, dx);
1492                                 float dist = sqrtf(dx * dx + dy * dy);
1493                                 float delta_angle = min_ff(15.0f / dist, (float)M_PI / 4.0f);
1494                                 float spacing_angle = min_ff(5.0f / dist, (float)M_PI / 12.0f);
1495                                 UI_ThemeColor(TH_WIRE);
1496
1497                                 setlinestyle(3);
1498                                 glBegin(GL_LINE_STRIP);
1499                                 glVertex2iv(t->mval);
1500                                 glVertex2fv(cent);
1501                                 glEnd();
1502
1503                                 glTranslatef(cent[0] - t->mval[0] + mval[0], cent[1] - t->mval[1] + mval[1], 0);
1504
1505                                 setlinestyle(0);
1506                                 glLineWidth(3.0);
1507                                 drawArc(dist, angle - delta_angle, angle - spacing_angle, 10);
1508                                 drawArc(dist, angle + spacing_angle, angle + delta_angle, 10);
1509
1510                                 glPushMatrix();
1511
1512                                 glTranslatef(cosf(angle - delta_angle) * dist, sinf(angle - delta_angle) * dist, 0);
1513                                 glRotatef(RAD2DEGF(angle - delta_angle), 0, 0, 1);
1514
1515                                 drawArrowHead(DOWN, 5);
1516
1517                                 glPopMatrix();
1518
1519                                 glTranslatef(cosf(angle + delta_angle) * dist, sinf(angle + delta_angle) * dist, 0);
1520                                 glRotatef(RAD2DEGF(angle + delta_angle), 0, 0, 1);
1521
1522                                 drawArrowHead(UP, 5);
1523
1524                                 glLineWidth(1.0);
1525                                 break;
1526                         }
1527                         case HLP_TRACKBALL:
1528                         {
1529                                 unsigned char col[3], col2[3];
1530                                 UI_GetThemeColor3ubv(TH_GRID, col);
1531
1532                                 glTranslatef(mval[0], mval[1], 0);
1533
1534                                 glLineWidth(3.0);
1535
1536                                 UI_make_axis_color(col, col2, 'X');
1537                                 glColor3ubv((GLubyte *)col2);
1538
1539                                 drawArrow(RIGHT, 5, 10, 5);
1540                                 drawArrow(LEFT, 5, 10, 5);
1541
1542                                 UI_make_axis_color(col, col2, 'Y');
1543                                 glColor3ubv((GLubyte *)col2);
1544
1545                                 drawArrow(UP, 5, 10, 5);
1546                                 drawArrow(DOWN, 5, 10, 5);
1547                                 glLineWidth(1.0);
1548                                 break;
1549                         }
1550                 }
1551
1552                 glPopMatrix();
1553         }
1554 }
1555
1556 static void drawTransformView(const struct bContext *C, ARegion *UNUSED(ar), void *arg)
1557 {
1558         TransInfo *t = arg;
1559
1560         drawConstraint(t);
1561         drawPropCircle(C, t);
1562         drawSnapping(C, t);
1563         drawNonPropEdge(C, t);
1564 }
1565
1566 /* just draw a little warning message in the top-right corner of the viewport to warn that autokeying is enabled */
1567 static void drawAutoKeyWarning(TransInfo *UNUSED(t), ARegion *ar)
1568 {
1569         const char printable[] = "Auto Keying On";
1570         float      printable_size[2];
1571         int xco, yco;
1572
1573         BLF_width_and_height_default(printable, &printable_size[0], &printable_size[1]);
1574         
1575         xco = ar->winx - (int)printable_size[0] - 10;
1576         yco = ar->winy - (int)printable_size[1] - 10;
1577         
1578         /* warning text (to clarify meaning of overlays)
1579          * - original color was red to match the icon, but that clashes badly with a less nasty border
1580          */
1581         UI_ThemeColorShade(TH_TEXT_HI, -50);
1582         BLF_draw_default_ascii(xco, ar->winy - 17, 0.0f, printable, sizeof(printable));
1583         
1584         /* autokey recording icon... */
1585         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1586         glEnable(GL_BLEND);
1587         
1588         xco -= (ICON_DEFAULT_WIDTH + 2);
1589         UI_icon_draw(xco, yco, ICON_REC);
1590         
1591         glDisable(GL_BLEND);
1592 }
1593
1594 static void drawTransformPixel(const struct bContext *UNUSED(C), ARegion *ar, void *arg)
1595 {       
1596         TransInfo *t = arg;
1597         Scene *scene = t->scene;
1598         Object *ob = OBACT;
1599         
1600         /* draw autokeyframing hint in the corner 
1601          * - only draw if enabled (advanced users may be distracted/annoyed), 
1602          *   for objects that will be autokeyframed (no point ohterwise),
1603          *   AND only for the active region (as showing all is too overwhelming)
1604          */
1605         if ((U.autokey_flag & AUTOKEY_FLAG_NOWARNING) == 0) {
1606                 if (ar == t->ar) {
1607                         if (t->flag & (T_OBJECT | T_POSE)) {
1608                                 if (ob && autokeyframe_cfra_can_key(scene, &ob->id)) {
1609                                         drawAutoKeyWarning(t, ar);
1610                                 }
1611                         }
1612                 }
1613         }
1614 }
1615
1616 void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
1617 {
1618         ToolSettings *ts = CTX_data_tool_settings(C);
1619         int constraint_axis[3] = {0, 0, 0};
1620         int proportional = 0;
1621         PropertyRNA *prop;
1622
1623         // Save back mode in case we're in the generic operator
1624         if ((prop = RNA_struct_find_property(op->ptr, "mode"))) {
1625                 RNA_property_enum_set(op->ptr, prop, t->mode);
1626         }
1627
1628         if ((prop = RNA_struct_find_property(op->ptr, "value"))) {
1629                 float *values = (t->flag & T_AUTOVALUES) ? t->auto_values : t->values;
1630                 if (RNA_property_array_check(prop)) {
1631                         RNA_property_float_set_array(op->ptr, prop, values);
1632                 }
1633                 else {
1634                         RNA_property_float_set(op->ptr, prop, values[0]);
1635                 }
1636         }
1637
1638         /* convert flag to enum */
1639         switch (t->flag & (T_PROP_EDIT | T_PROP_CONNECTED)) {
1640                 case (T_PROP_EDIT | T_PROP_CONNECTED):
1641                         proportional = PROP_EDIT_CONNECTED;
1642                         break;
1643                 case T_PROP_EDIT:
1644                         proportional = PROP_EDIT_ON;
1645                         break;
1646                 default:
1647                         proportional = PROP_EDIT_OFF;
1648         }
1649
1650         // If modal, save settings back in scene if not set as operator argument
1651         if (t->flag & T_MODAL) {
1652
1653                 /* save settings if not set in operator */
1654                 if ((prop = RNA_struct_find_property(op->ptr, "proportional")) &&
1655                     !RNA_property_is_set(op->ptr, prop))
1656                 {
1657                         if (t->obedit)
1658                                 ts->proportional = proportional;
1659                         else if (t->options & CTX_MASK)
1660                                 ts->proportional_mask = (proportional != PROP_EDIT_OFF);
1661                         else
1662                                 ts->proportional_objects = (proportional != PROP_EDIT_OFF);
1663                 }
1664
1665                 if ((prop = RNA_struct_find_property(op->ptr, "proportional_size")) &&
1666                     !RNA_property_is_set(op->ptr, prop))
1667                 {
1668                         ts->proportional_size = t->prop_size;
1669                 }
1670
1671                 if ((prop = RNA_struct_find_property(op->ptr, "proportional_edit_falloff")) &&
1672                     !RNA_property_is_set(op->ptr, prop))
1673                 {
1674                         ts->prop_mode = t->prop_mode;
1675                 }
1676                 
1677                 /* do we check for parameter? */
1678                 if (t->modifiers & MOD_SNAP) {
1679                         ts->snap_flag |= SCE_SNAP;
1680                 }
1681                 else {
1682                         ts->snap_flag &= ~SCE_SNAP;
1683                 }
1684
1685                 if (t->spacetype == SPACE_VIEW3D) {
1686                         if ((prop = RNA_struct_find_property(op->ptr, "constraint_orientation")) &&
1687                             !RNA_property_is_set(op->ptr, prop))
1688                         {
1689                                 View3D *v3d = t->view;
1690
1691                                 v3d->twmode = t->current_orientation;
1692                         }
1693                 }
1694         }
1695         
1696         if (RNA_struct_find_property(op->ptr, "proportional")) {
1697                 RNA_enum_set(op->ptr, "proportional", proportional);
1698                 RNA_enum_set(op->ptr, "proportional_edit_falloff", t->prop_mode);
1699                 RNA_float_set(op->ptr, "proportional_size", t->prop_size);
1700         }
1701
1702         if ((prop = RNA_struct_find_property(op->ptr, "axis"))) {
1703                 RNA_property_float_set_array(op->ptr, prop, t->axis);
1704         }
1705
1706         if ((prop = RNA_struct_find_property(op->ptr, "mirror"))) {
1707                 RNA_property_boolean_set(op->ptr, prop, t->flag & T_MIRROR);
1708         }
1709
1710         if ((prop = RNA_struct_find_property(op->ptr, "constraint_axis"))) {
1711                 /* constraint orientation can be global, event if user selects something else
1712                  * so use the orientation in the constraint if set
1713                  * */
1714                 if (t->con.mode & CON_APPLY) {
1715                         RNA_enum_set(op->ptr, "constraint_orientation", t->con.orientation);
1716                 }
1717                 else {
1718                         RNA_enum_set(op->ptr, "constraint_orientation", t->current_orientation);
1719                 }
1720
1721                 if (t->con.mode & CON_APPLY) {
1722                         if (t->con.mode & CON_AXIS0) {
1723                                 constraint_axis[0] = 1;
1724                         }
1725                         if (t->con.mode & CON_AXIS1) {
1726                                 constraint_axis[1] = 1;
1727                         }
1728                         if (t->con.mode & CON_AXIS2) {
1729                                 constraint_axis[2] = 1;
1730                         }
1731                 }
1732
1733                 RNA_property_boolean_set_array(op->ptr, prop, constraint_axis);
1734         }
1735 }
1736
1737 /* note: caller needs to free 't' on a 0 return */
1738 int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int mode)
1739 {
1740         int options = 0;
1741         PropertyRNA *prop;
1742
1743         t->context = C;
1744
1745         /* added initialize, for external calls to set stuff in TransInfo, like undo string */
1746
1747         t->state = TRANS_STARTING;
1748
1749         if ((prop = RNA_struct_find_property(op->ptr, "texture_space")) && RNA_property_is_set(op->ptr, prop)) {
1750                 if (RNA_property_boolean_get(op->ptr, prop)) {
1751                         options |= CTX_TEXTURE;
1752                 }
1753         }
1754         
1755         t->options = options;
1756
1757         t->mode = mode;
1758
1759         t->launch_event = event ? event->type : -1;
1760
1761         if (t->launch_event == EVT_TWEAK_R) {
1762                 t->launch_event = RIGHTMOUSE;
1763         }
1764         else if (t->launch_event == EVT_TWEAK_L) {
1765                 t->launch_event = LEFTMOUSE;
1766         }
1767
1768         // XXX Remove this when wm_operator_call_internal doesn't use window->eventstate (which can have type = 0)
1769         // For manipulator only, so assume LEFTMOUSE
1770         if (t->launch_event == 0) {
1771                 t->launch_event = LEFTMOUSE;
1772         }
1773
1774         if (!initTransInfo(C, t, op, event)) {  /* internal data, mouse, vectors */
1775                 return 0;
1776         }
1777
1778         if (t->spacetype == SPACE_VIEW3D) {
1779                 //calc_manipulator_stats(curarea);
1780                 initTransformOrientation(C, t);
1781
1782                 t->draw_handle_apply = ED_region_draw_cb_activate(t->ar->type, drawTransformApply, t, REGION_DRAW_PRE_VIEW);
1783                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1784                 t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1785                 t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);
1786         }
1787         else if (t->spacetype == SPACE_IMAGE) {
1788                 unit_m3(t->spacemtx);
1789                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1790                 //t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1791                 t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);
1792         }
1793         else if (t->spacetype == SPACE_CLIP) {
1794                 unit_m3(t->spacemtx);
1795                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1796         }
1797         else if (t->spacetype == SPACE_NODE) {
1798                 unit_m3(t->spacemtx);
1799                 /*t->draw_handle_apply = ED_region_draw_cb_activate(t->ar->type, drawTransformApply, t, REGION_DRAW_PRE_VIEW);*/
1800                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1801                 /*t->draw_handle_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), helpline_poll, drawHelpline, t);*/
1802         }
1803         else
1804                 unit_m3(t->spacemtx);
1805
1806         createTransData(C, t);          // make TransData structs from selection
1807
1808         if (t->total == 0) {
1809                 postTrans(C, t);
1810                 return 0;
1811         }
1812
1813         /* Stupid code to have Ctrl-Click on manipulator work ok */
1814         if (event) {
1815                 /* do this only for translation/rotation/resize due to only this
1816                  * moded are available from manipulator and doing such check could
1817                  * lead to keymap conflicts for other modes (see #31584)
1818                  */
1819                 if (ELEM3(mode, TFM_TRANSLATION, TFM_ROTATION, TFM_RESIZE)) {
1820                         wmKeyMap *keymap = WM_keymap_active(CTX_wm_manager(C), op->type->modalkeymap);
1821                         wmKeyMapItem *kmi;
1822
1823                         for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
1824                                 if (kmi->propvalue == TFM_MODAL_SNAP_INV_ON && kmi->val == KM_PRESS) {
1825                                         if ((ELEM(kmi->type, LEFTCTRLKEY, RIGHTCTRLKEY) &&   event->ctrl)  ||
1826                                             (ELEM(kmi->type, LEFTSHIFTKEY, RIGHTSHIFTKEY) && event->shift) ||
1827                                             (ELEM(kmi->type, LEFTALTKEY, RIGHTALTKEY) &&     event->alt)   ||
1828                                             ((kmi->type == OSKEY) &&                         event->oskey) )
1829                                         {
1830                                                 t->modifiers |= MOD_SNAP_INVERT;
1831                                         }
1832                                         break;
1833                                 }
1834                         }
1835                 }
1836
1837         }
1838
1839         initSnapping(t, op); // Initialize snapping data AFTER mode flags
1840
1841         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1842         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1843         /* EVIL3: extend mode for animation editors also switches modes... but is best way to avoid duplicate code */
1844         mode = t->mode;
1845
1846         calculatePropRatio(t);
1847         calculateCenter(t);
1848
1849         initMouseInput(t, &t->mouse, t->center2d, t->imval);
1850
1851         switch (mode) {
1852                 case TFM_TRANSLATION:
1853                         initTranslation(t);
1854                         break;
1855                 case TFM_ROTATION:
1856                         initRotation(t);
1857                         break;
1858                 case TFM_RESIZE:
1859                         initResize(t);
1860                         break;
1861                 case TFM_SKIN_RESIZE:
1862                         initSkinResize(t);
1863                         break;
1864                 case TFM_TOSPHERE:
1865                         initToSphere(t);
1866                         break;
1867                 case TFM_SHEAR:
1868                         initShear(t);
1869                         break;
1870                 case TFM_WARP:
1871                         initWarp(t);
1872                         break;
1873                 case TFM_SHRINKFATTEN:
1874                         initShrinkFatten(t);
1875                         break;
1876                 case TFM_TILT:
1877                         initTilt(t);
1878                         break;
1879                 case TFM_CURVE_SHRINKFATTEN:
1880                         initCurveShrinkFatten(t);
1881                         break;
1882                 case TFM_MASK_SHRINKFATTEN:
1883                         initMaskShrinkFatten(t);
1884                         break;
1885                 case TFM_TRACKBALL:
1886                         initTrackball(t);
1887                         break;
1888                 case TFM_PUSHPULL:
1889                         initPushPull(t);
1890                         break;
1891                 case TFM_CREASE:
1892                         initCrease(t);
1893                         break;
1894                 case TFM_BONESIZE:
1895                 {   /* used for both B-Bone width (bonesize) as for deform-dist (envelope) */
1896                         bArmature *arm = t->poseobj->data;
1897                         if (arm->drawtype == ARM_ENVELOPE)
1898                                 initBoneEnvelope(t);
1899                         else
1900                                 initBoneSize(t);
1901                 }
1902                 break;
1903                 case TFM_BONE_ENVELOPE:
1904                         initBoneEnvelope(t);
1905                         break;
1906                 case TFM_EDGE_SLIDE:
1907                         initEdgeSlide(t);
1908                         break;
1909                 case TFM_BONE_ROLL:
1910                         initBoneRoll(t);
1911                         break;
1912                 case TFM_TIME_TRANSLATE:
1913                         initTimeTranslate(t);
1914                         break;
1915                 case TFM_TIME_SLIDE:
1916                         initTimeSlide(t);
1917                         break;
1918                 case TFM_TIME_SCALE:
1919                         initTimeScale(t);
1920                         break;
1921                 case TFM_TIME_DUPLICATE:
1922                         /* same as TFM_TIME_EXTEND, but we need the mode info for later
1923                          * so that duplicate-culling will work properly
1924                          */
1925                         if (ELEM(t->spacetype, SPACE_IPO, SPACE_NLA))
1926                                 initTranslation(t);
1927                         else
1928                                 initTimeTranslate(t);
1929                         t->mode = mode;
1930                         break;
1931                 case TFM_TIME_EXTEND:
1932                         /* now that transdata has been made, do like for TFM_TIME_TRANSLATE (for most Animation
1933                          * Editors because they have only 1D transforms for time values) or TFM_TRANSLATION
1934                          * (for Graph/NLA Editors only since they uses 'standard' transforms to get 2D movement)
1935                          * depending on which editor this was called from
1936                          */
1937                         if (ELEM(t->spacetype, SPACE_IPO, SPACE_NLA))
1938                                 initTranslation(t);
1939                         else
1940                                 initTimeTranslate(t);
1941                         break;
1942                 case TFM_BAKE_TIME:
1943                         initBakeTime(t);
1944                         break;
1945                 case TFM_MIRROR:
1946                         initMirror(t);
1947                         break;
1948                 case TFM_BEVEL:
1949                         initBevel(t);
1950                         break;
1951                 case TFM_BWEIGHT:
1952                         initBevelWeight(t);
1953                         break;
1954                 case TFM_ALIGN:
1955                         initAlign(t);
1956                         break;
1957                 case TFM_SEQ_SLIDE:
1958                         initSeqSlide(t);
1959                         break;
1960         }
1961
1962         if (t->state == TRANS_CANCEL) {
1963                 postTrans(C, t);
1964                 return 0;
1965         }
1966
1967
1968         /* overwrite initial values if operator supplied a non-null vector */
1969         if ((prop = RNA_struct_find_property(op->ptr, "value")) && RNA_property_is_set(op->ptr, prop)) {
1970                 float values[4] = {0}; /* in case value isn't length 4, avoid uninitialized memory  */
1971
1972                 if (RNA_property_array_check(prop)) {
1973                         RNA_float_get_array(op->ptr, "value", values);
1974                 }
1975                 else {
1976                         values[0] = RNA_float_get(op->ptr, "value");
1977                 }
1978
1979                 copy_v4_v4(t->values, values);
1980                 copy_v4_v4(t->auto_values, values);
1981                 t->flag |= T_AUTOVALUES;
1982         }
1983
1984         /* Transformation axis from operator */
1985         if ((prop = RNA_struct_find_property(op->ptr, "axis")) && RNA_property_is_set(op->ptr, prop)) {
1986                 RNA_property_float_get_array(op->ptr, prop, t->axis);
1987                 normalize_v3(t->axis);
1988                 copy_v3_v3(t->axis_orig, t->axis);
1989         }
1990
1991         /* Constraint init from operator */
1992         if ((prop = RNA_struct_find_property(op->ptr, "constraint_axis")) && RNA_property_is_set(op->ptr, prop)) {
1993                 int constraint_axis[3];
1994
1995                 RNA_property_boolean_get_array(op->ptr, prop, constraint_axis);
1996
1997                 if (constraint_axis[0] || constraint_axis[1] || constraint_axis[2]) {
1998                         t->con.mode |= CON_APPLY;
1999
2000                         if (constraint_axis[0]) {
2001                                 t->con.mode |= CON_AXIS0;
2002                         }
2003                         if (constraint_axis[1]) {
2004                                 t->con.mode |= CON_AXIS1;
2005                         }
2006                         if (constraint_axis[2]) {
2007                                 t->con.mode |= CON_AXIS2;
2008                         }
2009
2010                         setUserConstraint(t, t->current_orientation, t->con.mode, "%s");
2011                 }
2012         }
2013
2014         t->context = NULL;
2015
2016         return 1;
2017 }
2018
2019 void transformApply(bContext *C, TransInfo *t)
2020 {
2021         t->context = C;
2022
2023         if ((t->redraw & TREDRAW_HARD) || (t->draw_handle_apply == NULL && (t->redraw & TREDRAW_SOFT))) {
2024                 selectConstraint(t);
2025                 if (t->transform) {
2026                         t->transform(t, t->mval);  // calls recalcData()
2027                         viewRedrawForce(C, t);
2028                 }
2029                 t->redraw = TREDRAW_NOTHING;
2030         }
2031         else if (t->redraw & TREDRAW_SOFT) {
2032                 viewRedrawForce(C, t);
2033         }
2034
2035         /* If auto confirm is on, break after one pass */
2036         if (t->options & CTX_AUTOCONFIRM) {
2037                 t->state = TRANS_CONFIRM;
2038         }
2039
2040         if (BKE_ptcache_get_continue_physics()) {
2041                 // TRANSFORM_FIX_ME
2042                 //do_screenhandlers(G.curscreen);
2043                 t->redraw |= TREDRAW_HARD;
2044         }
2045
2046         t->context = NULL;
2047 }
2048
2049 static void drawTransformApply(const bContext *C, ARegion *UNUSED(ar), void *arg)
2050 {
2051         TransInfo *t = arg;
2052
2053         if (t->redraw & TREDRAW_SOFT) {
2054                 t->redraw |= TREDRAW_HARD;
2055                 transformApply((bContext *)C, t);
2056         }
2057 }
2058
2059 int transformEnd(bContext *C, TransInfo *t)
2060 {
2061         int exit_code = OPERATOR_RUNNING_MODAL;
2062
2063         t->context = C;
2064
2065         if (t->state != TRANS_STARTING && t->state != TRANS_RUNNING) {
2066                 /* handle restoring objects */
2067                 if (t->state == TRANS_CANCEL) {
2068                         /* exception, edge slide transformed UVs too */
2069                         if (t->mode == TFM_EDGE_SLIDE)
2070                                 doEdgeSlide(t, 0.0f);
2071                         
2072                         exit_code = OPERATOR_CANCELLED;
2073                         restoreTransObjects(t); // calls recalcData()
2074                 }
2075                 else {
2076                         exit_code = OPERATOR_FINISHED;
2077                 }
2078
2079                 /* aftertrans does insert keyframes, and clears base flags, doesnt read transdata */
2080                 special_aftertrans_update(C, t);
2081
2082                 /* free data */
2083                 postTrans(C, t);
2084
2085                 /* send events out for redraws */
2086                 viewRedrawPost(C, t);
2087
2088                 /*  Undo as last, certainly after special_trans_update! */
2089
2090                 if (t->state == TRANS_CANCEL) {
2091 //                      if (t->undostr) ED_undo_push(C, t->undostr);
2092                 }
2093                 else {
2094 //                      if (t->undostr) ED_undo_push(C, t->undostr);
2095 //                      else ED_undo_push(C, transform_to_undostr(t));
2096                 }
2097                 t->undostr = NULL;
2098
2099                 viewRedrawForce(C, t);
2100         }
2101
2102         t->context = NULL;
2103
2104         return exit_code;
2105 }
2106
2107 /* ************************** TRANSFORM LOCKS **************************** */
2108
2109 static void protectedTransBits(short protectflag, float *vec)
2110 {
2111         if (protectflag & OB_LOCK_LOCX)
2112                 vec[0] = 0.0f;
2113         if (protectflag & OB_LOCK_LOCY)
2114                 vec[1] = 0.0f;
2115         if (protectflag & OB_LOCK_LOCZ)
2116                 vec[2] = 0.0f;
2117 }
2118
2119 static void protectedSizeBits(short protectflag, float *size)
2120 {
2121         if (protectflag & OB_LOCK_SCALEX)
2122                 size[0] = 1.0f;
2123         if (protectflag & OB_LOCK_SCALEY)
2124                 size[1] = 1.0f;
2125         if (protectflag & OB_LOCK_SCALEZ)
2126                 size[2] = 1.0f;
2127 }
2128
2129 static void protectedRotateBits(short protectflag, float *eul, float *oldeul)
2130 {
2131         if (protectflag & OB_LOCK_ROTX)
2132                 eul[0] = oldeul[0];
2133         if (protectflag & OB_LOCK_ROTY)
2134                 eul[1] = oldeul[1];
2135         if (protectflag & OB_LOCK_ROTZ)
2136                 eul[2] = oldeul[2];
2137 }
2138
2139
2140 /* this function only does the delta rotation */
2141 /* axis-angle is usually internally stored as quats... */
2142 static void protectedAxisAngleBits(short protectflag, float axis[3], float *angle, float oldAxis[3], float oldAngle)
2143 {
2144         /* check that protection flags are set */
2145         if ((protectflag & (OB_LOCK_ROTX | OB_LOCK_ROTY | OB_LOCK_ROTZ | OB_LOCK_ROTW)) == 0)
2146                 return;
2147         
2148         if (protectflag & OB_LOCK_ROT4D) {
2149                 /* axis-angle getting limited as 4D entities that they are... */
2150                 if (protectflag & OB_LOCK_ROTW)
2151                         *angle = oldAngle;
2152                 if (protectflag & OB_LOCK_ROTX)
2153                         axis[0] = oldAxis[0];
2154                 if (protectflag & OB_LOCK_ROTY)
2155                         axis[1] = oldAxis[1];
2156                 if (protectflag & OB_LOCK_ROTZ)
2157                         axis[2] = oldAxis[2];
2158         }
2159         else {
2160                 /* axis-angle get limited with euler... */
2161                 float eul[3], oldeul[3];
2162                 
2163                 axis_angle_to_eulO(eul, EULER_ORDER_DEFAULT, axis, *angle);
2164                 axis_angle_to_eulO(oldeul, EULER_ORDER_DEFAULT, oldAxis, oldAngle);
2165                 
2166                 if (protectflag & OB_LOCK_ROTX)
2167                         eul[0] = oldeul[0];
2168                 if (protectflag & OB_LOCK_ROTY)
2169                         eul[1] = oldeul[1];
2170                 if (protectflag & OB_LOCK_ROTZ)
2171                         eul[2] = oldeul[2];
2172                 
2173                 eulO_to_axis_angle(axis, angle, eul, EULER_ORDER_DEFAULT);
2174                 
2175                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
2176                 if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) {
2177                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
2178                         axis[1] = 1.0f;
2179                 }
2180         }
2181 }
2182
2183 /* this function only does the delta rotation */
2184 static void protectedQuaternionBits(short protectflag, float *quat, float *oldquat)
2185 {
2186         /* check that protection flags are set */
2187         if ((protectflag & (OB_LOCK_ROTX | OB_LOCK_ROTY | OB_LOCK_ROTZ | OB_LOCK_ROTW)) == 0)
2188                 return;
2189         
2190         if (protectflag & OB_LOCK_ROT4D) {
2191                 /* quaternions getting limited as 4D entities that they are... */
2192                 if (protectflag & OB_LOCK_ROTW)
2193                         quat[0] = oldquat[0];
2194                 if (protectflag & OB_LOCK_ROTX)
2195                         quat[1] = oldquat[1];
2196                 if (protectflag & OB_LOCK_ROTY)
2197                         quat[2] = oldquat[2];
2198                 if (protectflag & OB_LOCK_ROTZ)
2199                         quat[3] = oldquat[3];
2200         }
2201         else {
2202                 /* quaternions get limited with euler... (compatibility mode) */
2203                 float eul[3], oldeul[3], nquat[4], noldquat[4];
2204                 float qlen;
2205
2206                 qlen = normalize_qt_qt(nquat, quat);
2207                 normalize_qt_qt(noldquat, oldquat);
2208
2209                 quat_to_eul(eul, nquat);
2210                 quat_to_eul(oldeul, noldquat);
2211
2212                 if (protectflag & OB_LOCK_ROTX)
2213                         eul[0] = oldeul[0];
2214                 if (protectflag & OB_LOCK_ROTY)
2215                         eul[1] = oldeul[1];
2216                 if (protectflag & OB_LOCK_ROTZ)
2217                         eul[2] = oldeul[2];
2218
2219                 eul_to_quat(quat, eul);
2220
2221                 /* restore original quat size */
2222                 mul_qt_fl(quat, qlen);
2223                 
2224                 /* quaternions flip w sign to accumulate rotations correctly */
2225                 if ((nquat[0] < 0.0f && quat[0] > 0.0f) ||
2226                     (nquat[0] > 0.0f && quat[0] < 0.0f))
2227                 {
2228                         mul_qt_fl(quat, -1.0f);
2229                 }
2230         }
2231 }
2232
2233 /* ******************* TRANSFORM LIMITS ********************** */
2234
2235 static void constraintTransLim(TransInfo *t, TransData *td)
2236 {
2237         if (td->con) {
2238                 bConstraintTypeInfo *ctiLoc = get_constraint_typeinfo(CONSTRAINT_TYPE_LOCLIMIT);
2239                 bConstraintTypeInfo *ctiDist = get_constraint_typeinfo(CONSTRAINT_TYPE_DISTLIMIT);
2240                 
2241                 bConstraintOb cob = {NULL};
2242                 bConstraint *con;
2243                 float ctime = (float)(t->scene->r.cfra);
2244                 
2245                 /* Make a temporary bConstraintOb for using these limit constraints
2246                  *  - they only care that cob->matrix is correctly set ;-)
2247                  *      - current space should be local
2248                  */
2249                 unit_m4(cob.matrix);
2250                 copy_v3_v3(cob.matrix[3], td->loc);
2251                 
2252                 /* Evaluate valid constraints */
2253                 for (con = td->con; con; con = con->next) {
2254                         bConstraintTypeInfo *cti = NULL;
2255                         ListBase targets = {NULL, NULL};
2256                         
2257                         /* only consider constraint if enabled */
2258                         if (con->flag & CONSTRAINT_DISABLE) continue;
2259                         if (con->enforce == 0.0f) continue;
2260                         
2261                         /* only use it if it's tagged for this purpose (and the right type) */
2262                         if (con->type == CONSTRAINT_TYPE_LOCLIMIT) {
2263                                 bLocLimitConstraint *data = con->data;
2264                                 
2265                                 if ((data->flag2 & LIMIT_TRANSFORM) == 0)
2266                                         continue;
2267                                 cti = ctiLoc;
2268                         }
2269                         else if (con->type == CONSTRAINT_TYPE_DISTLIMIT) {
2270                                 bDistLimitConstraint *data = con->data;
2271                                 
2272                                 if ((data->flag & LIMITDIST_TRANSFORM) == 0)
2273                                         continue;
2274                                 cti = ctiDist;
2275                         }
2276                         
2277                         if (cti) {
2278                                 /* do space conversions */
2279                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2280                                         /* just multiply by td->mtx (this should be ok) */
2281                                         mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
2282                                 }
2283                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
2284                                         /* skip... incompatable spacetype */
2285                                         continue;
2286                                 }
2287                                 
2288                                 /* get constraint targets if needed */
2289                                 get_constraint_targets_for_solving(con, &cob, &targets, ctime);
2290                                 
2291                                 /* do constraint */
2292                                 cti->evaluate_constraint(con, &cob, &targets);
2293                                 
2294                                 /* convert spaces again */
2295                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2296                                         /* just multiply by td->smtx (this should be ok) */
2297                                         mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
2298                                 }
2299                                 
2300                                 /* free targets list */
2301                                 BLI_freelistN(&targets);
2302                         }
2303                 }
2304                 
2305                 /* copy results from cob->matrix */
2306                 copy_v3_v3(td->loc, cob.matrix[3]);
2307         }
2308 }
2309
2310 static void constraintob_from_transdata(bConstraintOb *cob, TransData *td)
2311 {
2312         /* Make a temporary bConstraintOb for use by limit constraints
2313          *  - they only care that cob->matrix is correctly set ;-)
2314          *      - current space should be local
2315          */
2316         memset(cob, 0, sizeof(bConstraintOb));
2317         if (td->ext) {
2318                 if (td->ext->rotOrder == ROT_MODE_QUAT) {
2319                         /* quats */
2320                         /* objects and bones do normalization first too, otherwise
2321                          * we don't necessarily end up with a rotation matrix, and
2322                          * then conversion back to quat gives a different result */
2323                         float quat[4];
2324                         normalize_qt_qt(quat, td->ext->quat);
2325                         quat_to_mat4(cob->matrix, quat);
2326                 }
2327                 else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2328                         /* axis angle */
2329                         axis_angle_to_mat4(cob->matrix, &td->ext->quat[1], td->ext->quat[0]);
2330                 }
2331                 else {
2332                         /* eulers */
2333                         eulO_to_mat4(cob->matrix, td->ext->rot, td->ext->rotOrder);
2334                 }
2335         }
2336 }
2337
2338 static void constraintRotLim(TransInfo *UNUSED(t), TransData *td)
2339 {
2340         if (td->con) {
2341                 bConstraintTypeInfo *cti = get_constraint_typeinfo(CONSTRAINT_TYPE_ROTLIMIT);
2342                 bConstraintOb cob;
2343                 bConstraint *con;
2344                 int do_limit = FALSE;
2345
2346                 /* Evaluate valid constraints */
2347                 for (con = td->con; con; con = con->next) {
2348                         /* only consider constraint if enabled */
2349                         if (con->flag & CONSTRAINT_DISABLE) continue;
2350                         if (con->enforce == 0.0f) continue;
2351
2352                         /* we're only interested in Limit-Rotation constraints */
2353                         if (con->type == CONSTRAINT_TYPE_ROTLIMIT) {
2354                                 bRotLimitConstraint *data = con->data;
2355
2356                                 /* only use it if it's tagged for this purpose */
2357                                 if ((data->flag2 & LIMIT_TRANSFORM) == 0)
2358                                         continue;
2359
2360                                 /* skip incompatable spacetypes */
2361                                 if (!ELEM(con->ownspace, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL))
2362                                         continue;
2363
2364                                 /* only do conversion if necessary, to preserve quats and eulers */
2365                                 if (do_limit == FALSE) {
2366                                         constraintob_from_transdata(&cob, td);
2367                                         do_limit = TRUE;
2368                                 }
2369
2370                                 /* do space conversions */
2371                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2372                                         /* just multiply by td->mtx (this should be ok) */
2373                                         mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
2374                                 }
2375                                 
2376                                 /* do constraint */
2377                                 cti->evaluate_constraint(con, &cob, NULL);
2378                                 
2379                                 /* convert spaces again */
2380                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2381                                         /* just multiply by td->smtx (this should be ok) */
2382                                         mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
2383                                 }
2384                         }
2385                 }
2386                 
2387                 if (do_limit) {
2388                         /* copy results from cob->matrix */
2389                         if (td->ext->rotOrder == ROT_MODE_QUAT) {
2390                                 /* quats */
2391                                 mat4_to_quat(td->ext->quat, cob.matrix);
2392                         }
2393                         else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2394                                 /* axis angle */
2395                                 mat4_to_axis_angle(&td->ext->quat[1], &td->ext->quat[0], cob.matrix);
2396                         }
2397                         else {
2398                                 /* eulers */
2399                                 mat4_to_eulO(td->ext->rot, td->ext->rotOrder, cob.matrix);
2400                         }
2401                 }
2402         }
2403 }
2404
2405 static void constraintSizeLim(TransInfo *t, TransData *td)
2406 {
2407         if (td->con && td->ext) {
2408                 bConstraintTypeInfo *cti = get_constraint_typeinfo(CONSTRAINT_TYPE_SIZELIMIT);
2409                 bConstraintOb cob = {NULL};
2410                 bConstraint *con;
2411                 
2412                 /* Make a temporary bConstraintOb for using these limit constraints
2413                  *  - they only care that cob->matrix is correctly set ;-)
2414                  *      - current space should be local
2415                  */
2416                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
2417                         /* scale val and reset size */
2418                         return; // TODO: fix this case
2419                 }
2420                 else {
2421                         /* Reset val if SINGLESIZE but using a constraint */
2422                         if (td->flag & TD_SINGLESIZE)
2423                                 return;
2424                         
2425                         size_to_mat4(cob.matrix, td->ext->size);
2426                 }
2427                 
2428                 /* Evaluate valid constraints */
2429                 for (con = td->con; con; con = con->next) {
2430                         /* only consider constraint if enabled */
2431                         if (con->flag & CONSTRAINT_DISABLE) continue;
2432                         if (con->enforce == 0.0f) continue;
2433                         
2434                         /* we're only interested in Limit-Scale constraints */
2435                         if (con->type == CONSTRAINT_TYPE_SIZELIMIT) {
2436                                 bSizeLimitConstraint *data = con->data;
2437                                 
2438                                 /* only use it if it's tagged for this purpose */
2439                                 if ((data->flag2 & LIMIT_TRANSFORM) == 0)
2440                                         continue;
2441                                 
2442                                 /* do space conversions */
2443                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2444                                         /* just multiply by td->mtx (this should be ok) */
2445                                         mul_m4_m3m4(cob.matrix, td->mtx, cob.matrix);
2446                                 }
2447                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
2448                                         /* skip... incompatible spacetype */
2449                                         continue;
2450                                 }
2451                                 
2452                                 /* do constraint */
2453                                 cti->evaluate_constraint(con, &cob, NULL);
2454                                 
2455                                 /* convert spaces again */
2456                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
2457                                         /* just multiply by td->smtx (this should be ok) */
2458                                         mul_m4_m3m4(cob.matrix, td->smtx, cob.matrix);
2459                                 }
2460                         }
2461                 }
2462
2463                 /* copy results from cob->matrix */
2464                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
2465                         /* scale val and reset size */
2466                         return; // TODO: fix this case
2467                 }
2468                 else {
2469                         /* Reset val if SINGLESIZE but using a constraint */
2470                         if (td->flag & TD_SINGLESIZE)
2471                                 return;
2472
2473                         mat4_to_size(td->ext->size, cob.matrix);
2474                 }
2475         }
2476 }
2477
2478 /* ************************** WARP *************************** */
2479
2480 static void postInputWarp(TransInfo *t, float values[3])
2481 {
2482         mul_v3_fl(values, (float)(M_PI * 2));
2483
2484         if (t->customData) { /* non-null value indicates reversed input */
2485                 negate_v3(values);
2486         }
2487 }
2488
2489 void initWarp(TransInfo *t)
2490 {
2491         float max[3], min[3];
2492         int i;
2493         
2494         t->mode = TFM_WARP;
2495         t->transform = Warp;
2496         t->handleEvent = handleEventWarp;
2497         
2498         setInputPostFct(&t->mouse, postInputWarp);
2499         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
2500         
2501         t->idx_max = 0;
2502         t->num.idx_max = 0;
2503         t->snap[0] = 0.0f;
2504         t->snap[1] = 5.0f / 180.0f * (float)M_PI;
2505         t->snap[2] = 1.0f / 180.0f * (float)M_PI;
2506         
2507         t->num.increment = 1.0f;
2508
2509         t->flag |= T_NO_CONSTRAINT;
2510         
2511         /* we need min/max in view space */
2512         for (i = 0; i < t->total; i++) {
2513                 float center[3];
2514                 copy_v3_v3(center, t->data[i].center);
2515                 mul_m3_v3(t->data[i].mtx, center);
2516                 mul_m4_v3(t->viewmat, center);
2517                 sub_v3_v3(center, t->viewmat[3]);
2518                 if (i) {
2519                         minmax_v3v3_v3(min, max, center);
2520                 }
2521                 else {
2522                         copy_v3_v3(max, center);
2523                         copy_v3_v3(min, center);
2524                 }
2525         }
2526
2527         mid_v3_v3v3(t->center, min, max);
2528
2529         if (max[0] == min[0]) max[0] += 0.1f;  /* not optimal, but flipping is better than invalid garbage (i.e. division by zero!) */
2530         t->val = (max[0] - min[0]) / 2.0f; /* t->val is X dimension projected boundbox */
2531 }
2532
2533 int handleEventWarp(TransInfo *t, wmEvent *event)
2534 {
2535         int status = 0;
2536         
2537         if (event->type == MIDDLEMOUSE && event->val == KM_PRESS) {
2538                 // Use customData pointer to signal warp direction
2539                 if (t->customData == NULL)
2540                         t->customData = (void *)1;
2541                 else
2542                         t->customData = NULL;
2543                 
2544                 status = 1;
2545         }
2546         
2547         return status;
2548 }
2549
2550 int Warp(TransInfo *t, const int UNUSED(mval[2]))
2551 {
2552         TransData *td = t->data;
2553         float vec[3], circumfac, dist, phi0, co, si, *curs, cursor[3], gcursor[3];
2554         int i;
2555         char str[50];
2556         
2557         curs = give_cursor(t->scene, t->view);
2558         /*
2559          * gcursor is the one used for helpline.
2560          * It has to be in the same space as the drawing loop
2561          * (that means it needs to be in the object's space when in edit mode and
2562          *  in global space in object mode)
2563          *
2564          * cursor is used for calculations.
2565          * It needs to be in view space, but we need to take object's offset
2566          * into account if in Edit mode.
2567          */
2568         copy_v3_v3(cursor, curs);
2569         copy_v3_v3(gcursor, cursor);
2570         if (t->flag & T_EDIT) {
2571                 sub_v3_v3(cursor, t->obedit->obmat[3]);
2572                 sub_v3_v3(gcursor, t->obedit->obmat[3]);
2573                 mul_m3_v3(t->data->smtx, gcursor);
2574         }
2575         mul_m4_v3(t->viewmat, cursor);
2576         sub_v3_v3(cursor, t->viewmat[3]);
2577         
2578         /* amount of radians for warp */
2579         circumfac = t->values[0];
2580         
2581         snapGrid(t, &circumfac);
2582         applyNumInput(&t->num, &circumfac);
2583         
2584         /* header print for NumInput */
2585         if (hasNumInput(&t->num)) {
2586                 char c[NUM_STR_REP_LEN];
2587                 
2588                 outputNumInput(&(t->num), c);
2589                 
2590                 sprintf(str, "Warp: %s", c);
2591
2592                 circumfac = DEG2RADF(circumfac);
2593         }
2594         else {
2595                 /* default header print */
2596                 sprintf(str, "Warp: %.3f", RAD2DEGF(circumfac));
2597         }
2598         
2599         t->values[0] = circumfac;
2600
2601         circumfac /= 2; /* only need 180 on each side to make 360 */
2602         
2603         for (i = 0; i < t->total; i++, td++) {
2604                 float loc[3];
2605                 if (td->flag & TD_NOACTION)
2606                         break;
2607                 
2608                 if (td->flag & TD_SKIP)
2609                         continue;
2610                 
2611                 /* translate point to center, rotate in such a way that outline==distance */
2612                 copy_v3_v3(vec, td->iloc);
2613                 mul_m3_v3(td->mtx, vec);
2614                 mul_m4_v3(t->viewmat, vec);
2615                 sub_v3_v3(vec, t->viewmat[3]);
2616                 
2617                 dist = vec[0] - cursor[0];
2618                 
2619                 /* t->val is X dimension projected boundbox */
2620                 phi0 = (circumfac * dist / t->val);
2621                 
2622                 vec[1] = (vec[1] - cursor[1]);
2623                 
2624                 co = (float)cos(phi0);
2625                 si = (float)sin(phi0);
2626                 loc[0] = -si * vec[1] + cursor[0];
2627                 loc[1] = co * vec[1] + cursor[1];
2628                 loc[2] = vec[2];
2629                 
2630                 mul_m4_v3(t->viewinv, loc);
2631                 sub_v3_v3(loc, t->viewinv[3]);
2632                 mul_m3_v3(td->smtx, loc);
2633                 
2634                 sub_v3_v3(loc, td->iloc);
2635                 mul_v3_fl(loc, td->factor);
2636                 add_v3_v3v3(td->loc, td->iloc, loc);
2637         }
2638         
2639         recalcData(t);
2640         
2641         ED_area_headerprint(t->sa, str);
2642         
2643         return 1;
2644 }
2645
2646 /* ************************** SHEAR *************************** */
2647
2648 static void postInputShear(TransInfo *UNUSED(t), float values[3])
2649 {
2650         mul_v3_fl(values, 0.05f);
2651 }
2652
2653 void initShear(TransInfo *t)
2654 {
2655         t->mode = TFM_SHEAR;
2656         t->transform = Shear;
2657         t->handleEvent = handleEventShear;
2658         
2659         setInputPostFct(&t->mouse, postInputShear);
2660         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2661         
2662         t->idx_max = 0;
2663         t->num.idx_max = 0;
2664         t->snap[0] = 0.0f;
2665         t->snap[1] = 0.1f;
2666         t->snap[2] = t->snap[1] * 0.1f;
2667         
2668         t->num.increment = 0.1f;
2669
2670         t->flag |= T_NO_CONSTRAINT;
2671 }
2672
2673 int handleEventShear(TransInfo *t, wmEvent *event)
2674 {
2675         int status = 0;
2676         
2677         if (event->type == MIDDLEMOUSE && event->val == KM_PRESS) {
2678                 // Use customData pointer to signal Shear direction
2679                 if (t->customData == NULL) {
2680                         initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
2681                         t->customData = (void *)1;
2682                 }
2683                 else {
2684                         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2685                         t->customData = NULL;
2686                 }
2687
2688                 status = 1;
2689         }
2690         
2691         return status;
2692 }
2693
2694
2695 int Shear(TransInfo *t, const int UNUSED(mval[2]))
2696 {
2697         TransData *td = t->data;
2698         float vec[3];
2699         float smat[3][3], tmat[3][3], totmat[3][3], persmat[3][3], persinv[3][3];
2700         float value;
2701         int i;
2702         char str[50];
2703         
2704         copy_m3_m4(persmat, t->viewmat);
2705         invert_m3_m3(persinv, persmat);
2706         
2707         value = t->values[0];
2708         
2709         snapGrid(t, &value);
2710         
2711         applyNumInput(&t->num, &value);
2712         
2713         /* header print for NumInput */
2714         if (hasNumInput(&t->num)) {
2715                 char c[NUM_STR_REP_LEN];
2716                 
2717                 outputNumInput(&(t->num), c);
2718                 
2719                 sprintf(str, "Shear: %s %s", c, t->proptext);
2720         }
2721         else {
2722                 /* default header print */
2723                 sprintf(str, "Shear: %.3f %s", value, t->proptext);
2724         }
2725         
2726         t->values[0] = value;
2727
2728         unit_m3(smat);
2729         
2730         // Custom data signals shear direction
2731         if (t->customData == NULL)
2732                 smat[1][0] = value;
2733         else
2734                 smat[0][1] = value;
2735         
2736         mul_m3_m3m3(tmat, smat, persmat);
2737         mul_m3_m3m3(totmat, persinv, tmat);
2738         
2739         for (i = 0; i < t->total; i++, td++) {
2740                 if (td->flag & TD_NOACTION)
2741                         break;
2742                 
2743                 if (td->flag & TD_SKIP)
2744                         continue;
2745                 
2746                 if (t->obedit) {
2747                         float mat3[3][3];
2748                         mul_m3_m3m3(mat3, totmat, td->mtx);
2749                         mul_m3_m3m3(tmat, td->smtx, mat3);
2750                 }
2751                 else {
2752                         copy_m3_m3(tmat, totmat);
2753                 }
2754                 sub_v3_v3v3(vec, td->center, t->center);
2755                 
2756                 mul_m3_v3(tmat, vec);
2757                 
2758                 add_v3_v3(vec, t->center);
2759                 sub_v3_v3(vec, td->center);
2760                 
2761                 mul_v3_fl(vec, td->factor);
2762                 
2763                 add_v3_v3v3(td->loc, td->iloc, vec);
2764         }
2765         
2766         recalcData(t);
2767         
2768         ED_area_headerprint(t->sa, str);
2769
2770         return 1;
2771 }
2772
2773 /* ************************** RESIZE *************************** */
2774
2775 void initResize(TransInfo *t)
2776 {
2777         t->mode = TFM_RESIZE;
2778         t->transform = Resize;
2779         
2780         initMouseInputMode(t, &t->mouse, INPUT_SPRING_FLIP);
2781         
2782         t->flag |= T_NULL_ONE;
2783         t->num.flag |= NUM_NULL_ONE;
2784         t->num.flag |= NUM_AFFECT_ALL;
2785         if (!t->obedit) {
2786                 t->flag |= T_NO_ZERO;
2787                 t->num.flag |= NUM_NO_ZERO;
2788         }
2789         
2790         t->idx_max = 2;
2791         t->num.idx_max = 2;
2792         t->snap[0] = 0.0f;
2793         t->snap[1] = 0.1f;
2794         t->snap[2] = t->snap[1] * 0.1f;
2795
2796         t->num.increment = t->snap[1];
2797 }
2798
2799 static void headerResize(TransInfo *t, float vec[3], char *str)
2800 {
2801         char tvec[NUM_STR_REP_LEN * 3];
2802         char *spos = str;
2803         if (hasNumInput(&t->num)) {
2804                 outputNumInput(&(t->num), tvec);
2805         }
2806         else {
2807                 BLI_snprintf(&tvec[0], NUM_STR_REP_LEN, "%.4f", vec[0]);
2808                 BLI_snprintf(&tvec[NUM_STR_REP_LEN], NUM_STR_REP_LEN, "%.4f", vec[1]);
2809                 BLI_snprintf(&tvec[NUM_STR_REP_LEN * 2], NUM_STR_REP_LEN, "%.4f", vec[2]);
2810         }
2811         
2812         if (t->con.mode & CON_APPLY) {
2813                 switch (t->num.idx_max) {
2814                         case 0:
2815                                 spos += sprintf(spos, "Scale: %s%s %s", &tvec[0], t->con.text, t->proptext);
2816                                 break;
2817                         case 1:
2818                                 spos += sprintf(spos, "Scale: %s : %s%s %s", &tvec[0], &tvec[NUM_STR_REP_LEN],
2819                                                 t->con.text, t->proptext);
2820                                 break;
2821                         case 2:
2822                                 spos += sprintf(spos, "Scale: %s : %s : %s%s %s", &tvec[0], &tvec[NUM_STR_REP_LEN],
2823                                                 &tvec[NUM_STR_REP_LEN * 2], t->con.text, t->proptext);
2824                 }
2825         }
2826         else {
2827                 if (t->flag & T_2D_EDIT) {
2828                         spos += sprintf(spos, "Scale X: %s   Y: %s%s %s", &tvec[0], &tvec[NUM_STR_REP_LEN],
2829                                         t->con.text, t->proptext);
2830                 }
2831                 else {
2832                         spos += sprintf(spos, "Scale X: %s   Y: %s  Z: %s%s %s", &tvec[0], &tvec[NUM_STR_REP_LEN],
2833                                         &tvec[NUM_STR_REP_LEN * 2], t->con.text, t->proptext);
2834                 }
2835         }
2836         
2837         if (t->flag & (T_PROP_EDIT | T_PROP_CONNECTED)) {
2838                 spos += sprintf(spos, " Proportional size: %.2f", t->prop_size);
2839         }
2840
2841         (void)spos;
2842 }
2843
2844 #define SIGN(a)     (a<-FLT_EPSILON ? 1 : a>FLT_EPSILON ? 2 : 3)
2845 #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)
2846
2847 /* smat is reference matrix, only scaled */
2848 static void TransMat3ToSize(float mat[][3], float smat[][3], float *size)
2849 {
2850         float vec[3];
2851         
2852         copy_v3_v3(vec, mat[0]);
2853         size[0] = normalize_v3(vec);
2854         copy_v3_v3(vec, mat[1]);
2855         size[1] = normalize_v3(vec);
2856         copy_v3_v3(vec, mat[2]);
2857         size[2] = normalize_v3(vec);
2858         
2859         /* first tried with dotproduct... but the sign flip is crucial */
2860         if (VECSIGNFLIP(mat[0], smat[0]) ) size[0] = -size[0];
2861         if (VECSIGNFLIP(mat[1], smat[1]) ) size[1] = -size[1];
2862         if (VECSIGNFLIP(mat[2], smat[2]) ) size[2] = -size[2];
2863 }
2864
2865
2866 static void ElementResize(TransInfo *t, TransData *td, float mat[3][3])
2867 {
2868         float tmat[3][3], smat[3][3], center[3];
2869         float vec[3];
2870         
2871         if (t->flag & T_EDIT) {
2872                 mul_m3_m3m3(smat, mat, td->mtx);
2873                 mul_m3_m3m3(tmat, td->smtx, smat);
2874         }
2875         else {
2876                 copy_m3_m3(tmat, mat);
2877         }
2878         
2879         if (t->con.applySize) {
2880                 t->con.applySize(t, td, tmat);
2881         }
2882         
2883         /* local constraint shouldn't alter center */
2884         if ((t->around == V3D_LOCAL) &&
2885             (   (t->flag & (T_OBJECT | T_POSE)) ||
2886                 ((t->flag & T_EDIT) && (t->settings->selectmode & (SCE_SELECT_EDGE | SCE_SELECT_FACE))) ||
2887                 (t->obedit && t->obedit->type == OB_ARMATURE))
2888             )
2889         {
2890                 copy_v3_v3(center, td->center);
2891         }
2892         else if (t->options & CTX_MOVIECLIP) {
2893                 copy_v3_v3(center, td->center);
2894         }
2895         else {
2896                 copy_v3_v3(center, t->center);
2897         }
2898
2899         if (td->ext) {
2900                 float fsize[3];
2901                 
2902                 if (t->flag & (T_OBJECT | T_TEXTURE | T_POSE)) {
2903                         float obsizemat[3][3];
2904                         /* Reorient the size mat to fit the oriented object. */
2905                         mul_m3_m3m3(obsizemat, tmat, td->axismtx);
2906                         /* print_m3("obsizemat", obsizemat); */
2907                         TransMat3ToSize(obsizemat, td->axismtx, fsize);
2908                         /* print_v3("fsize", fsize); */
2909                 }
2910                 else {
2911                         mat3_to_size(fsize, tmat);
2912                 }
2913                 
2914                 protectedSizeBits(td->protectflag, fsize);
2915                 
2916                 if ((t->flag & T_V3D_ALIGN) == 0) {   /* align mode doesn't resize objects itself */
2917                         if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
2918                                 /* scale val and reset size */
2919                                 *td->val = td->ival * (1 + (fsize[0] - 1) * td->factor);
2920                                 
2921                                 td->ext->size[0] = td->ext->isize[0];
2922                                 td->ext->size[1] = td->ext->isize[1];
2923                                 td->ext->size[2] = td->ext->isize[2];
2924                         }
2925                    &