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