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