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