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