Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_fly.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/editors/space_view3d/view3d_fly.c
24  *  \ingroup spview3d
25  */
26
27 /* defines VIEW3D_OT_fly modal operator */
28
29 #ifdef WITH_INPUT_NDOF
30 //#  define NDOF_FLY_DEBUG
31 //#  define NDOF_FLY_DRAW_TOOMUCH  /* is this needed for ndof? - commented so redraw doesn't thrash - campbell */
32 #endif /* WITH_INPUT_NDOF */
33
34 #include "DNA_object_types.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40
41 #include "BKE_context.h"
42 #include "BKE_report.h"
43
44 #include "BLT_translation.h"
45
46 #include "BIF_gl.h"
47
48 #include "WM_api.h"
49 #include "WM_types.h"
50
51 #include "ED_screen.h"
52 #include "ED_space_api.h"
53
54 #include "PIL_time.h" /* smoothview */
55
56 #include "UI_interface.h"
57 #include "UI_resources.h"
58
59 #include "GPU_immediate.h"
60
61 #include "DEG_depsgraph.h"
62
63 #include "view3d_intern.h"  /* own include */
64
65 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
66 enum {
67         FLY_MODAL_CANCEL = 1,
68         FLY_MODAL_CONFIRM,
69         FLY_MODAL_ACCELERATE,
70         FLY_MODAL_DECELERATE,
71         FLY_MODAL_PAN_ENABLE,
72         FLY_MODAL_PAN_DISABLE,
73         FLY_MODAL_DIR_FORWARD,
74         FLY_MODAL_DIR_BACKWARD,
75         FLY_MODAL_DIR_LEFT,
76         FLY_MODAL_DIR_RIGHT,
77         FLY_MODAL_DIR_UP,
78         FLY_MODAL_DIR_DOWN,
79         FLY_MODAL_AXIS_LOCK_X,
80         FLY_MODAL_AXIS_LOCK_Z,
81         FLY_MODAL_PRECISION_ENABLE,
82         FLY_MODAL_PRECISION_DISABLE,
83         FLY_MODAL_FREELOOK_ENABLE,
84         FLY_MODAL_FREELOOK_DISABLE,
85         FLY_MODAL_SPEED,        /* mousepan typically */
86 };
87
88 /* relative view axis locking - xlock, zlock */
89 typedef enum eFlyPanState {
90         /* disabled */
91         FLY_AXISLOCK_STATE_OFF    = 0,
92
93         /* enabled but not checking because mouse hasn't moved outside the margin since locking was checked an not needed
94          * when the mouse moves, locking is set to 2 so checks are done. */
95         FLY_AXISLOCK_STATE_IDLE   = 1,
96
97         /* mouse moved and checking needed, if no view altering is done its changed back to #FLY_AXISLOCK_STATE_IDLE */
98         FLY_AXISLOCK_STATE_ACTIVE = 2
99 } eFlyPanState;
100
101 /* called in transform_ops.c, on each regeneration of keymaps  */
102 void fly_modal_keymap(wmKeyConfig *keyconf)
103 {
104         static const EnumPropertyItem modal_items[] = {
105                 {FLY_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
106                 {FLY_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
107
108                 {FLY_MODAL_DIR_FORWARD, "FORWARD", 0, "Forward", ""},
109                 {FLY_MODAL_DIR_BACKWARD, "BACKWARD", 0, "Backward", ""},
110                 {FLY_MODAL_DIR_LEFT, "LEFT", 0, "Left", ""},
111                 {FLY_MODAL_DIR_RIGHT, "RIGHT", 0, "Right", ""},
112                 {FLY_MODAL_DIR_UP, "UP", 0, "Up", ""},
113                 {FLY_MODAL_DIR_DOWN, "DOWN", 0, "Down", ""},
114
115                 {FLY_MODAL_PAN_ENABLE, "PAN_ENABLE", 0, "Pan", ""},
116                 {FLY_MODAL_PAN_DISABLE, "PAN_DISABLE", 0, "Pan (Off)", ""},
117
118                 {FLY_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""},
119                 {FLY_MODAL_DECELERATE, "DECELERATE", 0, "Decelerate", ""},
120
121                 {FLY_MODAL_AXIS_LOCK_X, "AXIS_LOCK_X", 0, "X Axis Correction", "X axis correction (toggle)"},
122                 {FLY_MODAL_AXIS_LOCK_Z, "AXIS_LOCK_Z", 0, "X Axis Correction", "Z axis correction (toggle)"},
123
124                 {FLY_MODAL_PRECISION_ENABLE, "PRECISION_ENABLE", 0, "Precision", ""},
125                 {FLY_MODAL_PRECISION_DISABLE, "PRECISION_DISABLE", 0, "Precision (Off)", ""},
126
127                 {FLY_MODAL_FREELOOK_ENABLE, "FREELOOK_ENABLE", 0, "Rotation", ""},
128                 {FLY_MODAL_FREELOOK_DISABLE, "FREELOOK_DISABLE", 0, "Rotation (Off)", ""},
129
130                 {0, NULL, 0, NULL, NULL}};
131
132         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Fly Modal");
133
134         /* this function is called for each spacetype, only needs to add map once */
135         if (keymap && keymap->modal_items)
136                 return;
137
138         keymap = WM_modalkeymap_add(keyconf, "View3D Fly Modal", modal_items);
139
140         /* assign map to operators */
141         WM_modalkeymap_assign(keymap, "VIEW3D_OT_fly");
142 }
143
144 typedef struct FlyInfo {
145         /* context stuff */
146         RegionView3D *rv3d;
147         View3D *v3d;
148         ARegion *ar;
149         struct Depsgraph *depsgraph;
150         Scene *scene;
151
152         wmTimer *timer; /* needed for redraws */
153
154         short state;
155         bool redraw;
156         bool use_precision;
157         /* if the user presses shift they can look about
158          * without moving the direction there looking */
159         bool use_freelook;
160
161         int mval[2]; /* latest 2D mouse values */
162         int center_mval[2]; /* center mouse values */
163         float width, height; /* camera viewport dimensions */
164
165 #ifdef WITH_INPUT_NDOF
166         wmNDOFMotionData *ndof;  /* latest 3D mouse values */
167 #endif
168
169         /* fly state state */
170         float speed; /* the speed the view is moving per redraw */
171         short axis; /* Axis index to move along by default Z to move along the view */
172         bool pan_view; /* when true, pan the view instead of rotating */
173
174         eFlyPanState xlock, zlock;
175         float xlock_momentum, zlock_momentum; /* nicer dynamics */
176         float grid; /* world scale 1.0 default */
177
178         /* compare between last state */
179         double time_lastwheel; /* used to accelerate when using the mousewheel a lot */
180         double time_lastdraw; /* time between draws */
181
182         void *draw_handle_pixel;
183
184         /* use for some lag */
185         float dvec_prev[3]; /* old for some lag */
186
187         struct View3DCameraControl *v3d_camera_control;
188
189 } FlyInfo;
190
191 static void drawFlyPixel(const struct bContext *UNUSED(C), ARegion *UNUSED(ar), void *arg)
192 {
193         FlyInfo *fly = arg;
194         rctf viewborder;
195         int xoff, yoff;
196         float x1, x2, y1, y2;
197
198         if (fly->scene->camera) {
199                 ED_view3d_calc_camera_border(fly->scene, fly->depsgraph, fly->ar, fly->v3d, fly->rv3d, &viewborder, false);
200                 xoff = viewborder.xmin;
201                 yoff = viewborder.ymin;
202         }
203         else {
204                 xoff = 0;
205                 yoff = 0;
206         }
207
208         /* draws 4 edge brackets that frame the safe area where the
209          * mouse can move during fly mode without spinning the view */
210
211         x1 = xoff + 0.45f * fly->width;
212         y1 = yoff + 0.45f * fly->height;
213         x2 = xoff + 0.55f * fly->width;
214         y2 = yoff + 0.55f * fly->height;
215
216         GPUVertFormat *format = immVertexFormat();
217         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
218
219         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
220
221         immUniformThemeColor(TH_VIEW_OVERLAY);
222
223         immBegin(GPU_PRIM_LINES, 16);
224
225         /* bottom left */
226         immVertex2f(pos, x1, y1);
227         immVertex2f(pos, x1, y1 + 5);
228
229         immVertex2f(pos, x1, y1);
230         immVertex2f(pos, x1 + 5, y1);
231
232         /* top right */
233         immVertex2f(pos, x2, y2);
234         immVertex2f(pos, x2, y2 - 5);
235
236         immVertex2f(pos, x2, y2);
237         immVertex2f(pos, x2 - 5, y2);
238
239         /* top left */
240         immVertex2f(pos, x1, y2);
241         immVertex2f(pos, x1, y2 - 5);
242
243         immVertex2f(pos, x1, y2);
244         immVertex2f(pos, x1 + 5, y2);
245
246         /* bottom right */
247         immVertex2f(pos, x2, y1);
248         immVertex2f(pos, x2, y1 + 5);
249
250         immVertex2f(pos, x2, y1);
251         immVertex2f(pos, x2 - 5, y1);
252
253         immEnd();
254         immUnbindProgram();
255 }
256
257 static void fly_update_header(bContext *C, wmOperator *op, FlyInfo *fly)
258 {
259         char header[UI_MAX_DRAW_STR];
260         char buf[UI_MAX_DRAW_STR];
261
262         char *p = buf;
263         int available_len = sizeof(buf);
264
265 #define WM_MODALKEY(_id) \
266         WM_modalkeymap_operator_items_to_string_buf(op->type, (_id), true, UI_MAX_SHORTCUT_STR, &available_len, &p)
267
268         BLI_snprintf(header, sizeof(header), IFACE_("%s: confirm, %s: cancel, "
269                                                     "%s: pan enable, "
270                                                     "%s|%s|%s|%s|%s|%s: direction, "
271                                                     "%s: slow, %s: free look, "
272                                                     "%s: Upright x axis (%s), "
273                                                     "%s: Upright z axis (%s), "
274                                                     "%s: increase  speed, %s: decrease speed"),
275                      WM_MODALKEY(FLY_MODAL_CONFIRM), WM_MODALKEY(FLY_MODAL_CANCEL),
276                      WM_MODALKEY(FLY_MODAL_PAN_ENABLE),
277                      WM_MODALKEY(FLY_MODAL_DIR_FORWARD), WM_MODALKEY(FLY_MODAL_DIR_LEFT),
278                      WM_MODALKEY(FLY_MODAL_DIR_BACKWARD), WM_MODALKEY(FLY_MODAL_DIR_RIGHT),
279                      WM_MODALKEY(FLY_MODAL_DIR_UP), WM_MODALKEY(FLY_MODAL_DIR_DOWN),
280                      WM_MODALKEY(FLY_MODAL_PRECISION_ENABLE), WM_MODALKEY(FLY_MODAL_FREELOOK_ENABLE),
281                      WM_MODALKEY(FLY_MODAL_AXIS_LOCK_X), WM_bool_as_string(fly->xlock != FLY_AXISLOCK_STATE_OFF),
282                      WM_MODALKEY(FLY_MODAL_AXIS_LOCK_Z), WM_bool_as_string(fly->zlock != FLY_AXISLOCK_STATE_OFF),
283                      WM_MODALKEY(FLY_MODAL_ACCELERATE), WM_MODALKEY(FLY_MODAL_DECELERATE));
284
285 #undef WM_MODALKEY
286
287         ED_workspace_status_text(C, header);
288 }
289
290 /* FlyInfo->state */
291 enum {
292         FLY_RUNNING     = 0,
293         FLY_CANCEL      = 1,
294         FLY_CONFIRM     = 2,
295 };
296
297 static bool initFlyInfo(bContext *C, FlyInfo *fly, wmOperator *op, const wmEvent *event)
298 {
299         wmWindow *win = CTX_wm_window(C);
300
301         rctf viewborder;
302
303         float upvec[3]; /* tmp */
304         float mat[3][3];
305
306         fly->rv3d = CTX_wm_region_view3d(C);
307         fly->v3d = CTX_wm_view3d(C);
308         fly->ar = CTX_wm_region(C);
309         fly->depsgraph = CTX_data_depsgraph(C);
310         fly->scene = CTX_data_scene(C);
311
312 #ifdef NDOF_FLY_DEBUG
313         puts("\n-- fly begin --");
314 #endif
315
316         /* sanity check: for rare but possible case (if lib-linking the camera fails) */
317         if ((fly->rv3d->persp == RV3D_CAMOB) && (fly->v3d->camera == NULL)) {
318                 fly->rv3d->persp = RV3D_PERSP;
319         }
320
321         if (fly->rv3d->persp == RV3D_CAMOB && ID_IS_LINKED(fly->v3d->camera)) {
322                 BKE_report(op->reports, RPT_ERROR, "Cannot fly a camera from an external library");
323                 return false;
324         }
325
326         if (ED_view3d_offset_lock_check(fly->v3d, fly->rv3d)) {
327                 BKE_report(op->reports, RPT_ERROR, "Cannot fly when the view offset is locked");
328                 return false;
329         }
330
331         if (fly->rv3d->persp == RV3D_CAMOB && fly->v3d->camera->constraints.first) {
332                 BKE_report(op->reports, RPT_ERROR, "Cannot fly an object with constraints");
333                 return false;
334         }
335
336         fly->state = FLY_RUNNING;
337         fly->speed = 0.0f;
338         fly->axis = 2;
339         fly->pan_view = false;
340         fly->xlock = FLY_AXISLOCK_STATE_OFF;
341         fly->zlock = FLY_AXISLOCK_STATE_OFF;
342         fly->xlock_momentum = 0.0f;
343         fly->zlock_momentum = 0.0f;
344         fly->grid = 1.0f;
345         fly->use_precision = false;
346         fly->use_freelook = false;
347
348 #ifdef NDOF_FLY_DRAW_TOOMUCH
349         fly->redraw = 1;
350 #endif
351         zero_v3(fly->dvec_prev);
352
353         fly->timer = WM_event_add_timer(CTX_wm_manager(C), win, TIMER, 0.01f);
354
355         copy_v2_v2_int(fly->mval, event->mval);
356
357 #ifdef WITH_INPUT_NDOF
358         fly->ndof = NULL;
359 #endif
360
361         fly->time_lastdraw = fly->time_lastwheel = PIL_check_seconds_timer();
362
363         fly->draw_handle_pixel = ED_region_draw_cb_activate(fly->ar->type, drawFlyPixel, fly, REGION_DRAW_POST_PIXEL);
364
365         fly->rv3d->rflag |= RV3D_NAVIGATING;
366
367         /* detect whether to start with Z locking */
368         copy_v3_fl3(upvec, 1.0f, 0.0f, 0.0f);
369         copy_m3_m4(mat, fly->rv3d->viewinv);
370         mul_m3_v3(mat, upvec);
371         if (fabsf(upvec[2]) < 0.1f) {
372                 fly->zlock = FLY_AXISLOCK_STATE_IDLE;
373         }
374
375         fly->v3d_camera_control = ED_view3d_cameracontrol_acquire(
376                 CTX_data_depsgraph(C), fly->scene, fly->v3d, fly->rv3d,
377                 (U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0);
378
379         /* calculate center */
380         if (fly->scene->camera) {
381                 ED_view3d_calc_camera_border(fly->scene, fly->depsgraph, fly->ar, fly->v3d, fly->rv3d, &viewborder, false);
382
383                 fly->width = BLI_rctf_size_x(&viewborder);
384                 fly->height = BLI_rctf_size_y(&viewborder);
385
386                 fly->center_mval[0] = viewborder.xmin + fly->width / 2;
387                 fly->center_mval[1] = viewborder.ymin + fly->height / 2;
388         }
389         else {
390                 fly->width = fly->ar->winx;
391                 fly->height = fly->ar->winy;
392
393                 fly->center_mval[0] = fly->width / 2;
394                 fly->center_mval[1] = fly->height / 2;
395         }
396
397         /* center the mouse, probably the UI mafia are against this but without its quite annoying */
398         WM_cursor_warp(win, fly->ar->winrct.xmin + fly->center_mval[0], fly->ar->winrct.ymin + fly->center_mval[1]);
399
400         fly_update_header(C, op, fly);
401         return 1;
402 }
403
404 static int flyEnd(bContext *C, FlyInfo *fly)
405 {
406         wmWindow *win;
407         RegionView3D *rv3d;
408
409         if (fly->state == FLY_RUNNING)
410                 return OPERATOR_RUNNING_MODAL;
411
412 #ifdef NDOF_FLY_DEBUG
413         puts("\n-- fly end --");
414 #endif
415
416         win = CTX_wm_window(C);
417         rv3d = fly->rv3d;
418
419         WM_event_remove_timer(CTX_wm_manager(C), win, fly->timer);
420
421         ED_region_draw_cb_exit(fly->ar->type, fly->draw_handle_pixel);
422
423         ED_view3d_cameracontrol_release(fly->v3d_camera_control, fly->state == FLY_CANCEL);
424
425         rv3d->rflag &= ~RV3D_NAVIGATING;
426
427 #ifdef WITH_INPUT_NDOF
428         if (fly->ndof)
429                 MEM_freeN(fly->ndof);
430 #endif
431
432         if (fly->state == FLY_CONFIRM) {
433                 MEM_freeN(fly);
434                 return OPERATOR_FINISHED;
435         }
436
437         MEM_freeN(fly);
438         return OPERATOR_CANCELLED;
439 }
440
441 static void flyEvent(bContext *C, wmOperator *op, FlyInfo *fly, const wmEvent *event)
442 {
443         if (event->type == TIMER && event->customdata == fly->timer) {
444                 fly->redraw = 1;
445         }
446         else if (event->type == MOUSEMOVE) {
447                 copy_v2_v2_int(fly->mval, event->mval);
448         }
449 #ifdef WITH_INPUT_NDOF
450         else if (event->type == NDOF_MOTION) {
451                 /* do these automagically get delivered? yes. */
452                 // puts("ndof motion detected in fly mode!");
453                 // static const char *tag_name = "3D mouse position";
454
455                 const wmNDOFMotionData *incoming_ndof = event->customdata;
456                 switch (incoming_ndof->progress) {
457                         case P_STARTING:
458                                 /* start keeping track of 3D mouse position */
459 #  ifdef NDOF_FLY_DEBUG
460                                 puts("start keeping track of 3D mouse position");
461 #  endif
462                                 /* fall-through */
463                         case P_IN_PROGRESS:
464                                 /* update 3D mouse position */
465 #  ifdef NDOF_FLY_DEBUG
466                                 putchar('.'); fflush(stdout);
467 #  endif
468                                 if (fly->ndof == NULL) {
469                                         // fly->ndof = MEM_mallocN(sizeof(wmNDOFMotionData), tag_name);
470                                         fly->ndof = MEM_dupallocN(incoming_ndof);
471                                         // fly->ndof = malloc(sizeof(wmNDOFMotionData));
472                                 }
473                                 else {
474                                         memcpy(fly->ndof, incoming_ndof, sizeof(wmNDOFMotionData));
475                                 }
476                                 break;
477                         case P_FINISHING:
478                                 /* stop keeping track of 3D mouse position */
479 #  ifdef NDOF_FLY_DEBUG
480                                 puts("stop keeping track of 3D mouse position");
481 #  endif
482                                 if (fly->ndof) {
483                                         MEM_freeN(fly->ndof);
484                                         // free(fly->ndof);
485                                         fly->ndof = NULL;
486                                 }
487                                 /* update the time else the view will jump when 2D mouse/timer resume */
488                                 fly->time_lastdraw = PIL_check_seconds_timer();
489                                 break;
490                         default:
491                                 break; /* should always be one of the above 3 */
492                 }
493         }
494 #endif /* WITH_INPUT_NDOF */
495         /* handle modal keymap first */
496         else if (event->type == EVT_MODAL_MAP) {
497                 switch (event->val) {
498                         case FLY_MODAL_CANCEL:
499                                 fly->state = FLY_CANCEL;
500                                 break;
501                         case FLY_MODAL_CONFIRM:
502                                 fly->state = FLY_CONFIRM;
503                                 break;
504
505                         /* speed adjusting with mousepan (trackpad) */
506                         case FLY_MODAL_SPEED:
507                         {
508                                 float fac = 0.02f * (event->prevy - event->y);
509
510                                 /* allowing to brake immediate */
511                                 if (fac > 0.0f && fly->speed < 0.0f)
512                                         fly->speed = 0.0f;
513                                 else if (fac < 0.0f && fly->speed > 0.0f)
514                                         fly->speed = 0.0f;
515                                 else
516                                         fly->speed += fly->grid * fac;
517
518                                 break;
519                         }
520                         case FLY_MODAL_ACCELERATE:
521                         {
522                                 double time_currwheel;
523                                 float time_wheel;
524
525                                 /* not quite correct but avoids confusion WASD/arrow keys 'locking up' */
526                                 if (fly->axis == -1) {
527                                         fly->axis = 2;
528                                         fly->speed = fabsf(fly->speed);
529                                 }
530
531                                 time_currwheel = PIL_check_seconds_timer();
532                                 time_wheel = (float)(time_currwheel - fly->time_lastwheel);
533                                 fly->time_lastwheel = time_currwheel;
534                                 /* Mouse wheel delays range from (0.5 == slow) to (0.01 == fast) */
535                                 time_wheel = 1.0f + (10.0f - (20.0f * min_ff(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
536
537                                 if (fly->speed < 0.0f) {
538                                         fly->speed = 0.0f;
539                                 }
540                                 else {
541                                         fly->speed += fly->grid * time_wheel * (fly->use_precision ? 0.1f : 1.0f);
542                                 }
543                                 break;
544                         }
545                         case FLY_MODAL_DECELERATE:
546                         {
547                                 double time_currwheel;
548                                 float time_wheel;
549
550                                 /* not quite correct but avoids confusion WASD/arrow keys 'locking up' */
551                                 if (fly->axis == -1) {
552                                         fly->axis = 2;
553                                         fly->speed = -fabsf(fly->speed);
554                                 }
555
556                                 time_currwheel = PIL_check_seconds_timer();
557                                 time_wheel = (float)(time_currwheel - fly->time_lastwheel);
558                                 fly->time_lastwheel = time_currwheel;
559                                 time_wheel = 1.0f + (10.0f - (20.0f * min_ff(time_wheel, 0.5f))); /* 0-0.5 -> 0-5.0 */
560
561                                 if (fly->speed > 0.0f) {
562                                         fly->speed = 0;
563                                 }
564                                 else {
565                                         fly->speed -= fly->grid * time_wheel * (fly->use_precision ? 0.1f : 1.0f);
566                                 }
567                                 break;
568                         }
569                         case FLY_MODAL_PAN_ENABLE:
570                                 fly->pan_view = true;
571                                 break;
572                         case FLY_MODAL_PAN_DISABLE:
573                                 fly->pan_view = false;
574                                 break;
575
576                         /* implement WASD keys,
577                          * comments only for 'forward '*/
578                         case FLY_MODAL_DIR_FORWARD:
579                                 if (fly->axis == 2 && fly->speed < 0.0f) { /* reverse direction stops, tap again to continue */
580                                         fly->axis = -1;
581                                 }
582                                 else {
583                                         /* flip speed rather than stopping, game like motion,
584                                          * else increase like mousewheel if were already moving in that direction */
585                                         if (fly->speed < 0.0f)   fly->speed = -fly->speed;
586                                         else if (fly->axis == 2) fly->speed += fly->grid;
587                                         fly->axis = 2;
588                                 }
589                                 break;
590                         case FLY_MODAL_DIR_BACKWARD:
591                                 if (fly->axis == 2 && fly->speed > 0.0f) {
592                                         fly->axis = -1;
593                                 }
594                                 else {
595                                         if (fly->speed > 0.0f)   fly->speed = -fly->speed;
596                                         else if (fly->axis == 2) fly->speed -= fly->grid;
597
598                                         fly->axis = 2;
599                                 }
600                                 break;
601                         case FLY_MODAL_DIR_LEFT:
602                                 if (fly->axis == 0 && fly->speed < 0.0f) {
603                                         fly->axis = -1;
604                                 }
605                                 else {
606                                         if (fly->speed < 0.0f)   fly->speed = -fly->speed;
607                                         else if (fly->axis == 0) fly->speed += fly->grid;
608
609                                         fly->axis = 0;
610                                 }
611                                 break;
612                         case FLY_MODAL_DIR_RIGHT:
613                                 if (fly->axis == 0 && fly->speed > 0.0f) {
614                                         fly->axis = -1;
615                                 }
616                                 else {
617                                         if (fly->speed > 0.0f)   fly->speed = -fly->speed;
618                                         else if (fly->axis == 0) fly->speed -= fly->grid;
619
620                                         fly->axis = 0;
621                                 }
622                                 break;
623                         case FLY_MODAL_DIR_DOWN:
624                                 if (fly->axis == 1 && fly->speed < 0.0f) {
625                                         fly->axis = -1;
626                                 }
627                                 else {
628                                         if (fly->speed < 0.0f)   fly->speed = -fly->speed;
629                                         else if (fly->axis == 1) fly->speed += fly->grid;
630                                         fly->axis = 1;
631                                 }
632                                 break;
633                         case FLY_MODAL_DIR_UP:
634                                 if (fly->axis == 1 && fly->speed > 0.0f) {
635                                         fly->axis = -1;
636                                 }
637                                 else {
638                                         if (fly->speed > 0.0f)   fly->speed = -fly->speed;
639                                         else if (fly->axis == 1) fly->speed -= fly->grid;
640                                         fly->axis = 1;
641                                 }
642                                 break;
643
644                         case FLY_MODAL_AXIS_LOCK_X:
645                                 if (fly->xlock != FLY_AXISLOCK_STATE_OFF)
646                                         fly->xlock = FLY_AXISLOCK_STATE_OFF;
647                                 else {
648                                         fly->xlock = FLY_AXISLOCK_STATE_ACTIVE;
649                                         fly->xlock_momentum = 0.0;
650                                 }
651                                 fly_update_header(C, op, fly);
652                                 break;
653                         case FLY_MODAL_AXIS_LOCK_Z:
654                                 if (fly->zlock != FLY_AXISLOCK_STATE_OFF)
655                                         fly->zlock = FLY_AXISLOCK_STATE_OFF;
656                                 else {
657                                         fly->zlock = FLY_AXISLOCK_STATE_ACTIVE;
658                                         fly->zlock_momentum = 0.0;
659                                 }
660                                 fly_update_header(C, op, fly);
661                                 break;
662
663                         case FLY_MODAL_PRECISION_ENABLE:
664                                 fly->use_precision = true;
665                                 break;
666                         case FLY_MODAL_PRECISION_DISABLE:
667                                 fly->use_precision = false;
668                                 break;
669
670                         case FLY_MODAL_FREELOOK_ENABLE:
671                                 fly->use_freelook = true;
672                                 break;
673                         case FLY_MODAL_FREELOOK_DISABLE:
674                                 fly->use_freelook = false;
675                                 break;
676                 }
677         }
678 }
679
680 static void flyMoveCamera(bContext *C, FlyInfo *fly,
681                           const bool do_rotate, const bool do_translate)
682 {
683         ED_view3d_cameracontrol_update(fly->v3d_camera_control, true, C, do_rotate, do_translate);
684 }
685
686 static int flyApply(bContext *C, FlyInfo *fly)
687 {
688 #define FLY_ROTATE_FAC 10.0f /* more is faster */
689 #define FLY_ZUP_CORRECT_FAC 0.1f /* amount to correct per step */
690 #define FLY_ZUP_CORRECT_ACCEL 0.05f /* increase upright momentum each step */
691 #define FLY_SMOOTH_FAC 20.0f  /* higher value less lag */
692
693         /* fly mode - Shift+F
694          * a fly loop where the user can move move the view as if they are flying
695          */
696         RegionView3D *rv3d = fly->rv3d;
697
698         float mat[3][3]; /* 3x3 copy of the view matrix so we can move along the view axis */
699         float dvec[3] = {0, 0, 0}; /* this is the direction that's added to the view offset per redraw */
700
701         /* Camera Uprighting variables */
702         float moffset[2]; /* mouse offset from the views center */
703         float tmp_quat[4]; /* used for rotating the view */
704
705         int xmargin, ymargin; /* x and y margin are define the safe area where the mouses movement wont rotate the view */
706
707 #ifdef NDOF_FLY_DEBUG
708         {
709                 static unsigned int iteration = 1;
710                 printf("fly timer %d\n", iteration++);
711         }
712 #endif
713
714         xmargin = fly->width / 20.0f;
715         ymargin = fly->height / 20.0f;
716
717         {
718
719                 /* mouse offset from the center */
720                 moffset[0] = fly->mval[0] - fly->center_mval[0];
721                 moffset[1] = fly->mval[1] - fly->center_mval[1];
722
723                 /* enforce a view margin */
724                 if      (moffset[0] >  xmargin) moffset[0] -= xmargin;
725                 else if (moffset[0] < -xmargin) moffset[0] += xmargin;
726                 else                            moffset[0] =  0;
727
728                 if      (moffset[1] >  ymargin) moffset[1] -= ymargin;
729                 else if (moffset[1] < -ymargin) moffset[1] += ymargin;
730                 else                            moffset[1] =  0;
731
732
733                 /* scale the mouse movement by this value - scales mouse movement to the view size
734                  * moffset[0] / (ar->winx-xmargin * 2) - window size minus margin (same for y)
735                  *
736                  * the mouse moves isn't linear */
737
738                 if (moffset[0]) {
739                         moffset[0] /= fly->width - (xmargin * 2);
740                         moffset[0] *= fabsf(moffset[0]);
741                 }
742
743                 if (moffset[1]) {
744                         moffset[1] /= fly->height - (ymargin * 2);
745                         moffset[1] *= fabsf(moffset[1]);
746                 }
747
748                 /* Should we redraw? */
749                 if ((fly->speed != 0.0f) ||
750                     moffset[0] || moffset[1] ||
751                     (fly->zlock != FLY_AXISLOCK_STATE_OFF) ||
752                     (fly->xlock != FLY_AXISLOCK_STATE_OFF) ||
753                     dvec[0] || dvec[1] || dvec[2])
754                 {
755                         float dvec_tmp[3];
756
757                         /* time how fast it takes for us to redraw,
758                          * this is so simple scenes don't fly too fast */
759                         double time_current;
760                         float time_redraw;
761                         float time_redraw_clamped;
762 #ifdef NDOF_FLY_DRAW_TOOMUCH
763                         fly->redraw = 1;
764 #endif
765                         time_current = PIL_check_seconds_timer();
766                         time_redraw = (float)(time_current - fly->time_lastdraw);
767                         time_redraw_clamped = min_ff(0.05f, time_redraw); /* clamp redraw time to avoid jitter in roll correction */
768                         fly->time_lastdraw = time_current;
769
770                         /* Scale the time to use shift to scale the speed down- just like
771                          * shift slows many other areas of blender down */
772                         if (fly->use_precision)
773                                 fly->speed = fly->speed * (1.0f - time_redraw_clamped);
774
775                         copy_m3_m4(mat, rv3d->viewinv);
776
777                         if (fly->pan_view == true) {
778                                 /* pan only */
779                                 copy_v3_fl3(dvec_tmp, -moffset[0], -moffset[1], 0.0f);
780
781                                 if (fly->use_precision) {
782                                         dvec_tmp[0] *= 0.1f;
783                                         dvec_tmp[1] *= 0.1f;
784                                 }
785
786                                 mul_m3_v3(mat, dvec_tmp);
787                                 mul_v3_fl(dvec_tmp, time_redraw * 200.0f * fly->grid);
788                         }
789                         else {
790                                 float roll; /* similar to the angle between the camera's up and the Z-up,
791                                              * but its very rough so just roll */
792
793                                 /* rotate about the X axis- look up/down */
794                                 if (moffset[1]) {
795                                         float upvec[3];
796                                         copy_v3_fl3(upvec, 1.0f, 0.0f, 0.0f);
797                                         mul_m3_v3(mat, upvec);
798                                         /* Rotate about the relative up vec */
799                                         axis_angle_to_quat(tmp_quat, upvec, moffset[1] * time_redraw * -FLY_ROTATE_FAC);
800                                         mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, tmp_quat);
801
802                                         if (fly->xlock != FLY_AXISLOCK_STATE_OFF)
803                                                 fly->xlock = FLY_AXISLOCK_STATE_ACTIVE;  /* check for rotation */
804                                         if (fly->zlock != FLY_AXISLOCK_STATE_OFF)
805                                                 fly->zlock = FLY_AXISLOCK_STATE_ACTIVE;
806                                         fly->xlock_momentum = 0.0f;
807                                 }
808
809                                 /* rotate about the Y axis- look left/right */
810                                 if (moffset[0]) {
811                                         float upvec[3];
812                                         /* if we're upside down invert the moffset */
813                                         copy_v3_fl3(upvec, 0.0f, 1.0f, 0.0f);
814                                         mul_m3_v3(mat, upvec);
815
816                                         if (upvec[2] < 0.0f)
817                                                 moffset[0] = -moffset[0];
818
819                                         /* make the lock vectors */
820                                         if (fly->zlock) {
821                                                 copy_v3_fl3(upvec, 0.0f, 0.0f, 1.0f);
822                                         }
823                                         else {
824                                                 copy_v3_fl3(upvec, 0.0f, 1.0f, 0.0f);
825                                                 mul_m3_v3(mat, upvec);
826                                         }
827
828                                         /* Rotate about the relative up vec */
829                                         axis_angle_to_quat(tmp_quat, upvec, moffset[0] * time_redraw * FLY_ROTATE_FAC);
830                                         mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, tmp_quat);
831
832                                         if (fly->xlock != FLY_AXISLOCK_STATE_OFF)
833                                                 fly->xlock = FLY_AXISLOCK_STATE_ACTIVE;  /* check for rotation */
834                                         if (fly->zlock != FLY_AXISLOCK_STATE_OFF)
835                                                 fly->zlock = FLY_AXISLOCK_STATE_ACTIVE;
836                                 }
837
838                                 if (fly->zlock == FLY_AXISLOCK_STATE_ACTIVE) {
839                                         float upvec[3];
840                                         copy_v3_fl3(upvec, 1.0f, 0.0f, 0.0f);
841                                         mul_m3_v3(mat, upvec);
842
843                                         /* make sure we have some z rolling */
844                                         if (fabsf(upvec[2]) > 0.00001f) {
845                                                 roll = upvec[2] * 5.0f;
846                                                 /* rotate the view about this axis */
847                                                 copy_v3_fl3(upvec, 0.0f, 0.0f, 1.0f);
848                                                 mul_m3_v3(mat, upvec);
849                                                 /* Rotate about the relative up vec */
850                                                 axis_angle_to_quat(tmp_quat, upvec,
851                                                                    roll * time_redraw_clamped * fly->zlock_momentum * FLY_ZUP_CORRECT_FAC);
852                                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, tmp_quat);
853
854                                                 fly->zlock_momentum += FLY_ZUP_CORRECT_ACCEL;
855                                         }
856                                         else {
857                                                 fly->zlock = FLY_AXISLOCK_STATE_IDLE; /* don't check until the view rotates again */
858                                                 fly->zlock_momentum = 0.0f;
859                                         }
860                                 }
861
862                                 /* only apply xcorrect when mouse isn't applying x rot */
863                                 if (fly->xlock == FLY_AXISLOCK_STATE_ACTIVE && moffset[1] == 0) {
864                                         float upvec[3];
865                                         copy_v3_fl3(upvec, 0.0f, 0.0f, 1.0f);
866                                         mul_m3_v3(mat, upvec);
867                                         /* make sure we have some z rolling */
868                                         if (fabsf(upvec[2]) > 0.00001f) {
869                                                 roll = upvec[2] * -5.0f;
870                                                 /* rotate the view about this axis */
871                                                 copy_v3_fl3(upvec, 1.0f, 0.0f, 0.0f);
872                                                 mul_m3_v3(mat, upvec);
873
874                                                 /* Rotate about the relative up vec */
875                                                 axis_angle_to_quat(tmp_quat, upvec, roll * time_redraw_clamped * fly->xlock_momentum * 0.1f);
876                                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, tmp_quat);
877
878                                                 fly->xlock_momentum += 0.05f;
879                                         }
880                                         else {
881                                                 fly->xlock = FLY_AXISLOCK_STATE_IDLE; /* see above */
882                                                 fly->xlock_momentum = 0.0f;
883                                         }
884                                 }
885
886                                 if (fly->axis == -1) {
887                                         /* pause */
888                                         zero_v3(dvec_tmp);
889                                 }
890                                 else if (!fly->use_freelook) {
891                                         /* Normal operation */
892                                         /* define dvec, view direction vector */
893                                         zero_v3(dvec_tmp);
894                                         /* move along the current axis */
895                                         dvec_tmp[fly->axis] = 1.0f;
896
897                                         mul_m3_v3(mat, dvec_tmp);
898                                 }
899                                 else {
900                                         normalize_v3_v3(dvec_tmp, fly->dvec_prev);
901                                         if (fly->speed < 0.0f) {
902                                                 negate_v3(dvec_tmp);
903                                         }
904                                 }
905
906                                 mul_v3_fl(dvec_tmp, fly->speed * time_redraw * 0.25f);
907                         }
908
909                         /* impose a directional lag */
910                         interp_v3_v3v3(dvec, dvec_tmp, fly->dvec_prev, (1.0f / (1.0f + (time_redraw * FLY_SMOOTH_FAC))));
911
912                         if (rv3d->persp == RV3D_CAMOB) {
913                                 Object *lock_ob = ED_view3d_cameracontrol_object_get(fly->v3d_camera_control);
914                                 if (lock_ob->protectflag & OB_LOCK_LOCX) dvec[0] = 0.0;
915                                 if (lock_ob->protectflag & OB_LOCK_LOCY) dvec[1] = 0.0;
916                                 if (lock_ob->protectflag & OB_LOCK_LOCZ) dvec[2] = 0.0;
917                         }
918
919                         add_v3_v3(rv3d->ofs, dvec);
920
921                         if (rv3d->persp == RV3D_CAMOB) {
922                                 const bool do_rotate = ((fly->xlock != FLY_AXISLOCK_STATE_OFF) ||
923                                                         (fly->zlock != FLY_AXISLOCK_STATE_OFF) ||
924                                                         ((moffset[0] || moffset[1]) && !fly->pan_view));
925                                 const bool do_translate = (fly->speed != 0.0f || fly->pan_view);
926                                 flyMoveCamera(C, fly, do_rotate, do_translate);
927                         }
928
929                 }
930                 else {
931                         /* we're not redrawing but we need to update the time else the view will jump */
932                         fly->time_lastdraw = PIL_check_seconds_timer();
933                 }
934                 /* end drawing */
935                 copy_v3_v3(fly->dvec_prev, dvec);
936         }
937
938         return OPERATOR_FINISHED;
939 }
940
941 #ifdef WITH_INPUT_NDOF
942 static void flyApply_ndof(bContext *C, FlyInfo *fly)
943 {
944         Object *lock_ob = ED_view3d_cameracontrol_object_get(fly->v3d_camera_control);
945         bool has_translate, has_rotate;
946
947         view3d_ndof_fly(fly->ndof,
948                         fly->v3d, fly->rv3d,
949                         fly->use_precision, lock_ob ? lock_ob->protectflag : 0,
950                         &has_translate, &has_rotate);
951
952         if (has_translate || has_rotate) {
953                 fly->redraw = true;
954
955                 if (fly->rv3d->persp == RV3D_CAMOB) {
956                         flyMoveCamera(C, fly, has_rotate, has_translate);
957                 }
958         }
959 }
960 #endif /* WITH_INPUT_NDOF */
961
962 static int fly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
963 {
964         RegionView3D *rv3d = CTX_wm_region_view3d(C);
965         FlyInfo *fly;
966
967         if (rv3d->viewlock & RV3D_LOCKED)
968                 return OPERATOR_CANCELLED;
969
970         fly = MEM_callocN(sizeof(FlyInfo), "FlyOperation");
971
972         op->customdata = fly;
973
974         if (initFlyInfo(C, fly, op, event) == false) {
975                 MEM_freeN(op->customdata);
976                 return OPERATOR_CANCELLED;
977         }
978
979         flyEvent(C, op, fly, event);
980
981         WM_event_add_modal_handler(C, op);
982
983         return OPERATOR_RUNNING_MODAL;
984 }
985
986 static void fly_cancel(bContext *C, wmOperator *op)
987 {
988         FlyInfo *fly = op->customdata;
989
990         fly->state = FLY_CANCEL;
991         flyEnd(C, fly);
992         op->customdata = NULL;
993 }
994
995 static int fly_modal(bContext *C, wmOperator *op, const wmEvent *event)
996 {
997         int exit_code;
998         bool do_draw = false;
999         FlyInfo *fly = op->customdata;
1000         RegionView3D *rv3d = fly->rv3d;
1001         Object *fly_object = ED_view3d_cameracontrol_object_get(fly->v3d_camera_control);
1002
1003         fly->redraw = 0;
1004
1005         flyEvent(C, op, fly, event);
1006
1007 #ifdef WITH_INPUT_NDOF
1008         if (fly->ndof) { /* 3D mouse overrules [2D mouse + timer] */
1009                 if (event->type == NDOF_MOTION) {
1010                         flyApply_ndof(C, fly);
1011                 }
1012         }
1013         else
1014 #endif /* WITH_INPUT_NDOF */
1015         if (event->type == TIMER && event->customdata == fly->timer) {
1016                 flyApply(C, fly);
1017         }
1018
1019         do_draw |= fly->redraw;
1020
1021         exit_code = flyEnd(C, fly);
1022
1023         if (exit_code != OPERATOR_RUNNING_MODAL)
1024                 do_draw = true;
1025
1026         if (do_draw) {
1027                 if (rv3d->persp == RV3D_CAMOB) {
1028                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, fly_object);
1029                 }
1030
1031                 // puts("redraw!"); // too frequent, commented with NDOF_FLY_DRAW_TOOMUCH for now
1032                 ED_region_tag_redraw(CTX_wm_region(C));
1033         }
1034
1035         if (ELEM(exit_code, OPERATOR_FINISHED, OPERATOR_CANCELLED))
1036                 ED_workspace_status_text(C, NULL);
1037
1038         return exit_code;
1039 }
1040
1041 void VIEW3D_OT_fly(wmOperatorType *ot)
1042 {
1043         /* identifiers */
1044         ot->name = "Fly Navigation";
1045         ot->description = "Interactively fly around the scene";
1046         ot->idname = "VIEW3D_OT_fly";
1047
1048         /* api callbacks */
1049         ot->invoke = fly_invoke;
1050         ot->cancel = fly_cancel;
1051         ot->modal = fly_modal;
1052         ot->poll = ED_operator_region_view3d_active;
1053
1054         /* flags */
1055         ot->flag = OPTYPE_BLOCKING;
1056 }