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