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