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