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