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