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