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