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