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