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