Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_edit.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  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/editors/space_view3d/view3d_edit.c
28  *  \ingroup spview3d
29  *
30  * 3D view manipulation/operators.
31  */
32
33 #include <string.h>
34 #include <stdio.h>
35 #include <math.h>
36 #include <float.h>
37
38 #include "DNA_armature_types.h"
39 #include "DNA_camera_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_gpencil_types.h"
44
45 #include "MEM_guardedalloc.h"
46
47 #include "BLI_blenlib.h"
48 #include "BLI_math.h"
49 #include "BLI_utildefines.h"
50
51 #include "BKE_armature.h"
52 #include "BKE_camera.h"
53 #include "BKE_context.h"
54 #include "BKE_font.h"
55 #include "BKE_layer.h"
56 #include "BKE_library.h"
57 #include "BKE_main.h"
58 #include "BKE_object.h"
59 #include "BKE_paint.h"
60 #include "BKE_report.h"
61 #include "BKE_scene.h"
62 #include "BKE_screen.h"
63 #include "BKE_action.h"
64
65 #include "DEG_depsgraph.h"
66 #include "DEG_depsgraph_query.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70 #include "WM_message.h"
71
72 #include "RNA_access.h"
73 #include "RNA_define.h"
74
75 #include "ED_armature.h"
76 #include "ED_particle.h"
77 #include "ED_screen.h"
78 #include "ED_transform.h"
79 #include "ED_mesh.h"
80 #include "ED_gpencil.h"
81 #include "ED_view3d.h"
82 #include "ED_transform_snap_object_context.h"
83
84 #include "UI_resources.h"
85
86 #include "PIL_time.h"
87
88 #include "view3d_intern.h"  /* own include */
89
90 /* -------------------------------------------------------------------- */
91 /** \name Generic View Operator Properties
92  * \{ */
93
94 enum eV3D_OpPropFlag {
95         V3D_OP_PROP_MOUSE_CO = (1 << 0),
96         V3D_OP_PROP_DELTA = (1 << 1),
97         V3D_OP_PROP_USE_ALL_REGIONS = (1 << 2),
98         V3D_OP_PROP_USE_MOUSE_INIT = (1 << 3),
99 };
100
101 static void view3d_operator_properties_common(wmOperatorType *ot, const enum eV3D_OpPropFlag flag)
102 {
103         if (flag & V3D_OP_PROP_MOUSE_CO) {
104                 PropertyRNA *prop;
105                 prop = RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Region Position X", "", 0, INT_MAX);
106                 RNA_def_property_flag(prop, PROP_HIDDEN);
107                 prop = RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Region Position Y", "", 0, INT_MAX);
108                 RNA_def_property_flag(prop, PROP_HIDDEN);
109         }
110         if (flag & V3D_OP_PROP_DELTA) {
111                 RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
112         }
113         if (flag & V3D_OP_PROP_USE_ALL_REGIONS) {
114                 PropertyRNA *prop;
115                 prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
116                 RNA_def_property_flag(prop, PROP_SKIP_SAVE);
117         }
118         if (flag & V3D_OP_PROP_USE_MOUSE_INIT) {
119                 /* Disable when view operators are initialized from buttons. */
120                 PropertyRNA *prop;
121                 prop = RNA_def_boolean(ot->srna, "use_mouse_init", true, "Mouse Init", "Use initial mouse position");
122                 RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
123         }
124 }
125
126 /** \} */
127
128 /* -------------------------------------------------------------------- */
129 /** \name Generic View Operator Custom-Data
130  * \{ */
131
132 typedef struct ViewOpsData {
133         /** Context pointers (assigned by #viewops_data_alloc). */
134         Main *bmain;
135         Scene *scene;
136         ScrArea *sa;
137         ARegion *ar;
138         View3D *v3d;
139         RegionView3D *rv3d;
140         Depsgraph *depsgraph;
141
142         /** Needed for continuous zoom. */
143         wmTimer *timer;
144
145         /** Viewport state on initialization, don't change afterwards. */
146         struct {
147                 float dist;
148                 float camzoom;
149                 float quat[4];
150                 /** #wmEvent.x, y. */
151                 int event_xy[2];
152                 /** Offset to use when #VIEWOPS_FLAG_USE_MOUSE_INIT is not set.
153                  * so we can simulate pressing in the middle of the screen. */
154                 int event_xy_offset[2];
155                 /** #wmEvent.type that triggered the operator. */
156                 int event_type;
157                 float ofs[3];
158                 /** Initial distance to 'ofs'. */
159                 float zfac;
160
161                 /** Trackball rotation only. */
162                 float trackvec[3];
163                 /** Dolly only. */
164                 float mousevec[3];
165         } init;
166
167         /** Previous state (previous modal event handled). */
168         struct {
169                 int event_xy[2];
170                 /** For operators that use time-steps (continuous zoom). */
171                 double time;
172         } prev;
173
174         /** Current state. */
175         struct {
176                 /** Working copy of #RegionView3D.viewquat, needed for rotation calculation
177                  * so we can apply snap to the view-port while keeping the unsnapped rotation
178                  * here to use when snap is disabled and for continued calculation. */
179                 float viewquat[4];
180         } curr;
181
182         float reverse;
183         bool axis_snap;  /* view rotate only */
184
185         /** Use for orbit selection and auto-dist. */
186         float dyn_ofs[3];
187         bool use_dyn_ofs;
188 } ViewOpsData;
189
190 #define TRACKBALLSIZE  (1.1f)
191
192 static void calctrackballvec(const rcti *rect, const int event_xy[2], float vec[3])
193 {
194         const float radius = TRACKBALLSIZE;
195         const float t = radius / (float)M_SQRT2;
196         float x, y, z, d;
197
198         /* normalize x and y */
199         x = BLI_rcti_cent_x(rect) - event_xy[0];
200         x /= (float)(BLI_rcti_size_x(rect) / 4);
201         y = BLI_rcti_cent_y(rect) - event_xy[1];
202         y /= (float)(BLI_rcti_size_y(rect) / 2);
203         d = sqrtf(x * x + y * y);
204         if (d < t) { /* Inside sphere */
205                 z = sqrtf(radius * radius - d * d);
206         }
207         else { /* On hyperbola */
208                 z = t * t / d;
209         }
210
211         vec[0] = x;
212         vec[1] = y;
213         vec[2] = -z;     /* yah yah! */
214 }
215
216 /**
217  * Allocate and fill in context pointers for #ViewOpsData
218  */
219 static void viewops_data_alloc(bContext *C, wmOperator *op)
220 {
221         ViewOpsData *vod = MEM_callocN(sizeof(ViewOpsData), "viewops data");
222
223         /* store data */
224         op->customdata = vod;
225         vod->bmain = CTX_data_main(C);
226         vod->depsgraph = CTX_data_depsgraph(C);
227         vod->scene = CTX_data_scene(C);
228         vod->sa = CTX_wm_area(C);
229         vod->ar = CTX_wm_region(C);
230         vod->v3d = vod->sa->spacedata.first;
231         vod->rv3d = vod->ar->regiondata;
232 }
233
234 void view3d_orbit_apply_dyn_ofs(
235         float r_ofs[3], const float ofs_init[3], const float viewquat_old[4],
236         const float viewquat_new[4], const float dyn_ofs[3])
237 {
238         float q[4];
239         invert_qt_qt_normalized(q, viewquat_old);
240         mul_qt_qtqt(q, q, viewquat_new);
241
242         invert_qt_normalized(q);
243
244         sub_v3_v3v3(r_ofs, ofs_init, dyn_ofs);
245         mul_qt_v3(q, r_ofs);
246         add_v3_v3(r_ofs, dyn_ofs);
247 }
248
249 static bool view3d_orbit_calc_center(bContext *C, float r_dyn_ofs[3])
250 {
251         static float lastofs[3] = {0, 0, 0};
252         bool is_set = false;
253
254         const Depsgraph *depsgraph = CTX_data_depsgraph(C);
255         Scene *scene = CTX_data_scene(C);
256         ViewLayer *view_layer_eval = DEG_get_evaluated_view_layer(depsgraph);
257         Object *ob_act_eval = OBACT(view_layer_eval);
258         Object *ob_act = DEG_get_original_object(ob_act_eval);
259
260         if (ob_act && (ob_act->mode & OB_MODE_ALL_PAINT) &&
261             /* with weight-paint + pose-mode, fall through to using calculateTransformCenter */
262             ((ob_act->mode & OB_MODE_WEIGHT_PAINT) && BKE_object_pose_armature_get(ob_act)) == 0)
263         {
264                 /* in case of sculpting use last average stroke position as a rotation
265                  * center, in other cases it's not clear what rotation center shall be
266                  * so just rotate around object origin
267                  */
268                 if (ob_act->mode & (OB_MODE_SCULPT | OB_MODE_TEXTURE_PAINT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
269                         float stroke[3];
270                         BKE_paint_stroke_get_average(scene, ob_act_eval, stroke);
271                         copy_v3_v3(lastofs, stroke);
272                 }
273                 else {
274                         copy_v3_v3(lastofs, ob_act_eval->obmat[3]);
275                 }
276                 is_set = true;
277         }
278         else if (ob_act && (ob_act->mode & OB_MODE_EDIT) && (ob_act->type == OB_FONT)) {
279                 Curve *cu = ob_act_eval->data;
280                 EditFont *ef = cu->editfont;
281                 int i;
282
283                 zero_v3(lastofs);
284                 for (i = 0; i < 4; i++) {
285                         add_v2_v2(lastofs, ef->textcurs[i]);
286                 }
287                 mul_v2_fl(lastofs, 1.0f / 4.0f);
288
289                 mul_m4_v3(ob_act_eval->obmat, lastofs);
290
291                 is_set = true;
292         }
293         else if (ob_act == NULL || ob_act->mode == OB_MODE_OBJECT) {
294                 /* object mode use boundbox centers */
295                 Base *base_eval;
296                 unsigned int tot = 0;
297                 float select_center[3];
298
299                 zero_v3(select_center);
300                 for (base_eval = FIRSTBASE(view_layer_eval); base_eval; base_eval = base_eval->next) {
301                         if (TESTBASE(base_eval)) {
302                                 /* use the boundbox if we can */
303                                 Object *ob_eval = base_eval->object;
304
305                                 if (ob_eval->bb && !(ob_eval->bb->flag & BOUNDBOX_DIRTY)) {
306                                         float cent[3];
307
308                                         BKE_boundbox_calc_center_aabb(ob_eval->bb, cent);
309
310                                         mul_m4_v3(ob_eval->obmat, cent);
311                                         add_v3_v3(select_center, cent);
312                                 }
313                                 else {
314                                         add_v3_v3(select_center, ob_eval->obmat[3]);
315                                 }
316                                 tot++;
317                         }
318                 }
319                 if (tot) {
320                         mul_v3_fl(select_center, 1.0f / (float)tot);
321                         copy_v3_v3(lastofs, select_center);
322                         is_set = true;
323                 }
324         }
325         else {
326                 /* If there's no selection, lastofs is unmodified and last value since static */
327                 is_set = calculateTransformCenter(C, V3D_AROUND_CENTER_MEAN, lastofs, NULL);
328         }
329
330         copy_v3_v3(r_dyn_ofs, lastofs);
331
332         return is_set;
333 }
334
335 enum eViewOpsFlag {
336         /** When enabled, rotate around the selection. */
337         VIEWOPS_FLAG_ORBIT_SELECT = (1 << 0),
338         /** When enabled, use the depth under the cursor for navigation. */
339         VIEWOPS_FLAG_DEPTH_NAVIGATE = (1 << 1),
340         /**
341          * When enabled run #ED_view3d_persp_ensure this may switch out of
342          * camera view when orbiting or switch from ortho to perspective when auto-persp is enabled.
343          * Some operations don't require this (view zoom/pan or ndof where subtle rotation is common
344          * so we don't want it to trigger auto-perspective). */
345         VIEWOPS_FLAG_PERSP_ENSURE = (1 << 2),
346         /** When set, ignore any options that depend on initial cursor location. */
347         VIEWOPS_FLAG_USE_MOUSE_INIT = (1 << 3),
348 };
349
350 static enum eViewOpsFlag viewops_flag_from_args(bool use_select, bool use_depth)
351 {
352         enum eViewOpsFlag flag = 0;
353         if (use_select) {
354                 flag |= VIEWOPS_FLAG_ORBIT_SELECT;
355         }
356         if (use_depth) {
357                 flag |= VIEWOPS_FLAG_DEPTH_NAVIGATE;
358         }
359
360         return flag;
361 }
362
363 static enum eViewOpsFlag viewops_flag_from_prefs(void)
364 {
365         return viewops_flag_from_args(
366                 (U.uiflag & USER_ORBIT_SELECTION) != 0,
367                 (U.uiflag & USER_DEPTH_NAVIGATE) != 0);
368 }
369
370 /**
371  * Calculate the values for #ViewOpsData
372  */
373 static void viewops_data_create(
374         bContext *C, wmOperator *op, const wmEvent *event,
375         enum eViewOpsFlag viewops_flag)
376 {
377         Depsgraph *depsgraph = CTX_data_depsgraph(C);
378         ViewOpsData *vod = op->customdata;
379         RegionView3D *rv3d = vod->rv3d;
380
381         /* Could do this more nicely. */
382         if ((viewops_flag & VIEWOPS_FLAG_USE_MOUSE_INIT) == 0) {
383                 viewops_flag &= ~VIEWOPS_FLAG_DEPTH_NAVIGATE;
384         }
385
386         /* we need the depth info before changing any viewport options */
387         if (viewops_flag & VIEWOPS_FLAG_DEPTH_NAVIGATE) {
388                 float fallback_depth_pt[3];
389
390                 view3d_operator_needs_opengl(C); /* needed for zbuf drawing */
391
392                 negate_v3_v3(fallback_depth_pt, rv3d->ofs);
393
394                 vod->use_dyn_ofs = ED_view3d_autodist(
395                         depsgraph, vod->ar, vod->v3d,
396                         event->mval, vod->dyn_ofs, true, fallback_depth_pt);
397         }
398         else {
399                 vod->use_dyn_ofs = false;
400         }
401
402         if (viewops_flag & VIEWOPS_FLAG_PERSP_ENSURE) {
403                 if (ED_view3d_persp_ensure(depsgraph, vod->v3d, vod->ar)) {
404                         /* If we're switching from camera view to the perspective one,
405                          * need to tag viewport update, so camera vuew and borders
406                          * are properly updated.
407                          */
408                         ED_region_tag_redraw(vod->ar);
409                 }
410         }
411
412         /* set the view from the camera, if view locking is enabled.
413          * we may want to make this optional but for now its needed always */
414         ED_view3d_camera_lock_init(depsgraph, vod->v3d, vod->rv3d);
415
416         vod->init.dist = rv3d->dist;
417         vod->init.camzoom = rv3d->camzoom;
418         copy_qt_qt(vod->init.quat, rv3d->viewquat);
419         vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
420         vod->init.event_xy[1] = vod->prev.event_xy[1] = event->y;
421
422         if (viewops_flag & VIEWOPS_FLAG_USE_MOUSE_INIT) {
423                 vod->init.event_xy_offset[0] = 0;
424                 vod->init.event_xy_offset[1] = 0;
425         }
426         else {
427                 /* Simulate the event starting in the middle of the region. */
428                 vod->init.event_xy_offset[0] = BLI_rcti_cent_x(&vod->ar->winrct) - event->x;
429                 vod->init.event_xy_offset[1] = BLI_rcti_cent_y(&vod->ar->winrct) - event->y;
430         }
431
432         vod->init.event_type = event->type;
433         copy_v3_v3(vod->init.ofs, rv3d->ofs);
434
435         copy_qt_qt(vod->curr.viewquat, rv3d->viewquat);
436
437         if (viewops_flag & VIEWOPS_FLAG_ORBIT_SELECT) {
438                 float ofs[3];
439                 if (view3d_orbit_calc_center(C, ofs) || (vod->use_dyn_ofs == false)) {
440                         vod->use_dyn_ofs = true;
441                         negate_v3_v3(vod->dyn_ofs, ofs);
442                         viewops_flag &= ~VIEWOPS_FLAG_DEPTH_NAVIGATE;
443                 }
444         }
445
446         if (viewops_flag & VIEWOPS_FLAG_DEPTH_NAVIGATE) {
447                 if (vod->use_dyn_ofs) {
448                         if (rv3d->is_persp) {
449                                 float my_origin[3]; /* original G.vd->ofs */
450                                 float my_pivot[3]; /* view */
451                                 float dvec[3];
452
453                                 /* locals for dist correction */
454                                 float mat[3][3];
455                                 float upvec[3];
456
457                                 negate_v3_v3(my_origin, rv3d->ofs);             /* ofs is flipped */
458
459                                 /* Set the dist value to be the distance from this 3d point
460                                  * this means youll always be able to zoom into it and panning wont go bad when dist was zero */
461
462                                 /* remove dist value */
463                                 upvec[0] = upvec[1] = 0;
464                                 upvec[2] = rv3d->dist;
465                                 copy_m3_m4(mat, rv3d->viewinv);
466
467                                 mul_m3_v3(mat, upvec);
468                                 sub_v3_v3v3(my_pivot, rv3d->ofs, upvec);
469                                 negate_v3(my_pivot);                /* ofs is flipped */
470
471                                 /* find a new ofs value that is along the view axis (rather than the mouse location) */
472                                 closest_to_line_v3(dvec, vod->dyn_ofs, my_pivot, my_origin);
473                                 vod->init.dist = rv3d->dist = len_v3v3(my_pivot, dvec);
474
475                                 negate_v3_v3(rv3d->ofs, dvec);
476                         }
477                         else {
478                                 const float mval_ar_mid[2] = {
479                                     (float)vod->ar->winx / 2.0f,
480                                     (float)vod->ar->winy / 2.0f};
481
482                                 ED_view3d_win_to_3d(vod->v3d, vod->ar, vod->dyn_ofs, mval_ar_mid, rv3d->ofs);
483                                 negate_v3(rv3d->ofs);
484                         }
485                         negate_v3(vod->dyn_ofs);
486                         copy_v3_v3(vod->init.ofs, rv3d->ofs);
487                 }
488         }
489
490         /* For dolly */
491         ED_view3d_win_to_vector(vod->ar, (const float[2]){UNPACK2(event->mval)}, vod->init.mousevec);
492
493         {
494                 const int event_xy_offset[2] = {
495                         event->x + vod->init.event_xy_offset[0],
496                         event->y + vod->init.event_xy_offset[1],
497                 };
498                 /* For rotation with trackball rotation. */
499                 calctrackballvec(&vod->ar->winrct, event_xy_offset, vod->init.trackvec);
500         }
501
502         {
503                 float tvec[3];
504                 negate_v3_v3(tvec, rv3d->ofs);
505                 vod->init.zfac = ED_view3d_calc_zfac(rv3d, tvec, NULL);
506         }
507
508         vod->reverse = 1.0f;
509         if (rv3d->persmat[2][1] < 0.0f)
510                 vod->reverse = -1.0f;
511
512         rv3d->rflag |= RV3D_NAVIGATING;
513 }
514
515 static void viewops_data_free(bContext *C, wmOperator *op)
516 {
517         ARegion *ar;
518 #if 0
519         Paint *p = BKE_paint_get_active_from_context(C);
520 #endif
521         if (op->customdata) {
522                 ViewOpsData *vod = op->customdata;
523                 ar = vod->ar;
524                 vod->rv3d->rflag &= ~RV3D_NAVIGATING;
525
526                 if (vod->timer)
527                         WM_event_remove_timer(CTX_wm_manager(C), vod->timer->win, vod->timer);
528
529                 MEM_freeN(vod);
530                 op->customdata = NULL;
531         }
532         else {
533                 ar = CTX_wm_region(C);
534         }
535
536 #if 0
537         if (p && (p->flags & PAINT_FAST_NAVIGATE))
538 #endif
539                 ED_region_tag_redraw(ar);
540 }
541
542 /** \} */
543
544 /* -------------------------------------------------------------------- */
545 /** \name View Rotate Operator
546  * \{ */
547
548 enum {
549         VIEW_PASS = 0,
550         VIEW_APPLY,
551         VIEW_CONFIRM
552 };
553
554 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
555 enum {
556         VIEW_MODAL_CONFIRM              = 1, /* used for all view operations */
557         VIEWROT_MODAL_AXIS_SNAP_ENABLE  = 2,
558         VIEWROT_MODAL_AXIS_SNAP_DISABLE = 3,
559         VIEWROT_MODAL_SWITCH_ZOOM       = 4,
560         VIEWROT_MODAL_SWITCH_MOVE       = 5,
561         VIEWROT_MODAL_SWITCH_ROTATE     = 6,
562 };
563
564 /* called in transform_ops.c, on each regeneration of keymaps  */
565 void viewrotate_modal_keymap(wmKeyConfig *keyconf)
566 {
567         static const EnumPropertyItem modal_items[] = {
568                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
569
570                 {VIEWROT_MODAL_AXIS_SNAP_ENABLE,    "AXIS_SNAP_ENABLE", 0, "Axis Snap", ""},
571                 {VIEWROT_MODAL_AXIS_SNAP_DISABLE,   "AXIS_SNAP_DISABLE", 0, "Axis Snap (Off)", ""},
572
573                 {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
574                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
575
576                 {0, NULL, 0, NULL, NULL}
577         };
578
579         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Rotate Modal");
580
581         /* this function is called for each spacetype, only needs to add map once */
582         if (keymap && keymap->modal_items) return;
583
584         keymap = WM_modalkeymap_add(keyconf, "View3D Rotate Modal", modal_items);
585
586         /* items for modal map */
587         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
588         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
589
590         WM_modalkeymap_add_item(keymap, LEFTALTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_AXIS_SNAP_ENABLE);
591         WM_modalkeymap_add_item(keymap, LEFTALTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_AXIS_SNAP_DISABLE);
592
593         /* disabled mode switching for now, can re-implement better, later on */
594 #if 0
595         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
596         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
597         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
598 #endif
599
600         /* assign map to operators */
601         WM_modalkeymap_assign(keymap, "VIEW3D_OT_rotate");
602 }
603
604 static void viewrotate_apply_dyn_ofs(ViewOpsData *vod, const float viewquat_new[4])
605 {
606         if (vod->use_dyn_ofs) {
607                 RegionView3D *rv3d = vod->rv3d;
608                 view3d_orbit_apply_dyn_ofs(rv3d->ofs, vod->init.ofs, vod->init.quat, viewquat_new, vod->dyn_ofs);
609         }
610 }
611
612 static void viewrotate_apply_snap(ViewOpsData *vod)
613 {
614         const float axis_limit = DEG2RADF(45 / 3);
615
616         RegionView3D *rv3d = vod->rv3d;
617
618         float viewquat_inv[4];
619         float zaxis[3] = {0, 0, 1};
620         float zaxis_best[3];
621         int x, y, z;
622         bool found = false;
623
624         invert_qt_qt_normalized(viewquat_inv, vod->curr.viewquat);
625
626         mul_qt_v3(viewquat_inv, zaxis);
627         normalize_v3(zaxis);
628
629
630         for (x = -1; x < 2; x++) {
631                 for (y = -1; y < 2; y++) {
632                         for (z = -1; z < 2; z++) {
633                                 if (x || y || z) {
634                                         float zaxis_test[3] = {x, y, z};
635
636                                         normalize_v3(zaxis_test);
637
638                                         if (angle_normalized_v3v3(zaxis_test, zaxis) < axis_limit) {
639                                                 copy_v3_v3(zaxis_best, zaxis_test);
640                                                 found = true;
641                                         }
642                                 }
643                         }
644                 }
645         }
646
647         if (found) {
648
649                 /* find the best roll */
650                 float quat_roll[4], quat_final[4], quat_best[4], quat_snap[4];
651                 float viewquat_align[4]; /* viewquat aligned to zaxis_best */
652                 float viewquat_align_inv[4]; /* viewquat aligned to zaxis_best */
653                 float best_angle = axis_limit;
654                 int j;
655
656                 /* viewquat_align is the original viewquat aligned to the snapped axis
657                  * for testing roll */
658                 rotation_between_vecs_to_quat(viewquat_align, zaxis_best, zaxis);
659                 normalize_qt(viewquat_align);
660                 mul_qt_qtqt(viewquat_align, vod->curr.viewquat, viewquat_align);
661                 normalize_qt(viewquat_align);
662                 invert_qt_qt_normalized(viewquat_align_inv, viewquat_align);
663
664                 vec_to_quat(quat_snap, zaxis_best, OB_NEGZ, OB_POSY);
665                 normalize_qt(quat_snap);
666                 invert_qt_normalized(quat_snap);
667
668                 /* check if we can find the roll */
669                 found = false;
670
671                 /* find best roll */
672                 for (j = 0; j < 8; j++) {
673                         float angle;
674                         float xaxis1[3] = {1, 0, 0};
675                         float xaxis2[3] = {1, 0, 0};
676                         float quat_final_inv[4];
677
678                         axis_angle_to_quat(quat_roll, zaxis_best, (float)j * DEG2RADF(45.0f));
679                         normalize_qt(quat_roll);
680
681                         mul_qt_qtqt(quat_final, quat_snap, quat_roll);
682                         normalize_qt(quat_final);
683
684                         /* compare 2 vector angles to find the least roll */
685                         invert_qt_qt_normalized(quat_final_inv, quat_final);
686                         mul_qt_v3(viewquat_align_inv, xaxis1);
687                         mul_qt_v3(quat_final_inv, xaxis2);
688                         angle = angle_v3v3(xaxis1, xaxis2);
689
690                         if (angle <= best_angle) {
691                                 found = true;
692                                 best_angle = angle;
693                                 copy_qt_qt(quat_best, quat_final);
694                         }
695                 }
696
697                 if (found) {
698                         /* lock 'quat_best' to an axis view if we can */
699                         rv3d->view = ED_view3d_quat_to_axis_view(quat_best, 0.01f);
700                         if (rv3d->view != RV3D_VIEW_USER) {
701                                 ED_view3d_quat_from_axis_view(rv3d->view, quat_best);
702                         }
703                 }
704                 else {
705                         copy_qt_qt(quat_best, viewquat_align);
706                 }
707
708                 copy_qt_qt(rv3d->viewquat, quat_best);
709
710                 viewrotate_apply_dyn_ofs(vod, rv3d->viewquat);
711         }
712 }
713
714 static void viewrotate_apply(ViewOpsData *vod, const int event_xy[2])
715 {
716         RegionView3D *rv3d = vod->rv3d;
717
718         rv3d->view = RV3D_VIEW_USER; /* need to reset every time because of view snapping */
719
720         if (U.flag & USER_TRACKBALL) {
721                 float axis[3], q1[4], dvec[3], newvec[3];
722                 float angle;
723
724                 {
725                         const int event_xy_offset[2] = {
726                                 event_xy[0] + vod->init.event_xy_offset[0],
727                                 event_xy[1] + vod->init.event_xy_offset[1],
728                         };
729                         calctrackballvec(&vod->ar->winrct, event_xy_offset, newvec);
730                 }
731
732                 sub_v3_v3v3(dvec, newvec, vod->init.trackvec);
733
734                 angle = (len_v3(dvec) / (2.0f * TRACKBALLSIZE)) * (float)M_PI;
735
736                 /* Allow for rotation beyond the interval [-pi, pi] */
737                 angle = angle_wrap_rad(angle);
738
739                 /* This relation is used instead of the actual angle between vectors
740                  * so that the angle of rotation is linearly proportional to
741                  * the distance that the mouse is dragged. */
742
743                 cross_v3_v3v3(axis, vod->init.trackvec, newvec);
744                 axis_angle_to_quat(q1, axis, angle);
745
746                 mul_qt_qtqt(vod->curr.viewquat, q1, vod->init.quat);
747
748                 viewrotate_apply_dyn_ofs(vod, vod->curr.viewquat);
749         }
750         else {
751                 /* New turntable view code by John Aughey */
752                 float quat_local_x[4], quat_global_z[4];
753                 float m[3][3];
754                 float m_inv[3][3];
755                 const float zvec_global[3] = {0.0f, 0.0f, 1.0f};
756                 float xaxis[3];
757
758                 /* Sensitivity will control how fast the viewport rotates.  0.007 was
759                  * obtained experimentally by looking at viewport rotation sensitivities
760                  * on other modeling programs. */
761                 /* Perhaps this should be a configurable user parameter. */
762                 const float sensitivity = 0.007f;
763
764                 /* Get the 3x3 matrix and its inverse from the quaternion */
765                 quat_to_mat3(m, vod->curr.viewquat);
766                 invert_m3_m3(m_inv, m);
767
768                 /* avoid gimble lock */
769 #if 1
770                 if (len_squared_v3v3(zvec_global, m_inv[2]) > 0.001f) {
771                         float fac;
772                         cross_v3_v3v3(xaxis, zvec_global, m_inv[2]);
773                         if (dot_v3v3(xaxis, m_inv[0]) < 0) {
774                                 negate_v3(xaxis);
775                         }
776                         fac = angle_normalized_v3v3(zvec_global, m_inv[2]) / (float)M_PI;
777                         fac = fabsf(fac - 0.5f) * 2;
778                         fac = fac * fac;
779                         interp_v3_v3v3(xaxis, xaxis, m_inv[0], fac);
780                 }
781                 else {
782                         copy_v3_v3(xaxis, m_inv[0]);
783                 }
784 #else
785                 copy_v3_v3(xaxis, m_inv[0]);
786 #endif
787
788                 /* Determine the direction of the x vector (for rotating up and down) */
789                 /* This can likely be computed directly from the quaternion. */
790
791                 /* Perform the up/down rotation */
792                 axis_angle_to_quat(quat_local_x, xaxis, sensitivity * -(event_xy[1] - vod->prev.event_xy[1]));
793                 mul_qt_qtqt(quat_local_x, vod->curr.viewquat, quat_local_x);
794
795                 /* Perform the orbital rotation */
796                 axis_angle_to_quat_single(quat_global_z, 'Z', sensitivity * vod->reverse * (event_xy[0] - vod->prev.event_xy[0]));
797                 mul_qt_qtqt(vod->curr.viewquat, quat_local_x, quat_global_z);
798
799                 viewrotate_apply_dyn_ofs(vod, vod->curr.viewquat);
800         }
801
802         /* avoid precision loss over time */
803         normalize_qt(vod->curr.viewquat);
804
805         /* use a working copy so view rotation locking doesnt overwrite the locked
806          * rotation back into the view we calculate with */
807         copy_qt_qt(rv3d->viewquat, vod->curr.viewquat);
808
809         /* check for view snap,
810          * note: don't apply snap to vod->viewquat so the view wont jam up */
811         if (vod->axis_snap) {
812                 viewrotate_apply_snap(vod);
813         }
814         vod->prev.event_xy[0] = event_xy[0];
815         vod->prev.event_xy[1] = event_xy[1];
816
817         ED_view3d_camera_lock_sync(vod->depsgraph, vod->v3d, rv3d);
818
819         ED_region_tag_redraw(vod->ar);
820 }
821
822 static int viewrotate_modal(bContext *C, wmOperator *op, const wmEvent *event)
823 {
824         ViewOpsData *vod = op->customdata;
825         short event_code = VIEW_PASS;
826         bool use_autokey = false;
827         int ret = OPERATOR_RUNNING_MODAL;
828
829         /* execute the events */
830         if (event->type == MOUSEMOVE) {
831                 event_code = VIEW_APPLY;
832         }
833         else if (event->type == EVT_MODAL_MAP) {
834                 switch (event->val) {
835                         case VIEW_MODAL_CONFIRM:
836                                 event_code = VIEW_CONFIRM;
837                                 break;
838                         case VIEWROT_MODAL_AXIS_SNAP_ENABLE:
839                                 vod->axis_snap = true;
840                                 event_code = VIEW_APPLY;
841                                 break;
842                         case VIEWROT_MODAL_AXIS_SNAP_DISABLE:
843                                 vod->axis_snap = false;
844                                 event_code = VIEW_APPLY;
845                                 break;
846                         case VIEWROT_MODAL_SWITCH_ZOOM:
847                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
848                                 event_code = VIEW_CONFIRM;
849                                 break;
850                         case VIEWROT_MODAL_SWITCH_MOVE:
851                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
852                                 event_code = VIEW_CONFIRM;
853                                 break;
854                 }
855         }
856         else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
857                 event_code = VIEW_CONFIRM;
858         }
859
860         if (event_code == VIEW_APPLY) {
861                 viewrotate_apply(vod, &event->x);
862                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
863                         use_autokey = true;
864                 }
865         }
866         else if (event_code == VIEW_CONFIRM) {
867                 ED_view3d_depth_tag_update(vod->rv3d);
868                 use_autokey = true;
869                 ret = OPERATOR_FINISHED;
870         }
871
872         if (use_autokey) {
873                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, true, true);
874         }
875
876         if (ret & OPERATOR_FINISHED) {
877                 viewops_data_free(C, op);
878         }
879
880         return ret;
881 }
882
883 static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event)
884 {
885         ViewOpsData *vod;
886
887         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
888
889         /* makes op->customdata */
890         viewops_data_alloc(C, op);
891         vod = op->customdata;
892
893         /* poll should check but in some cases fails, see poll func for details */
894         if (vod->rv3d->viewlock & RV3D_LOCKED) {
895                 viewops_data_free(C, op);
896                 return OPERATOR_PASS_THROUGH;
897         }
898
899         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
900
901         viewops_data_create(
902                 C, op, event,
903                 viewops_flag_from_prefs() |
904                 VIEWOPS_FLAG_PERSP_ENSURE |
905                 (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
906
907         if (ELEM(event->type, MOUSEPAN, MOUSEROTATE)) {
908                 /* Rotate direction we keep always same */
909                 int event_xy[2];
910
911                 if (event->type == MOUSEPAN) {
912                         if (U.uiflag2 & USER_TRACKPAD_NATURAL) {
913                                 event_xy[0] = 2 * event->x - event->prevx;
914                                 event_xy[1] = 2 * event->y - event->prevy;
915                         }
916                         else {
917                                 event_xy[0] = event->prevx;
918                                 event_xy[1] = event->prevy;
919                         }
920                 }
921                 else {
922                         /* MOUSEROTATE performs orbital rotation, so y axis delta is set to 0 */
923                         event_xy[0] = event->prevx;
924                         event_xy[1] = event->y;
925                 }
926
927                 viewrotate_apply(vod, event_xy);
928                 ED_view3d_depth_tag_update(vod->rv3d);
929
930                 viewops_data_free(C, op);
931
932                 return OPERATOR_FINISHED;
933         }
934         else {
935                 /* add temp handler */
936                 WM_event_add_modal_handler(C, op);
937
938                 return OPERATOR_RUNNING_MODAL;
939         }
940 }
941
942 /* test for unlocked camera view in quad view */
943 static bool view3d_camera_user_poll(bContext *C)
944 {
945         View3D *v3d;
946         ARegion *ar;
947
948         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
949                 RegionView3D *rv3d = ar->regiondata;
950                 if (rv3d->persp == RV3D_CAMOB) {
951                         return 1;
952                 }
953         }
954
955         return 0;
956 }
957
958 static bool view3d_lock_poll(bContext *C)
959 {
960         View3D *v3d = CTX_wm_view3d(C);
961         if (v3d) {
962                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
963                 if (rv3d) {
964                         return ED_view3d_offset_lock_check(v3d, rv3d);
965                 }
966         }
967         return false;
968 }
969
970 static void viewrotate_cancel(bContext *C, wmOperator *op)
971 {
972         viewops_data_free(C, op);
973 }
974
975 void VIEW3D_OT_rotate(wmOperatorType *ot)
976 {
977         /* identifiers */
978         ot->name = "Rotate View";
979         ot->description = "Rotate the view";
980         ot->idname = "VIEW3D_OT_rotate";
981
982         /* api callbacks */
983         ot->invoke = viewrotate_invoke;
984         ot->modal = viewrotate_modal;
985         ot->poll = ED_operator_region_view3d_active;
986         ot->cancel = viewrotate_cancel;
987
988         /* flags */
989         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
990
991         view3d_operator_properties_common(ot, V3D_OP_PROP_USE_MOUSE_INIT);
992 }
993
994 /** \} */
995
996 /* -------------------------------------------------------------------- */
997 /** \name NDOF Utility Functions
998  * \{ */
999
1000 #ifdef WITH_INPUT_NDOF
1001 #define NDOF_HAS_TRANSLATE ((!ED_view3d_offset_lock_check(v3d, rv3d)) && !is_zero_v3(ndof->tvec))
1002 #define NDOF_HAS_ROTATE    (((rv3d->viewlock & RV3D_LOCKED) == 0) && !is_zero_v3(ndof->rvec))
1003
1004 /**
1005  * \param depth_pt: A point to calculate the depth (in perspective mode)
1006  */
1007 static float view3d_ndof_pan_speed_calc_ex(RegionView3D *rv3d, const float depth_pt[3])
1008 {
1009         float speed = rv3d->pixsize * NDOF_PIXELS_PER_SECOND;
1010
1011         if (rv3d->is_persp) {
1012                 speed *= ED_view3d_calc_zfac(rv3d, depth_pt, NULL);
1013         }
1014
1015         return speed;
1016 }
1017
1018 static float view3d_ndof_pan_speed_calc_from_dist(RegionView3D *rv3d, const float dist)
1019 {
1020         float viewinv[4];
1021         float tvec[3];
1022
1023         BLI_assert(dist >= 0.0f);
1024
1025         copy_v3_fl3(tvec, 0.0f, 0.0f, dist);
1026         /* rv3d->viewinv isn't always valid */
1027 #if 0
1028         mul_mat3_m4_v3(rv3d->viewinv, tvec);
1029 #else
1030         invert_qt_qt_normalized(viewinv, rv3d->viewquat);
1031         mul_qt_v3(viewinv, tvec);
1032 #endif
1033
1034         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1035 }
1036
1037 static float view3d_ndof_pan_speed_calc(RegionView3D *rv3d)
1038 {
1039         float tvec[3];
1040         negate_v3_v3(tvec, rv3d->ofs);
1041
1042         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1043 }
1044
1045 /**
1046  * Zoom and pan in the same function since sometimes zoom is interpreted as dolly (pan forward).
1047  *
1048  * \param has_zoom zoom, otherwise dolly, often `!rv3d->is_persp` since it doesnt make sense to dolly in ortho.
1049  */
1050 static void view3d_ndof_pan_zoom(
1051         const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1052         const bool has_translate, const bool has_zoom)
1053 {
1054         RegionView3D *rv3d = ar->regiondata;
1055         float view_inv[4];
1056         float pan_vec[3];
1057
1058         if (has_translate == false && has_zoom == false) {
1059                 return;
1060         }
1061
1062         WM_event_ndof_pan_get(ndof, pan_vec, false);
1063
1064         if (has_zoom) {
1065                 /* zoom with Z */
1066
1067                 /* Zoom!
1068                  * velocity should be proportional to the linear velocity attained by rotational motion of same strength
1069                  * [got that?]
1070                  * proportional to arclength = radius * angle
1071                  */
1072
1073                 pan_vec[2] = 0.0f;
1074
1075                 /* "zoom in" or "translate"? depends on zoom mode in user settings? */
1076                 if (ndof->tvec[2]) {
1077                         float zoom_distance = rv3d->dist * ndof->dt * ndof->tvec[2];
1078
1079                         if (U.ndof_flag & NDOF_ZOOM_INVERT)
1080                                 zoom_distance = -zoom_distance;
1081
1082                         rv3d->dist += zoom_distance;
1083                 }
1084         }
1085         else {
1086                 /* dolly with Z */
1087
1088                 /* all callers must check */
1089                 if (has_translate) {
1090                         BLI_assert(ED_view3d_offset_lock_check((View3D *)sa->spacedata.first, rv3d) == false);
1091                 }
1092         }
1093
1094         if (has_translate) {
1095                 const float speed = view3d_ndof_pan_speed_calc(rv3d);
1096
1097                 mul_v3_fl(pan_vec, speed * ndof->dt);
1098
1099                 /* transform motion from view to world coordinates */
1100                 invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1101                 mul_qt_v3(view_inv, pan_vec);
1102
1103                 /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1104                 sub_v3_v3(rv3d->ofs, pan_vec);
1105
1106                 if (rv3d->viewlock & RV3D_BOXVIEW) {
1107                         view3d_boxview_sync(sa, ar);
1108                 }
1109         }
1110 }
1111
1112
1113 static void view3d_ndof_orbit(
1114         const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1115         ViewOpsData *vod, const bool apply_dyn_ofs)
1116 {
1117         View3D *v3d = sa->spacedata.first;
1118         RegionView3D *rv3d = ar->regiondata;
1119
1120         float view_inv[4];
1121
1122         BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
1123
1124         ED_view3d_persp_ensure(vod->depsgraph, v3d, ar);
1125
1126         rv3d->view = RV3D_VIEW_USER;
1127
1128         invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1129
1130         if (U.ndof_flag & NDOF_TURNTABLE) {
1131                 float rot[3];
1132
1133                 /* turntable view code by John Aughey, adapted for 3D mouse by [mce] */
1134                 float angle, quat[4];
1135                 float xvec[3] = {1, 0, 0};
1136
1137                 /* only use XY, ignore Z */
1138                 WM_event_ndof_rotate_get(ndof, rot);
1139
1140                 /* Determine the direction of the x vector (for rotating up and down) */
1141                 mul_qt_v3(view_inv, xvec);
1142
1143                 /* Perform the up/down rotation */
1144                 angle = ndof->dt * rot[0];
1145                 axis_angle_to_quat(quat, xvec, angle);
1146                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1147
1148                 /* Perform the orbital rotation */
1149                 angle = ndof->dt * rot[1];
1150
1151                 /* update the onscreen doo-dad */
1152                 rv3d->rot_angle = angle;
1153                 rv3d->rot_axis[0] = 0;
1154                 rv3d->rot_axis[1] = 0;
1155                 rv3d->rot_axis[2] = 1;
1156
1157                 axis_angle_to_quat_single(quat, 'Z', angle);
1158                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1159         }
1160         else {
1161                 float quat[4];
1162                 float axis[3];
1163                 float angle = WM_event_ndof_to_axis_angle(ndof, axis);
1164
1165                 /* transform rotation axis from view to world coordinates */
1166                 mul_qt_v3(view_inv, axis);
1167
1168                 /* update the onscreen doo-dad */
1169                 rv3d->rot_angle = angle;
1170                 copy_v3_v3(rv3d->rot_axis, axis);
1171
1172                 axis_angle_to_quat(quat, axis, angle);
1173
1174                 /* apply rotation */
1175                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1176         }
1177
1178         if (apply_dyn_ofs) {
1179                 viewrotate_apply_dyn_ofs(vod, rv3d->viewquat);
1180         }
1181 }
1182
1183 /**
1184  * Called from both fly mode and walk mode,
1185  */
1186 void view3d_ndof_fly(
1187         const wmNDOFMotionData *ndof,
1188         View3D *v3d, RegionView3D *rv3d,
1189         const bool use_precision, const short protectflag,
1190         bool *r_has_translate, bool *r_has_rotate)
1191 {
1192         bool has_translate = NDOF_HAS_TRANSLATE;
1193         bool has_rotate = NDOF_HAS_ROTATE;
1194
1195         float view_inv[4];
1196         invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1197
1198         rv3d->rot_angle = 0.0f;  /* disable onscreen rotation doo-dad */
1199
1200         if (has_translate) {
1201                 /* ignore real 'dist' since fly has its own speed settings,
1202                  * also its overwritten at this point. */
1203                 float speed = view3d_ndof_pan_speed_calc_from_dist(rv3d, 1.0f);
1204                 float trans[3], trans_orig_y;
1205
1206                 if (use_precision)
1207                         speed *= 0.2f;
1208
1209                 WM_event_ndof_pan_get(ndof, trans, false);
1210                 mul_v3_fl(trans, speed * ndof->dt);
1211                 trans_orig_y = trans[1];
1212
1213                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1214                         trans[1] = 0.0f;
1215                 }
1216
1217                 /* transform motion from view to world coordinates */
1218                 mul_qt_v3(view_inv, trans);
1219
1220                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1221                         /* replace world z component with device y (yes it makes sense) */
1222                         trans[2] = trans_orig_y;
1223                 }
1224
1225                 if (rv3d->persp == RV3D_CAMOB) {
1226                         /* respect camera position locks */
1227                         if (protectflag & OB_LOCK_LOCX) trans[0] = 0.0f;
1228                         if (protectflag & OB_LOCK_LOCY) trans[1] = 0.0f;
1229                         if (protectflag & OB_LOCK_LOCZ) trans[2] = 0.0f;
1230                 }
1231
1232                 if (!is_zero_v3(trans)) {
1233                         /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1234                         sub_v3_v3(rv3d->ofs, trans);
1235                         has_translate = true;
1236                 }
1237                 else {
1238                         has_translate = false;
1239                 }
1240         }
1241
1242         if (has_rotate) {
1243                 const float turn_sensitivity = 1.0f;
1244
1245                 float rotation[4];
1246                 float axis[3];
1247                 float angle = turn_sensitivity * WM_event_ndof_to_axis_angle(ndof, axis);
1248
1249                 if (fabsf(angle) > 0.0001f) {
1250                         has_rotate = true;
1251
1252                         if (use_precision)
1253                                 angle *= 0.2f;
1254
1255                         /* transform rotation axis from view to world coordinates */
1256                         mul_qt_v3(view_inv, axis);
1257
1258                         /* apply rotation to view */
1259                         axis_angle_to_quat(rotation, axis, angle);
1260                         mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1261
1262                         if (U.ndof_flag & NDOF_LOCK_HORIZON) {
1263                                 /* force an upright viewpoint
1264                                  * TODO: make this less... sudden */
1265                                 float view_horizon[3] = {1.0f, 0.0f, 0.0f}; /* view +x */
1266                                 float view_direction[3] = {0.0f, 0.0f, -1.0f}; /* view -z (into screen) */
1267
1268                                 /* find new inverse since viewquat has changed */
1269                                 invert_qt_qt_normalized(view_inv, rv3d->viewquat);
1270                                 /* could apply reverse rotation to existing view_inv to save a few cycles */
1271
1272                                 /* transform view vectors to world coordinates */
1273                                 mul_qt_v3(view_inv, view_horizon);
1274                                 mul_qt_v3(view_inv, view_direction);
1275
1276
1277                                 /* find difference between view & world horizons
1278                                  * true horizon lives in world xy plane, so look only at difference in z */
1279                                 angle = -asinf(view_horizon[2]);
1280
1281                                 /* rotate view so view horizon = world horizon */
1282                                 axis_angle_to_quat(rotation, view_direction, angle);
1283                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1284                         }
1285
1286                         rv3d->view = RV3D_VIEW_USER;
1287                 }
1288                 else {
1289                         has_rotate = false;
1290                 }
1291         }
1292
1293         *r_has_translate = has_translate;
1294         *r_has_rotate    = has_rotate;
1295 }
1296
1297 /** \} */
1298
1299 /* -------------------------------------------------------------------- */
1300 /** \name NDOF Operators
1301  *
1302  * - "orbit" navigation (trackball/turntable)
1303  * - zooming
1304  * - panning in rotationally-locked views
1305  * \{ */
1306
1307 static int ndof_orbit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1308 {
1309         if (event->type != NDOF_MOTION) {
1310                 return OPERATOR_CANCELLED;
1311         }
1312         else {
1313                 const Depsgraph *depsgraph = CTX_data_depsgraph(C);
1314                 ViewOpsData *vod;
1315                 View3D *v3d;
1316                 RegionView3D *rv3d;
1317
1318                 const wmNDOFMotionData *ndof = event->customdata;
1319
1320                 viewops_data_alloc(C, op);
1321                 viewops_data_create(
1322                         C, op, event,
1323                         viewops_flag_from_args((U.uiflag & USER_ORBIT_SELECTION) != 0, false));
1324                 vod = op->customdata;
1325
1326                 ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1327
1328                 v3d = vod->v3d;
1329                 rv3d = vod->rv3d;
1330
1331                 /* off by default, until changed later this function */
1332                 rv3d->rot_angle = 0.0f;
1333
1334                 ED_view3d_camera_lock_init_ex(depsgraph, v3d, rv3d, false);
1335
1336                 if (ndof->progress != P_FINISHING) {
1337                         const bool has_rotation = NDOF_HAS_ROTATE;
1338                         /* if we can't rotate, fallback to translate (locked axis views) */
1339                         const bool has_translate = NDOF_HAS_TRANSLATE && (rv3d->viewlock & RV3D_LOCKED);
1340                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1341
1342                         if (has_translate || has_zoom) {
1343                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1344                         }
1345
1346                         if (has_rotation) {
1347                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod, true);
1348                         }
1349                 }
1350
1351                 ED_view3d_camera_lock_sync(depsgraph, v3d, rv3d);
1352
1353                 ED_region_tag_redraw(vod->ar);
1354
1355                 viewops_data_free(C, op);
1356
1357                 return OPERATOR_FINISHED;
1358         }
1359 }
1360
1361 void VIEW3D_OT_ndof_orbit(struct wmOperatorType *ot)
1362 {
1363         /* identifiers */
1364         ot->name = "NDOF Orbit View";
1365         ot->description = "Orbit the view using the 3D mouse";
1366         ot->idname = "VIEW3D_OT_ndof_orbit";
1367
1368         /* api callbacks */
1369         ot->invoke = ndof_orbit_invoke;
1370         ot->poll = ED_operator_view3d_active;
1371
1372         /* flags */
1373         ot->flag = 0;
1374 }
1375
1376 static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1377 {
1378         if (event->type != NDOF_MOTION) {
1379                 return OPERATOR_CANCELLED;
1380         }
1381         else {
1382                 const Depsgraph *depsgraph = CTX_data_depsgraph(C);
1383                 ViewOpsData *vod;
1384                 View3D *v3d;
1385                 RegionView3D *rv3d;
1386
1387                 const wmNDOFMotionData *ndof = event->customdata;
1388
1389                 viewops_data_alloc(C, op);
1390                 viewops_data_create(
1391                         C, op, event,
1392                         viewops_flag_from_args((U.uiflag & USER_ORBIT_SELECTION) != 0, false));
1393
1394                 vod = op->customdata;
1395
1396                 ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1397
1398                 v3d = vod->v3d;
1399                 rv3d = vod->rv3d;
1400
1401                 /* off by default, until changed later this function */
1402                 rv3d->rot_angle = 0.0f;
1403
1404                 ED_view3d_camera_lock_init_ex(depsgraph, v3d, rv3d, false);
1405
1406                 if (ndof->progress == P_FINISHING) {
1407                         /* pass */
1408                 }
1409                 else if ((rv3d->persp == RV3D_ORTHO) && RV3D_VIEW_IS_AXIS(rv3d->view)) {
1410                         /* if we can't rotate, fallback to translate (locked axis views) */
1411                         const bool has_translate = NDOF_HAS_TRANSLATE;
1412                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && ED_view3d_offset_lock_check(v3d, rv3d);
1413
1414                         if (has_translate || has_zoom) {
1415                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, true);
1416                         }
1417                 }
1418                 else if ((U.ndof_flag & NDOF_MODE_ORBIT) ||
1419                          ED_view3d_offset_lock_check(v3d, rv3d))
1420                 {
1421                         const bool has_rotation = NDOF_HAS_ROTATE;
1422                         const bool has_zoom = (ndof->tvec[2] != 0.0f);
1423
1424                         if (has_zoom) {
1425                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, false, has_zoom);
1426                         }
1427
1428                         if (has_rotation) {
1429                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod, true);
1430                         }
1431                 }
1432                 else {  /* free/explore (like fly mode) */
1433                         const bool has_rotation = NDOF_HAS_ROTATE;
1434                         const bool has_translate = NDOF_HAS_TRANSLATE;
1435                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1436
1437                         float dist_backup;
1438
1439                         if (has_translate || has_zoom) {
1440                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1441                         }
1442
1443                         dist_backup = rv3d->dist;
1444                         ED_view3d_distance_set(rv3d, 0.0f);
1445
1446                         if (has_rotation) {
1447                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod, false);
1448                         }
1449
1450                         ED_view3d_distance_set(rv3d, dist_backup);
1451                 }
1452
1453                 ED_view3d_camera_lock_sync(depsgraph, v3d, rv3d);
1454
1455                 ED_region_tag_redraw(vod->ar);
1456
1457                 viewops_data_free(C, op);
1458
1459                 return OPERATOR_FINISHED;
1460         }
1461 }
1462
1463 void VIEW3D_OT_ndof_orbit_zoom(struct wmOperatorType *ot)
1464 {
1465         /* identifiers */
1466         ot->name = "NDOF Orbit View with Zoom";
1467         ot->description = "Orbit and zoom the view using the 3D mouse";
1468         ot->idname = "VIEW3D_OT_ndof_orbit_zoom";
1469
1470         /* api callbacks */
1471         ot->invoke = ndof_orbit_zoom_invoke;
1472         ot->poll = ED_operator_view3d_active;
1473
1474         /* flags */
1475         ot->flag = 0;
1476 }
1477
1478 /* -- "pan" navigation
1479  * -- zoom or dolly?
1480  */
1481 static int ndof_pan_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1482 {
1483         if (event->type != NDOF_MOTION) {
1484                 return OPERATOR_CANCELLED;
1485         }
1486         else {
1487                 const Depsgraph *depsgraph = CTX_data_depsgraph(C);
1488                 View3D *v3d = CTX_wm_view3d(C);
1489                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1490                 const wmNDOFMotionData *ndof = event->customdata;
1491
1492                 const bool has_translate = NDOF_HAS_TRANSLATE;
1493                 const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1494
1495                 /* we're panning here! so erase any leftover rotation from other operators */
1496                 rv3d->rot_angle = 0.0f;
1497
1498                 if (!(has_translate || has_zoom))
1499                         return OPERATOR_CANCELLED;
1500
1501                 ED_view3d_camera_lock_init_ex(depsgraph, v3d, rv3d, false);
1502
1503                 if (ndof->progress != P_FINISHING) {
1504                         ScrArea *sa = CTX_wm_area(C);
1505                         ARegion *ar = CTX_wm_region(C);
1506
1507                         if (has_translate || has_zoom) {
1508                                 view3d_ndof_pan_zoom(ndof, sa, ar, has_translate, has_zoom);
1509                         }
1510                 }
1511
1512                 ED_view3d_camera_lock_sync(depsgraph, v3d, rv3d);
1513
1514                 ED_region_tag_redraw(CTX_wm_region(C));
1515
1516                 return OPERATOR_FINISHED;
1517         }
1518 }
1519
1520 void VIEW3D_OT_ndof_pan(struct wmOperatorType *ot)
1521 {
1522         /* identifiers */
1523         ot->name = "NDOF Pan View";
1524         ot->description = "Pan the view with the 3D mouse";
1525         ot->idname = "VIEW3D_OT_ndof_pan";
1526
1527         /* api callbacks */
1528         ot->invoke = ndof_pan_invoke;
1529         ot->poll = ED_operator_view3d_active;
1530
1531         /* flags */
1532         ot->flag = 0;
1533 }
1534
1535
1536 /**
1537  * wraps #ndof_orbit_zoom but never restrict to orbit.
1538  */
1539 static int ndof_all_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1540 {
1541         /* weak!, but it works */
1542         const int ndof_flag = U.ndof_flag;
1543         int ret;
1544
1545         U.ndof_flag &= ~NDOF_MODE_ORBIT;
1546
1547         ret = ndof_orbit_zoom_invoke(C, op, event);
1548
1549         U.ndof_flag = ndof_flag;
1550
1551         return ret;
1552 }
1553
1554 void VIEW3D_OT_ndof_all(struct wmOperatorType *ot)
1555 {
1556         /* identifiers */
1557         ot->name = "NDOF Pan View";
1558         ot->description = "Pan and rotate the view with the 3D mouse";
1559         ot->idname = "VIEW3D_OT_ndof_all";
1560
1561         /* api callbacks */
1562         ot->invoke = ndof_all_invoke;
1563         ot->poll = ED_operator_view3d_active;
1564
1565         /* flags */
1566         ot->flag = 0;
1567 }
1568
1569 #endif /* WITH_INPUT_NDOF */
1570
1571 /** \} */
1572
1573 /* -------------------------------------------------------------------- */
1574 /** \name View Move (Pan) Operator
1575  * \{ */
1576
1577 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
1578
1579 /* called in transform_ops.c, on each regeneration of keymaps  */
1580 void viewmove_modal_keymap(wmKeyConfig *keyconf)
1581 {
1582         static const EnumPropertyItem modal_items[] = {
1583                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1584
1585                 {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
1586                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1587
1588                 {0, NULL, 0, NULL, NULL}
1589         };
1590
1591         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Move Modal");
1592
1593         /* this function is called for each spacetype, only needs to add map once */
1594         if (keymap && keymap->modal_items) return;
1595
1596         keymap = WM_modalkeymap_add(keyconf, "View3D Move Modal", modal_items);
1597
1598         /* items for modal map */
1599         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1600         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1601
1602         /* disabled mode switching for now, can re-implement better, later on */
1603 #if 0
1604         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1605         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1606         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1607 #endif
1608
1609         /* assign map to operators */
1610         WM_modalkeymap_assign(keymap, "VIEW3D_OT_move");
1611 }
1612
1613
1614 static void viewmove_apply(ViewOpsData *vod, int x, int y)
1615 {
1616         if (ED_view3d_offset_lock_check(vod->v3d, vod->rv3d)) {
1617                 vod->rv3d->ofs_lock[0] -= ((vod->prev.event_xy[0] - x) * 2.0f) / (float)vod->ar->winx;
1618                 vod->rv3d->ofs_lock[1] -= ((vod->prev.event_xy[1] - y) * 2.0f) / (float)vod->ar->winy;
1619         }
1620         else if ((vod->rv3d->persp == RV3D_CAMOB) && !ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) {
1621                 const float zoomfac = BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
1622                 vod->rv3d->camdx += (vod->prev.event_xy[0] - x) / (vod->ar->winx * zoomfac);
1623                 vod->rv3d->camdy += (vod->prev.event_xy[1] - y) / (vod->ar->winy * zoomfac);
1624                 CLAMP(vod->rv3d->camdx, -1.0f, 1.0f);
1625                 CLAMP(vod->rv3d->camdy, -1.0f, 1.0f);
1626         }
1627         else {
1628                 float dvec[3];
1629                 float mval_f[2];
1630
1631                 mval_f[0] = x - vod->prev.event_xy[0];
1632                 mval_f[1] = y - vod->prev.event_xy[1];
1633                 ED_view3d_win_to_delta(vod->ar, mval_f, dvec, vod->init.zfac);
1634
1635                 add_v3_v3(vod->rv3d->ofs, dvec);
1636
1637                 if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
1638                         view3d_boxview_sync(vod->sa, vod->ar);
1639                 }
1640         }
1641
1642         vod->prev.event_xy[0] = x;
1643         vod->prev.event_xy[1] = y;
1644
1645         ED_view3d_camera_lock_sync(vod->depsgraph, vod->v3d, vod->rv3d);
1646
1647         ED_region_tag_redraw(vod->ar);
1648 }
1649
1650
1651 static int viewmove_modal(bContext *C, wmOperator *op, const wmEvent *event)
1652 {
1653
1654         ViewOpsData *vod = op->customdata;
1655         short event_code = VIEW_PASS;
1656         bool use_autokey = false;
1657         int ret = OPERATOR_RUNNING_MODAL;
1658
1659         /* execute the events */
1660         if (event->type == MOUSEMOVE) {
1661                 event_code = VIEW_APPLY;
1662         }
1663         else if (event->type == EVT_MODAL_MAP) {
1664                 switch (event->val) {
1665                         case VIEW_MODAL_CONFIRM:
1666                                 event_code = VIEW_CONFIRM;
1667                                 break;
1668                         case VIEWROT_MODAL_SWITCH_ZOOM:
1669                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1670                                 event_code = VIEW_CONFIRM;
1671                                 break;
1672                         case VIEWROT_MODAL_SWITCH_ROTATE:
1673                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1674                                 event_code = VIEW_CONFIRM;
1675                                 break;
1676                 }
1677         }
1678         else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
1679                 event_code = VIEW_CONFIRM;
1680         }
1681
1682         if (event_code == VIEW_APPLY) {
1683                 viewmove_apply(vod, event->x, event->y);
1684                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
1685                         use_autokey = true;
1686                 }
1687         }
1688         else if (event_code == VIEW_CONFIRM) {
1689                 ED_view3d_depth_tag_update(vod->rv3d);
1690                 use_autokey = true;
1691                 ret = OPERATOR_FINISHED;
1692         }
1693
1694         if (use_autokey) {
1695                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
1696         }
1697
1698         if (ret & OPERATOR_FINISHED) {
1699                 viewops_data_free(C, op);
1700         }
1701
1702         return ret;
1703 }
1704
1705 static int viewmove_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1706 {
1707         ViewOpsData *vod;
1708
1709         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
1710
1711         /* makes op->customdata */
1712         viewops_data_alloc(C, op);
1713         viewops_data_create(
1714                 C, op, event,
1715                 viewops_flag_from_prefs() |
1716                 (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
1717         vod = op->customdata;
1718
1719         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
1720
1721         if (event->type == MOUSEPAN) {
1722                 /* invert it, trackpad scroll follows same principle as 2d windows this way */
1723                 viewmove_apply(vod, 2 * event->x - event->prevx, 2 * event->y - event->prevy);
1724                 ED_view3d_depth_tag_update(vod->rv3d);
1725
1726                 viewops_data_free(C, op);
1727
1728                 return OPERATOR_FINISHED;
1729         }
1730         else {
1731                 /* add temp handler */
1732                 WM_event_add_modal_handler(C, op);
1733
1734                 return OPERATOR_RUNNING_MODAL;
1735         }
1736 }
1737
1738 static void viewmove_cancel(bContext *C, wmOperator *op)
1739 {
1740         viewops_data_free(C, op);
1741 }
1742
1743 void VIEW3D_OT_move(wmOperatorType *ot)
1744 {
1745
1746         /* identifiers */
1747         ot->name = "Pan View";
1748         ot->description = "Move the view";
1749         ot->idname = "VIEW3D_OT_move";
1750
1751         /* api callbacks */
1752         ot->invoke = viewmove_invoke;
1753         ot->modal = viewmove_modal;
1754         ot->poll = ED_operator_view3d_active;
1755         ot->cancel = viewmove_cancel;
1756
1757         /* flags */
1758         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
1759
1760         /* properties */
1761         view3d_operator_properties_common(ot, V3D_OP_PROP_USE_MOUSE_INIT);
1762 }
1763
1764 /** \} */
1765
1766 /* -------------------------------------------------------------------- */
1767 /** \name View Zoom Operator
1768  * \{ */
1769
1770 /* viewdolly_modal_keymap has an exact copy of this, apply fixes to both */
1771 /* called in transform_ops.c, on each regeneration of keymaps  */
1772 void viewzoom_modal_keymap(wmKeyConfig *keyconf)
1773 {
1774         static const EnumPropertyItem modal_items[] = {
1775                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1776
1777                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1778                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
1779
1780                 {0, NULL, 0, NULL, NULL}
1781         };
1782
1783         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Zoom Modal");
1784
1785         /* this function is called for each spacetype, only needs to add map once */
1786         if (keymap && keymap->modal_items) return;
1787
1788         keymap = WM_modalkeymap_add(keyconf, "View3D Zoom Modal", modal_items);
1789
1790         /* items for modal map */
1791         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1792         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1793
1794         /* disabled mode switching for now, can re-implement better, later on */
1795 #if 0
1796         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1797         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1798         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
1799 #endif
1800
1801         /* assign map to operators */
1802         WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom");
1803 }
1804
1805 /**
1806  * \param zoom_xy: Optionally zoom to window location (coords compatible w/ #wmEvent.x, y). Use when not NULL.
1807  */
1808 static void view_zoom_to_window_xy_camera(
1809         Scene *scene, Depsgraph *depsgraph, View3D *v3d,
1810         ARegion *ar, float dfac, const int zoom_xy[2])
1811 {
1812         RegionView3D *rv3d = ar->regiondata;
1813         const float zoomfac = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
1814         const float zoomfac_new = clamp_f(zoomfac * (1.0f / dfac), RV3D_CAMZOOM_MIN_FACTOR, RV3D_CAMZOOM_MAX_FACTOR);
1815         const float camzoom_new = BKE_screen_view3d_zoom_from_fac(zoomfac_new);
1816
1817
1818         if (zoom_xy != NULL) {
1819                 float zoomfac_px;
1820                 rctf camera_frame_old;
1821                 rctf camera_frame_new;
1822
1823                 const float pt_src[2] = {zoom_xy[0], zoom_xy[1]};
1824                 float pt_dst[2];
1825                 float delta_px[2];
1826
1827                 ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &camera_frame_old, false);
1828                 BLI_rctf_translate(&camera_frame_old, ar->winrct.xmin, ar->winrct.ymin);
1829
1830                 rv3d->camzoom = camzoom_new;
1831                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
1832
1833                 ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &camera_frame_new, false);
1834                 BLI_rctf_translate(&camera_frame_new, ar->winrct.xmin, ar->winrct.ymin);
1835
1836                 BLI_rctf_transform_pt_v(&camera_frame_new, &camera_frame_old, pt_dst, pt_src);
1837                 sub_v2_v2v2(delta_px, pt_dst, pt_src);
1838
1839                 /* translate the camera offset using pixel space delta
1840                  * mapped back to the camera (same logic as panning in camera view) */
1841                 zoomfac_px = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom) * 2.0f;
1842
1843                 rv3d->camdx += delta_px[0] / (ar->winx * zoomfac_px);
1844                 rv3d->camdy += delta_px[1] / (ar->winy * zoomfac_px);
1845                 CLAMP(rv3d->camdx, -1.0f, 1.0f);
1846                 CLAMP(rv3d->camdy, -1.0f, 1.0f);
1847         }
1848         else {
1849                 rv3d->camzoom = camzoom_new;
1850                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
1851         }
1852 }
1853
1854 /**
1855  * \param zoom_xy: Optionally zoom to window location (coords compatible w/ #wmEvent.x, y). Use when not NULL.
1856  */
1857 static void view_zoom_to_window_xy_3d(ARegion *ar, float dfac, const int zoom_xy[2])
1858 {
1859         RegionView3D *rv3d = ar->regiondata;
1860         const float dist_new = rv3d->dist * dfac;
1861
1862         if (zoom_xy != NULL) {
1863                 float dvec[3];
1864                 float tvec[3];
1865                 float tpos[3];
1866                 float mval_f[2];
1867
1868                 float zfac;
1869
1870                 negate_v3_v3(tpos, rv3d->ofs);
1871
1872                 mval_f[0] = (float)(((zoom_xy[0] - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
1873                 mval_f[1] = (float)(((zoom_xy[1] - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
1874
1875                 /* Project cursor position into 3D space */
1876                 zfac = ED_view3d_calc_zfac(rv3d, tpos, NULL);
1877                 ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
1878
1879                 /* Calculate view target position for dolly */
1880                 add_v3_v3v3(tvec, tpos, dvec);
1881                 negate_v3(tvec);
1882
1883                 /* Offset to target position and dolly */
1884                 copy_v3_v3(rv3d->ofs, tvec);
1885                 rv3d->dist = dist_new;
1886
1887                 /* Calculate final offset */
1888                 madd_v3_v3v3fl(rv3d->ofs, tvec, dvec, dfac);
1889         }
1890         else {
1891                 rv3d->dist = dist_new;
1892         }
1893 }
1894
1895 static float viewzoom_scale_value(
1896         const rcti *winrct,
1897         const short viewzoom,
1898         const bool zoom_invert, const bool zoom_invert_force,
1899         const int xy_curr[2], const int xy_init[2],
1900         const float val, const float val_orig,
1901         double *r_timer_lastdraw)
1902 {
1903         float zfac;
1904
1905         if (viewzoom == USER_ZOOM_CONT) {
1906                 double time = PIL_check_seconds_timer();
1907                 float time_step = (float)(time - *r_timer_lastdraw);
1908                 float fac;
1909
1910                 if (U.uiflag & USER_ZOOM_HORIZ) {
1911                         fac = (float)(xy_init[0] - xy_curr[0]);
1912                 }
1913                 else {
1914                         fac = (float)(xy_init[1] - xy_curr[1]);
1915                 }
1916
1917                 if (zoom_invert != zoom_invert_force) {
1918                         fac = -fac;
1919                 }
1920
1921                 /* oldstyle zoom */
1922                 zfac = 1.0f + ((fac / 20.0f) * time_step);
1923                 *r_timer_lastdraw = time;
1924         }
1925         else if (viewzoom == USER_ZOOM_SCALE) {
1926                 /* method which zooms based on how far you move the mouse */
1927
1928                 const int ctr[2] = {
1929                     BLI_rcti_cent_x(winrct),
1930                     BLI_rcti_cent_y(winrct),
1931                 };
1932                 float len_new = 5 + len_v2v2_int(ctr, xy_curr);
1933                 float len_old = 5 + len_v2v2_int(ctr, xy_init);
1934
1935                 /* intentionally ignore 'zoom_invert' for scale */
1936                 if (zoom_invert_force) {
1937                         SWAP(float, len_new, len_old);
1938                 }
1939
1940                 zfac = val_orig * (len_old / max_ff(len_new, 1.0f)) / val;
1941         }
1942         else {  /* USER_ZOOM_DOLLY */
1943                 float len_new = 5;
1944                 float len_old = 5;
1945
1946                 if (U.uiflag & USER_ZOOM_HORIZ) {
1947                         len_new += (winrct->xmax - (xy_curr[0]));
1948                         len_old += (winrct->xmax - (xy_init[0]));
1949                 }
1950                 else {
1951                         len_new += (winrct->ymax - (xy_curr[1]));
1952                         len_old += (winrct->ymax - (xy_init[1]));
1953                 }
1954
1955                 if (zoom_invert != zoom_invert_force) {
1956                         SWAP(float, len_new, len_old);
1957                 }
1958
1959                 zfac = val_orig * (2.0f * ((len_new / max_ff(len_old, 1.0f)) - 1.0f) + 1.0f) / val;
1960         }
1961
1962
1963         return zfac;
1964 }
1965
1966 static float viewzoom_scale_value_offset(
1967         const rcti *winrct,
1968         const short viewzoom,
1969         const bool zoom_invert, const bool zoom_invert_force,
1970         const int xy_curr[2], const int xy_init[2], const int xy_offset[2],
1971         const float val, const float val_orig,
1972         double *r_timer_lastdraw)
1973 {
1974         const int xy_curr_offset[2] = {
1975                 xy_curr[0] + xy_offset[0],
1976                 xy_curr[1] + xy_offset[1],
1977         };
1978         const int xy_init_offset[2] = {
1979                 xy_init[0] + xy_offset[0],
1980                 xy_init[1] + xy_offset[1],
1981         };
1982         return viewzoom_scale_value(
1983                 winrct, viewzoom, zoom_invert, zoom_invert_force,
1984                 xy_curr_offset, xy_init_offset,
1985                 val, val_orig, r_timer_lastdraw);
1986 }
1987
1988 static void viewzoom_apply_camera(
1989         ViewOpsData *vod, const int xy[2],
1990         const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
1991 {
1992         float zfac;
1993         float zoomfac_prev = BKE_screen_view3d_zoom_to_fac(vod->init.camzoom) * 2.0f;
1994         float zoomfac =      BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
1995
1996         zfac = viewzoom_scale_value_offset(
1997                &vod->ar->winrct, viewzoom, zoom_invert, true,
1998                xy, vod->init.event_xy, vod->init.event_xy_offset,
1999                zoomfac, zoomfac_prev,
2000                &vod->prev.time);
2001
2002         if (zfac != 1.0f && zfac != 0.0f) {
2003                 /* calculate inverted, then invert again (needed because of camera zoom scaling) */
2004                 zfac = 1.0f / zfac;
2005                 view_zoom_to_window_xy_camera(
2006                         vod->scene, vod->depsgraph, vod->v3d,
2007                         vod->ar, zfac, zoom_to_pos ? vod->prev.event_xy : NULL);
2008         }
2009
2010         ED_region_tag_redraw(vod->ar);
2011 }
2012
2013 static void viewzoom_apply_3d(
2014         ViewOpsData *vod, const int xy[2],
2015         const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
2016 {
2017         float zfac;
2018         float dist_range[2];
2019
2020         ED_view3d_dist_range_get(vod->v3d, dist_range);
2021
2022         zfac = viewzoom_scale_value_offset(
2023                &vod->ar->winrct, viewzoom, zoom_invert, false,
2024                xy, vod->init.event_xy, vod->init.event_xy_offset,
2025                vod->rv3d->dist, vod->init.dist,
2026                &vod->prev.time);
2027
2028         if (zfac != 1.0f) {
2029                 const float zfac_min = dist_range[0] / vod->rv3d->dist;
2030                 const float zfac_max = dist_range[1] / vod->rv3d->dist;
2031                 CLAMP(zfac, zfac_min, zfac_max);
2032
2033                 view_zoom_to_window_xy_3d(
2034                         vod->ar, zfac, zoom_to_pos ? vod->prev.event_xy : NULL);
2035         }
2036
2037         /* these limits were in old code too */
2038         CLAMP(vod->rv3d->dist, dist_range[0], dist_range[1]);
2039
2040         if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
2041                 view3d_boxview_sync(vod->sa, vod->ar);
2042         }
2043
2044         ED_view3d_camera_lock_sync(vod->depsgraph, vod->v3d, vod->rv3d);
2045
2046         ED_region_tag_redraw(vod->ar);
2047 }
2048
2049 static void viewzoom_apply(
2050         ViewOpsData *vod, const int xy[2],
2051         const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
2052 {
2053         if ((vod->rv3d->persp == RV3D_CAMOB) &&
2054             (vod->rv3d->is_persp && ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) == 0)
2055         {
2056                 viewzoom_apply_camera(vod, xy, viewzoom, zoom_invert, zoom_to_pos);
2057         }
2058         else {
2059                 viewzoom_apply_3d(vod, xy, viewzoom, zoom_invert, zoom_to_pos);
2060         }
2061 }
2062
2063 static int viewzoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
2064 {
2065         ViewOpsData *vod = op->customdata;
2066         short event_code = VIEW_PASS;
2067         bool use_autokey = false;
2068         int ret = OPERATOR_RUNNING_MODAL;
2069
2070         /* execute the events */
2071         if (event->type == TIMER && event->customdata == vod->timer) {
2072                 /* continuous zoom */
2073                 event_code = VIEW_APPLY;
2074         }
2075         else if (event->type == MOUSEMOVE) {
2076                 event_code = VIEW_APPLY;
2077         }
2078         else if (event->type == EVT_MODAL_MAP) {
2079                 switch (event->val) {
2080                         case VIEW_MODAL_CONFIRM:
2081                                 event_code = VIEW_CONFIRM;
2082                                 break;
2083                         case VIEWROT_MODAL_SWITCH_MOVE:
2084                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2085                                 event_code = VIEW_CONFIRM;
2086                                 break;
2087                         case VIEWROT_MODAL_SWITCH_ROTATE:
2088                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2089                                 event_code = VIEW_CONFIRM;
2090                                 break;
2091                 }
2092         }
2093         else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
2094                 event_code = VIEW_CONFIRM;
2095         }
2096
2097         if (event_code == VIEW_APPLY) {
2098                 const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
2099                 viewzoom_apply(
2100                         vod, &event->x, U.viewzoom,
2101                         (U.uiflag & USER_ZOOM_INVERT) != 0,
2102                         (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)));
2103                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2104                         use_autokey = true;
2105                 }
2106         }
2107         else if (event_code == VIEW_CONFIRM) {
2108                 ED_view3d_depth_tag_update(vod->rv3d);
2109                 use_autokey = true;
2110                 ret = OPERATOR_FINISHED;
2111         }
2112
2113         if (use_autokey) {
2114                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2115         }
2116
2117         if (ret & OPERATOR_FINISHED) {
2118                 viewops_data_free(C, op);
2119         }
2120
2121         return ret;
2122 }
2123
2124 static int viewzoom_exec(bContext *C, wmOperator *op)
2125 {
2126         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2127         Scene *scene = CTX_data_scene(C);
2128         View3D *v3d;
2129         RegionView3D *rv3d;
2130         ScrArea *sa;
2131         ARegion *ar;
2132         bool use_cam_zoom;
2133         float dist_range[2];
2134
2135         const int delta = RNA_int_get(op->ptr, "delta");
2136         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
2137
2138         if (op->customdata) {
2139                 ViewOpsData *vod = op->customdata;
2140
2141                 sa = vod->sa;
2142                 ar = vod->ar;
2143         }
2144         else {
2145                 sa = CTX_wm_area(C);
2146                 ar = CTX_wm_region(C);
2147         }
2148
2149         v3d = sa->spacedata.first;
2150         rv3d = ar->regiondata;
2151
2152
2153         use_cam_zoom = (rv3d->persp == RV3D_CAMOB) && !(rv3d->is_persp && ED_view3d_camera_lock_check(v3d, rv3d));
2154
2155         int zoom_xy_buf[2];
2156         const int *zoom_xy = NULL;
2157         if (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) {
2158                 zoom_xy_buf[0] = RNA_struct_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
2159                 zoom_xy_buf[1] = RNA_struct_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
2160                 zoom_xy = zoom_xy_buf;
2161         }
2162
2163         ED_view3d_dist_range_get(v3d, dist_range);
2164
2165         if (delta < 0) {
2166                 const float step = 1.2f;
2167                 /* this min and max is also in viewmove() */
2168                 if (use_cam_zoom) {
2169                         view_zoom_to_window_xy_camera(scene, depsgraph, v3d, ar, step, zoom_xy);
2170                 }
2171                 else {
2172                         if (rv3d->dist < dist_range[1]) {
2173                                 view_zoom_to_window_xy_3d(ar, step, zoom_xy);
2174                         }
2175                 }
2176         }
2177         else {
2178                 const float step = 1.0f / 1.2f;
2179                 if (use_cam_zoom) {
2180                         view_zoom_to_window_xy_camera(scene, depsgraph, v3d, ar, step, zoom_xy);
2181                 }
2182                 else {
2183                         if (rv3d->dist > dist_range[0]) {
2184                                 view_zoom_to_window_xy_3d(ar, step, zoom_xy);
2185                         }
2186                 }
2187         }
2188
2189         if (rv3d->viewlock & RV3D_BOXVIEW) {
2190                 view3d_boxview_sync(sa, ar);
2191         }
2192
2193         ED_view3d_depth_tag_update(rv3d);
2194
2195         ED_view3d_camera_lock_sync(depsgraph, v3d, rv3d);
2196         ED_view3d_camera_lock_autokey(v3d, rv3d, C, false, true);
2197
2198         ED_region_tag_redraw(ar);
2199
2200         viewops_data_free(C, op);
2201
2202         return OPERATOR_FINISHED;
2203 }
2204
2205 /* viewdolly_invoke() copied this function, changes here may apply there */
2206 static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2207 {
2208         ViewOpsData *vod;
2209
2210         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
2211
2212         /* makes op->customdata */
2213         viewops_data_alloc(C, op);
2214         viewops_data_create(
2215                 C, op, event,
2216                 viewops_flag_from_prefs() |
2217                 (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
2218         vod = op->customdata;
2219
2220         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
2221
2222         /* if one or the other zoom position aren't set, set from event */
2223         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2224                 RNA_int_set(op->ptr, "mx", event->x);
2225                 RNA_int_set(op->ptr, "my", event->y);
2226         }
2227
2228         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2229                 viewzoom_exec(C, op);
2230         }
2231         else {
2232                 if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
2233
2234                         if (U.uiflag & USER_ZOOM_HORIZ) {
2235                                 vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
2236                         }
2237                         else {
2238                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2239                                 vod->init.event_xy[1] = vod->prev.event_xy[1] = vod->init.event_xy[1] + event->x - event->prevx;
2240                         }
2241                         viewzoom_apply(
2242                                 vod, &event->prevx, USER_ZOOM_DOLLY,
2243                                 (U.uiflag & USER_ZOOM_INVERT) != 0,
2244                                 (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)));
2245                         ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2246
2247                         ED_view3d_depth_tag_update(vod->rv3d);
2248
2249                         viewops_data_free(C, op);
2250                         return OPERATOR_FINISHED;
2251                 }
2252                 else {
2253                         if (U.viewzoom == USER_ZOOM_CONT) {
2254                                 /* needs a timer to continue redrawing */
2255                                 vod->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
2256                                 vod->prev.time = PIL_check_seconds_timer();
2257                         }
2258
2259                         /* add temp handler */
2260                         WM_event_add_modal_handler(C, op);
2261
2262                         return OPERATOR_RUNNING_MODAL;
2263                 }
2264         }
2265         return OPERATOR_FINISHED;
2266 }
2267
2268 static void viewzoom_cancel(bContext *C, wmOperator *op)
2269 {
2270         viewops_data_free(C, op);
2271 }
2272
2273 void VIEW3D_OT_zoom(wmOperatorType *ot)
2274 {
2275         /* identifiers */
2276         ot->name = "Zoom View";
2277         ot->description = "Zoom in/out in the view";
2278         ot->idname = "VIEW3D_OT_zoom";
2279
2280         /* api callbacks */
2281         ot->invoke = viewzoom_invoke;
2282         ot->exec = viewzoom_exec;
2283         ot->modal = viewzoom_modal;
2284         ot->poll = ED_operator_region_view3d_active;
2285         ot->cancel = viewzoom_cancel;
2286
2287         /* flags */
2288         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2289
2290         /* properties */
2291         view3d_operator_properties_common(
2292                 ot,
2293                 V3D_OP_PROP_DELTA | V3D_OP_PROP_MOUSE_CO | V3D_OP_PROP_USE_MOUSE_INIT);
2294 }
2295
2296 /** \} */
2297
2298 /* -------------------------------------------------------------------- */
2299 /** \name View Dolly Operator
2300  *
2301  * Like zoom but translates the view offset along the view direction
2302  * which avoids #RegionView3D.dist approaching zero.
2303  * \{ */
2304
2305 /* this is an exact copy of viewzoom_modal_keymap */
2306 /* called in transform_ops.c, on each regeneration of keymaps  */
2307 void viewdolly_modal_keymap(wmKeyConfig *keyconf)
2308 {
2309         static const EnumPropertyItem modal_items[] = {
2310                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
2311
2312                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
2313                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
2314
2315                 {0, NULL, 0, NULL, NULL}
2316         };
2317
2318         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
2319
2320         /* this function is called for each spacetype, only needs to add map once */
2321         if (keymap && keymap->modal_items) return;
2322
2323         keymap = WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
2324
2325         /* items for modal map */
2326         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2327         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2328
2329         /* disabled mode switching for now, can re-implement better, later on */
2330 #if 0
2331         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2332         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2333         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
2334 #endif
2335
2336         /* assign map to operators */
2337         WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
2338 }
2339
2340 static bool viewdolly_offset_lock_check(bContext *C, wmOperator *op)
2341 {
2342         View3D *v3d = CTX_wm_view3d(C);
2343         RegionView3D *rv3d = CTX_wm_region_view3d(C);
2344         if (ED_view3d_offset_lock_check(v3d, rv3d)) {
2345                 BKE_report(op->reports, RPT_WARNING, "Cannot dolly when the view offset is locked");
2346                 return true;
2347         }
2348         else {
2349                 return false;
2350         }
2351 }
2352
2353 static void view_dolly_to_vector_3d(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
2354 {
2355         RegionView3D *rv3d = ar->regiondata;
2356         madd_v3_v3v3fl(rv3d->ofs, orig_ofs, dvec, -(1.0f - dfac));
2357 }
2358
2359 static void viewdolly_apply(ViewOpsData *vod, const int xy[2], const short zoom_invert)
2360 {
2361         float zfac = 1.0;
2362
2363         {
2364                 float len1, len2;
2365
2366                 if (U.uiflag & USER_ZOOM_HORIZ) {
2367                         len1 = (vod->ar->winrct.xmax - xy[0]) + 5;
2368                         len2 = (vod->ar->winrct.xmax - vod->init.event_xy[0]) + 5;
2369                 }
2370                 else {
2371                         len1 = (vod->ar->winrct.ymax - xy[1]) + 5;
2372                         len2 = (vod->ar->winrct.ymax - vod->init.event_xy[1]) + 5;
2373                 }
2374                 if (zoom_invert) {
2375                         SWAP(float, len1, len2);
2376                 }
2377
2378                 zfac =  1.0f + ((len1 - len2) * 0.01f * vod->rv3d->dist);
2379         }
2380
2381         if (zfac != 1.0f) {
2382                 view_dolly_to_vector_3d(vod->ar, vod->init.ofs, vod->init.mousevec, zfac);
2383         }
2384
2385         if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
2386                 view3d_boxview_sync(vod->sa, vod->ar);
2387         }
2388
2389         ED_view3d_camera_lock_sync(vod->depsgraph, vod->v3d, vod->rv3d);
2390
2391         ED_region_tag_redraw(vod->ar);
2392 }
2393
2394
2395 static int viewdolly_modal(bContext *C, wmOperator *op, const wmEvent *event)
2396 {
2397         ViewOpsData *vod = op->customdata;
2398         short event_code = VIEW_PASS;
2399         bool use_autokey = false;
2400         int ret = OPERATOR_RUNNING_MODAL;
2401
2402         /* execute the events */
2403         if (event->type == MOUSEMOVE) {
2404                 event_code = VIEW_APPLY;
2405         }
2406         else if (event->type == EVT_MODAL_MAP) {
2407                 switch (event->val) {
2408                         case VIEW_MODAL_CONFIRM:
2409                                 event_code = VIEW_CONFIRM;
2410                                 break;
2411                         case VIEWROT_MODAL_SWITCH_MOVE:
2412                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2413                                 event_code = VIEW_CONFIRM;
2414                                 break;
2415                         case VIEWROT_MODAL_SWITCH_ROTATE:
2416                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2417                                 event_code = VIEW_CONFIRM;
2418                                 break;
2419                 }
2420         }
2421         else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
2422                 event_code = VIEW_CONFIRM;
2423         }
2424
2425         if (event_code == VIEW_APPLY) {
2426                 viewdolly_apply(vod, &event->x, (U.uiflag & USER_ZOOM_INVERT) != 0);
2427                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2428                         use_autokey = true;
2429                 }
2430         }
2431         else if (event_code == VIEW_CONFIRM) {
2432                 ED_view3d_depth_tag_update(vod->rv3d);
2433                 use_autokey = true;
2434                 ret = OPERATOR_FINISHED;
2435         }
2436
2437         if (use_autokey) {
2438                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2439         }
2440
2441         if (ret & OPERATOR_FINISHED) {
2442                 viewops_data_free(C, op);
2443         }
2444
2445         return ret;
2446 }
2447
2448 static int viewdolly_exec(bContext *C, wmOperator *op)
2449 {
2450         View3D *v3d;
2451         RegionView3D *rv3d;
2452         ScrArea *sa;
2453         ARegion *ar;
2454         float mousevec[3];
2455
2456         const int delta = RNA_int_get(op->ptr, "delta");
2457
2458         if (op->customdata) {
2459                 ViewOpsData *vod = op->customdata;
2460
2461                 sa = vod->sa;
2462                 ar = vod->ar;
2463                 copy_v3_v3(mousevec, vod->init.mousevec);
2464         }
2465         else {
2466                 sa = CTX_wm_area(C);
2467                 ar = CTX_wm_region(C);
2468                 negate_v3_v3(mousevec, ((RegionView3D *)ar->regiondata)->viewinv[2]);
2469                 normalize_v3(mousevec);
2470         }
2471
2472         v3d = sa->spacedata.first;
2473         rv3d = ar->regiondata;
2474
2475         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
2476
2477         /* overwrite the mouse vector with the view direction (zoom into the center) */
2478         if ((use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) == 0) {
2479                 normalize_v3_v3(mousevec, rv3d->viewinv[2]);
2480         }
2481
2482         view_dolly_to_vector_3d(ar, rv3d->ofs, mousevec, delta < 0 ? 0.2f : 1.8f);
2483
2484         if (rv3d->viewlock & RV3D_BOXVIEW) {
2485                 view3d_boxview_sync(sa, ar);
2486         }
2487
2488         ED_view3d_depth_tag_update(rv3d);
2489
2490         ED_view3d_camera_lock_sync(CTX_data_depsgraph(C), v3d, rv3d);
2491
2492         ED_region_tag_redraw(ar);
2493
2494         viewops_data_free(C, op);
2495
2496         return OPERATOR_FINISHED;
2497 }
2498
2499 /* copied from viewzoom_invoke(), changes here may apply there */
2500 static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2501 {
2502         ViewOpsData *vod;
2503
2504         if (viewdolly_offset_lock_check(C, op))
2505                 return OPERATOR_CANCELLED;
2506
2507         /* makes op->customdata */
2508         viewops_data_alloc(C, op);
2509         vod = op->customdata;
2510
2511         /* poll should check but in some cases fails, see poll func for details */
2512         if (vod->rv3d->viewlock & RV3D_LOCKED) {
2513                 viewops_data_free(C, op);
2514                 return OPERATOR_PASS_THROUGH;
2515         }
2516
2517         ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
2518
2519         /* needs to run before 'viewops_data_create' so the backup 'rv3d->ofs' is correct */
2520         /* switch from camera view when: */
2521         if (vod->rv3d->persp != RV3D_PERSP) {
2522                 if (vod->rv3d->persp == RV3D_CAMOB) {
2523                         /* ignore rv3d->lpersp because dolly only makes sense in perspective mode */
2524                         const Depsgraph *depsgraph = CTX_data_depsgraph(C);
2525                         ED_view3d_persp_switch_from_camera(depsgraph, vod->v3d, vod->rv3d, RV3D_PERSP);
2526                 }
2527                 else {
2528                         vod->rv3d->persp = RV3D_PERSP;
2529                 }
2530                 ED_region_tag_redraw(vod->ar);
2531         }
2532
2533         const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
2534
2535         viewops_data_create(
2536                 C, op, event,
2537                 viewops_flag_from_prefs() |
2538                 (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
2539
2540
2541         /* if one or the other zoom position aren't set, set from event */
2542         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2543                 RNA_int_set(op->ptr, "mx", event->x);
2544                 RNA_int_set(op->ptr, "my", event->y);
2545         }
2546
2547         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2548                 viewdolly_exec(C, op);
2549         }
2550         else {
2551                 /* overwrite the mouse vector with the view direction (zoom into the center) */
2552                 if ((use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) == 0) {
2553                         negate_v3_v3(vod->init.mousevec, vod->rv3d->viewinv[2]);
2554                         normalize_v3(vod->init.mousevec);
2555                 }
2556
2557                 if (event->type == MOUSEZOOM) {
2558                         /* Bypass Zoom invert flag for track pads (pass false always) */
2559
2560                         if (U.uiflag & USER_ZOOM_HORIZ) {
2561                                 vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
2562                         }
2563                         else {
2564                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2565                                 vod->init.event_xy[1] = vod->prev.event_xy[1] = vod->init.event_xy[1] + event->x - event->prevx;
2566                         }
2567                         viewdolly_apply(vod, &event->prevx, (U.uiflag & USER_ZOOM_INVERT) == 0);
2568                         ED_view3d_depth_tag_update(vod->rv3d);
2569
2570                         viewops_data_free(C, op);
2571                         return OPERATOR_FINISHED;
2572                 }
2573                 else {
2574                         /* add temp handler */
2575                         WM_event_add_modal_handler(C, op);
2576
2577                         return OPERATOR_RUNNING_MODAL;
2578                 }
2579         }
2580         return OPERATOR_FINISHED;
2581 }
2582
2583 static void viewdolly_cancel(bContext *C, wmOperator *op)
2584 {
2585         viewops_data_free(C, op);
2586 }
2587
2588 void VIEW3D_OT_dolly(wmOperatorType *ot)
2589 {
2590         /* identifiers */
2591         ot->name = "Dolly View";
2592         ot->description = "Dolly in/out in the view";
2593         ot->idname = "VIEW3D_OT_dolly";
2594
2595         /* api callbacks */
2596         ot->invoke = viewdolly_invoke;
2597         ot->exec = viewdolly_exec;
2598         ot->modal = viewdolly_modal;
2599         ot->poll = ED_operator_region_view3d_active;
2600         ot->cancel = viewdolly_cancel;
2601
2602         /* flags */
2603         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2604
2605         /* properties */
2606         view3d_operator_properties_common(
2607                 ot, V3D_OP_PROP_DELTA | V3D_OP_PROP_MOUSE_CO | V3D_OP_PROP_USE_MOUSE_INIT);
2608 }
2609
2610 /** \} */
2611
2612 /* -------------------------------------------------------------------- */
2613 /** \name View All Operator
2614  *
2615  * Move & Zoom the view to fit all of it's contents.
2616  * \{ */
2617
2618 static void view3d_from_minmax(
2619         bContext *C, View3D *v3d, ARegion *ar,
2620         const float min[3], const float max[3],
2621         bool ok_dist, const int smooth_viewtx)
2622 {
2623         RegionView3D *rv3d = ar->regiondata;
2624         float afm[3];
2625         float size;
2626
2627         ED_view3d_smooth_view_force_finish(C, v3d, ar);
2628
2629         /* SMOOTHVIEW */
2630         float new_ofs[3];
2631         float new_dist;
2632
2633         sub_v3_v3v3(afm, max, min);
2634         size = max_fff(afm[0], afm[1], afm[2]);
2635
2636         if (ok_dist) {
2637                 char persp;
2638
2639                 if (rv3d->is_persp) {
2640                         if (rv3d->persp == RV3D_CAMOB && ED_view3d_camera_lock_check(v3d, rv3d)) {
2641                                 persp = RV3D_CAMOB;
2642                         }
2643                         else {
2644                                 persp = RV3D_PERSP;
2645                         }
2646                 }
2647                 else { /* ortho */
2648                         if (size < 0.0001f) {
2649                                 /* bounding box was a single point so do not zoom */
2650                                 ok_dist = false;
2651                         }
2652                         else {
2653                                 /* adjust zoom so it looks nicer */
2654                                 persp = RV3D_ORTHO;
2655                         }
2656                 }
2657
2658                 if (ok_dist) {
2659                         new_dist = ED_view3d_radius_to_dist(v3d, ar, CTX_data_depsgraph(C), persp, true, (size / 2) * VIEW3D_MARGIN);
2660                         if (rv3d->is_persp) {
2661                                 /* don't zoom closer than the near clipping plane */
2662                                 new_dist = max_ff(new_dist, v3d->near * 1.5f);
2663                         }
2664                 }
2665         }
2666
2667         mid_v3_v3v3(new_ofs, min, max);
2668         negate_v3(new_ofs);
2669
2670         if (rv3d->persp == RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
2671                 rv3d->persp = RV3D_PERSP;
2672                 ED_view3d_smooth_view(
2673                         C, v3d, ar, smooth_viewtx,
2674                         &(const V3D_SmoothParams) {
2675                             .camera_old = v3d->camera, .ofs = new_ofs,
2676                             .dist = ok_dist ? &new_dist : NULL});
2677         }
2678         else {
2679                 ED_view3d_smooth_view(
2680                         C, v3d, ar, smooth_viewtx,
2681                         &(const V3D_SmoothParams) {.ofs = new_ofs, .dist = ok_dist ? &new_dist : NULL});
2682         }
2683
2684         /* smooth view does viewlock RV3D_BOXVIEW copy */
2685 }
2686
2687 /**
2688  * Same as #view3d_from_minmax but for all regions (except cameras).
2689  */
2690 static void view3d_from_minmax_multi(
2691         bContext *C, View3D *v3d,
2692         const float min[3], const float max[3],
2693         const bool ok_dist, const int smooth_viewtx)
2694 {
2695         ScrArea *sa = CTX_wm_area(C);
2696         ARegion *ar;
2697         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2698                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2699                         RegionView3D *rv3d = ar->regiondata;
2700                         /* when using all regions, don't jump out of camera view,
2701                          * but _do_ allow locked cameras to be moved */
2702                         if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d)) {
2703                                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
2704                         }
2705                 }
2706         }
2707 }
2708
2709 static int view3d_all_exec(bContext *C, wmOperator *op)
2710 {
2711         ARegion *ar = CTX_wm_region(C);
2712         View3D *v3d = CTX_wm_view3d(C);
2713         Scene *scene = CTX_data_scene(C);
2714         const Depsgraph *depsgraph = CTX_data_depsgraph(C);
2715         ViewLayer *view_layer_eval = DEG_get_evaluated_view_layer(depsgraph);
2716         Base *base_eval;
2717         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
2718         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
2719                                   /* any one of the regions may be locked */
2720                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
2721         const bool center = RNA_boolean_get(op->ptr, "center");
2722         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
2723
2724         float min[3], max[3];
2725         bool changed = false;
2726
2727         if (center) {
2728                 /* in 2.4x this also move the cursor to (0, 0, 0) (with shift+c). */
2729                 View3DCursor *cursor = ED_view3d_cursor3d_get(scene, v3d);
2730                 zero_v3(min);
2731                 zero_v3(max);
2732                 zero_v3(cursor->location);
2733                 unit_qt(cursor->rotation);
2734         }
2735         else {
2736                 INIT_MINMAX(min, max);
2737         }
2738
2739         for (base_eval = view_layer_eval->object_bases.first; base_eval; base_eval = base_eval->next) {
2740                 if (BASE_VISIBLE(base_eval)) {
2741                         changed = true;
2742
2743                         Object *ob = DEG_get_original_object(base_eval->object);
2744                         if (skip_camera && ob == v3d->camera) {
2745                                 continue;
2746                         }
2747
2748                         BKE_object_minmax(base_eval->object, min, max, false);
2749                 }
2750         }
2751         if (!changed) {
2752                 ED_region_tag_redraw(ar);
2753                 /* TODO - should this be cancel?
2754                  * I think no, because we always move the cursor, with or without
2755                  * object, but in this case there is no change in the scene,
2756                  * only the cursor so I choice a ED_region_tag like
2757                  * view3d_smooth_view do for the center_cursor.
2758                  * See bug #22640
2759                  */
2760                 return OPERATOR_FINISHED;
2761         }
2762
2763         if (use_all_regions) {
2764                 view3d_from_minmax_multi(C, v3d, min, max, true, smooth_viewtx);
2765         }
2766         else {
2767                 view3d_from_minmax(C, v3d, ar, min, max, true, smooth_viewtx);
2768         }
2769
2770         if (center) {
2771                 DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE);
2772         }
2773
2774         return OPERATOR_FINISHED;
2775 }
2776
2777
2778 void VIEW3D_OT_view_all(wmOperatorType *ot)
2779 {
2780         /* identifiers */
2781         ot->name = "View All";
2782         ot->description = "View all objects in scene";
2783         ot->idname = "VIEW3D_OT_view_all";
2784
2785         /* api callbacks */
2786         ot->exec = view3d_all_exec;
2787         ot->poll = ED_operator_region_view3d_active;
2788
2789         /* flags */
2790         ot->flag = 0;
2791
2792         /* properties */
2793         view3d_operator_properties_common(ot, V3D_OP_PROP_USE_ALL_REGIONS);
2794         RNA_def_boolean(ot->srna, "center", 0, "Center", "");
2795 }
2796
2797 /** \} */
2798
2799 /* -------------------------------------------------------------------- */
2800 /** \name View Selected Operator
2801  *
2802  * Move & Zoom the view to fit selected contents.
2803  * \{ */
2804
2805 /* like a localview without local!, was centerview() in 2.4x */
2806 static int viewselected_exec(bContext *C, wmOperator *op)
2807 {
2808         ARegion *ar = CTX_wm_region(C);
2809         View3D *v3d = CTX_wm_view3d(C);
2810         Scene *scene = CTX_data_scene(C);
2811         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2812         ViewLayer *view_layer_eval = DEG_get_evaluated_view_layer(depsgraph);
2813         bGPdata *gpd = CTX_data_gpencil_data(C);
2814         const bool is_gp_edit = ((gpd) && (gpd->flag & GP_DATA_STROKE_EDITMODE));
2815         const bool is_face_map = ((is_gp_edit == false) && ar->manipulator_map &&
2816                                   WM_manipulatormap_is_any_selected(ar->manipulator_map));
2817         Object *ob_eval = OBACT(view_layer_eval);
2818         Object *obedit = CTX_data_edit_object(C);
2819         float min[3], max[3];
2820         bool ok = false, ok_dist = true;
2821         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
2822         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
2823                                   /* any one of the regions may be locked */
2824                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
2825         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
2826
2827         INIT_MINMAX(min, max);
2828         if (is_gp_edit || is_face_map) {
2829                 ob_eval = NULL;
2830         }
2831
2832         if (ob_eval && (ob_eval->mode & OB_MODE_WEIGHT_PAINT)) {
2833                 /* hard-coded exception, we look for the one selected armature */
2834                 /* this is weak code this way, we should make a generic active/selection callback interface once... */
2835                 Base *base_eval;
2836                 for (base_eval = view_layer_eval->object_bases.first; base_eval; base_eval = base_eval->next) {
2837                         if (TESTBASELIB(base_eval)) {
2838                                 if (base_eval->object->type == OB_ARMATURE)
2839                                         if (base_eval->object->mode & OB_MODE_POSE)
2840                                                 break;
2841                         }
2842                 }
2843                 if (base_eval)
2844                         ob_eval = base_eval->object;
2845         }
2846
2847         if (is_gp_edit) {
2848                 /* TODO(sergey): Check on this after gpencil merge. */
2849                 CTX_DATA_BEGIN(C, bGPDstroke *, gps, editable_gpencil_strokes)
2850                 {
2851                         /* we're only interested in selected points here... */
2852                         if ((gps->flag & GP_STROKE_SELECT) && (gps->flag & GP_STROKE_3DSPACE)) {
2853                                 if (ED_gpencil_stroke_minmax(gps, true, min, max)) {
2854                                         ok = true;
2855                                 }
2856                         }
2857                 }
2858                 CTX_DATA_END;
2859         }
2860         else if (is_face_map) {
2861                 ok = WM_manipulatormap_minmax(ar->manipulator_map, true, true, min, max);
2862         }
2863         else if (obedit) {
2864                 /* only selected */
2865                 FOREACH_OBJECT_IN_MODE_BEGIN (view_layer_eval, obedit->mode, ob_eval_iter) {
2866                         ok |= ED_view3d_minmax_verts(ob_eval_iter, min, max);
2867                 }
2868                 FOREACH_OBJECT_IN_MODE_END;
2869         }
2870         else if (ob_eval && (ob_eval->mode & OB_MODE_POSE)) {
2871                 FOREACH_OBJECT_IN_MODE_BEGIN (view_layer_eval, ob_eval->mode, ob_eval_iter) {
2872                         ok |= BKE_pose_minmax(ob_eval_iter, min, max, true, true);
2873                 }
2874                 FOREACH_OBJECT_IN_MODE_END;
2875         }
2876         else if (BKE_paint_select_face_test(ob_eval)) {
2877                 ok = paintface_minmax(ob_eval, min, max);
2878         }
2879         else if (ob_eval && (ob_eval->mode & OB_MODE_PARTICLE_EDIT)) {
2880                 ok = PE_minmax(scene, view_layer_eval, min, max);
2881         }
2882         else if (ob_eval &&
2883                  (ob_eval->mode & (OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)))
2884         {
2885                 BKE_paint_stroke_get_average(scene, ob_eval, min);
2886                 copy_v3_v3(max, min);
2887                 ok = true;
2888                 ok_dist = 0; /* don't zoom */
2889         }
2890         else {
2891                 Base *base_eval;
2892                 for (base_eval = FIRSTBASE(view_layer_eval); base_eval; base_eval = base_eval->next) {
2893                         if (TESTBASE(base_eval)) {
2894
2895                                 if (skip_camera && base_eval->object == v3d->camera) {
2896                                         continue;
2897                                 }
2898
2899                                 /* account for duplis */
2900                                 if (BKE_object_minmax_dupli(depsgraph, scene, base_eval->object, min, max, false) == 0)
2901                                         BKE_object_minmax(base_eval->object, min, max, false);  /* use if duplis not found */
2902
2903                                 ok = 1;
2904                         }
2905                 }
2906         }
2907
2908         if (ok == 0) {
2909                 return OPERATOR_FINISHED;
2910         }
2911
2912         if (use_all_regions) {
2913                 view3d_from_minmax_multi(C, v3d, min, max, ok_dist, smooth_viewtx);
2914         }
2915         else {
2916                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
2917         }
2918
2919         return OPERATOR_FINISHED;
2920 }
2921
2922 void VIEW3D_OT_view_selected(wmOperatorType *ot)
2923 {
2924         /* identifiers */
2925         ot->name = "View Selected";
2926         ot->description = "Move the view to the selection center";
2927         ot->idname = "VIEW3D_OT_view_selected";
2928
2929         /* api callbacks */
2930         ot->exec = viewselected_exec;
2931         ot->poll = ED_operator_region_view3d_active;
2932
2933         /* flags */
2934         ot->flag = 0;
2935
2936         /* properties */
2937         view3d_operator_properties_common(ot, V3D_OP_PROP_USE_ALL_REGIONS);
2938 }
2939
2940 /** \} */
2941
2942 /* -------------------------------------------------------------------- */
2943 /** \name View Lock Clear Operator
2944  * \{ */
2945
2946 static int view_lock_clear_exec(bContext *C, wmOperator *UNUSED(op))
2947 {
2948         View3D *v3d = CTX_wm_view3d(C);
2949
2950         if (v3d) {
2951                 ED_view3d_lock_clear(v3d);
2952
2953                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
2954
2955                 return OPERATOR_FINISHED;
2956         }
2957         else {
2958                 return OPERATOR_CANCELLED;
2959         }
2960 }
2961
2962 void VIEW3D_OT_view_lock_clear(wmOperatorType *ot)
2963 {
2964
2965         /* identifiers */
2966         ot->name = "View Lock Clear";
2967         ot->description = "Clear all view locking";
2968         ot->idname = "VIEW3D_OT_view_lock_clear";
2969
2970         /* api callbacks */
2971         ot->exec = view_lock_clear_exec;
2972         ot->poll = ED_operator_region_view3d_active;
2973
2974         /* flags */
2975         ot->flag = 0;
2976 }
2977
2978 /** \} */
2979
2980 /* -------------------------------------------------------------------- */
2981 /** \name View Lock to Active Operator
2982  * \{ */
2983
2984 static int view_lock_to_active_exec(bContext *C, wmOperator *UNUSED(op))
2985 {
2986         View3D *v3d = CTX_wm_view3d(C);
2987         Object *obact = CTX_data_active_object(C);
2988
2989         if (v3d) {
2990                 ED_view3d_lock_clear(v3d);
2991
2992                 v3d->ob_centre = obact; /* can be NULL */
2993
2994                 if (obact && obact->type == OB_ARMATURE) {
2995                         if (obact->mode & OB_MODE_POSE) {
2996                                 Object *obact_eval = DEG_get_evaluated_object(CTX_data_depsgraph(C), obact);
2997                                 bPoseChannel *pcham_act = BKE_pose_channel_active(obact_eval);
2998                                 if (pcham_act) {
2999                                         BLI_strncpy(v3d->ob_centre_bone, pcham_act->name, sizeof(v3d->ob_centre_bone));
3000                                 }
3001                         }
3002                         else {
3003                                 EditBone *ebone_act = ((bArmature *)obact->data)->act_edbone;
3004                                 if (ebone_act) {
3005                                         BLI_strncpy(v3d->ob_centre_bone, ebone_act->name, sizeof(v3d->ob_centre_bone));
3006                                 }
3007                         }
3008                 }
3009
3010                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3011
3012                 return OPERATOR_FINISHED;
3013         }
3014         else {
3015                 return OPERATOR_CANCELLED;
3016         }
3017 }
3018
3019 void VIEW3D_OT_view_lock_to_active(wmOperatorType *ot)
3020 {
3021
3022         /* identifiers */
3023         ot->name = "View Lock to Active";
3024         ot->description = "Lock the view to the active object/bone";
3025         ot->idname = "VIEW3D_OT_view_lock_to_active";
3026
3027         /* api callbacks */
3028         ot->exec = view_lock_to_active_exec;
3029         ot->poll = ED_operator_region_view3d_active;
3030
3031         /* flags */
3032         ot->flag = 0;
3033 }
3034
3035 /** \} */
3036
3037 /* -------------------------------------------------------------------- */
3038 /** \name View Center Cursor Operator
3039  * \{ */
3040
3041 static int viewcenter_cursor_exec(bContext *C, wmOperator *op)
3042 {
3043         View3D *v3d = CTX_wm_view3d(C);
3044         RegionView3D *rv3d = CTX_wm_region_view3d(C);
3045         Scene *scene = CTX_data_scene(C);
3046
3047         if (rv3d) {
3048                 ARegion *ar = CTX_wm_region(C);
3049                 const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
3050
3051                 ED_view3d_smooth_view_force_finish(C, v3d, ar);
3052
3053                 /* non camera center */
3054                 float new_ofs[3];
3055                 negate_v3_v3(new_ofs, ED_view3d_cursor3d_get(scene, v3d)->location);
3056                 ED_view3d_smooth_view(
3057                         C, v3d, ar, smooth_viewtx,
3058                         &(const V3D_SmoothParams) {.ofs = new_ofs});
3059
3060                 /* smooth view does viewlock RV3D_BOXVIEW copy */
3061         }
3062
3063         return OPERATOR_FINISHED;
3064 }
3065
3066 void VIEW3D_OT_view_center_cursor(wmOperatorType *ot)
3067 {
3068         /* identifiers */
3069         ot->name = "Center View to Cursor";
3070         ot->description = "Center the view so that the cursor is in the middle of the view";
3071         ot->idname = "VIEW3D_OT_view_center_cursor";
3072
3073         /* api callbacks */
3074         ot->exec = viewcenter_cursor_exec;
3075         ot->poll = ED_operator_view3d_active;
3076
3077         /* flags */
3078         ot->flag = 0;
3079 }
3080
3081 /** \} */
3082
3083 /* -------------------------------------------------------------------- */
3084 /** \name View Center Pick Operator
3085  * \{ */
3086
3087 static int viewcenter_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
3088 {
3089         View3D *v3d = CTX_wm_view3d(C);
3090         RegionView3D *rv3d = CTX_wm_region_view3d(C);
3091         ARegion *ar = CTX_wm_region(C);
3092
3093         if (rv3d) {
3094                 struct Depsgraph *depsgraph = CTX_data_depsgraph(C);
3095                 float new_ofs[3];
3096                 const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
3097
3098                 ED_view3d_smooth_view_force_finish(C, v3d, ar);
3099
3100                 view3d_operator_needs_opengl(C);
3101
3102                 if (ED_view3d_autodist(depsgraph, ar, v3d, event->mval, new_ofs, false, NULL)) {
3103                         /* pass */
3104                 }
3105                 else {
3106                         /* fallback to simple pan */
3107                         negate_v3_v3(new_ofs, rv3d->ofs);
3108                         ED_view3d_win_to_3d_int(v3d, ar, new_ofs, event->mval, new_ofs);
3109                 }
3110                 negate_v3(new_ofs);
3111                 ED_view3d_smooth_view(
3112                         C, v3d, ar, smooth_viewtx,
3113                         &(const V3D_SmoothParams) {.ofs = new_ofs});
3114         }
3115
3116         return OPERATOR_FINISHED;
3117 }
3118
3119 void VIEW3D_OT_view_center_pick(wmOperatorType *ot)
3120 {
3121         /* identifiers */
3122         ot->name = "Center View to Mouse";
3123         ot->description = "Center the view to the Z-depth position under the mouse cursor";
3124         ot->idname = "VIEW3D_OT_view_center_pick";
3125
3126         /* api callbacks */
3127         ot->invoke = viewcenter_pick_invoke;
3128         ot->poll = ED_operator_view3d_active;
3129
3130         /* flags */
3131         ot->flag = 0;
3132 }
3133
3134 /** \} */
3135
3136 /* -------------------------------------------------------------------- */
3137 /** \name View Camera Center Operator
3138  * \{ */
3139
3140 static int view3d_center_camera_exec(bContext *C, wmOperator *UNUSED(op)) /* was view3d_home() in 2.4x */
3141 {
3142         Depsgraph *depsgraph = CTX_data_depsgraph(C);
3143         Scene *scene = CTX_data_scene(C);
3144         float xfac, yfac;
3145         float size[2];
3146
3147         View3D *v3d;
3148         ARegion *ar;
3149         RegionView3D *rv3d;
3150
3151         /* no NULL check is needed, poll checks */
3152         ED_view3d_context_user_region(C, &v3d, &ar);
3153         rv3d = ar->regiondata;
3154
3155         rv3d->camdx = rv3d->camdy = 0.0f;
3156
3157         ED_view3d_calc_camera_border_size(scene, depsgraph, ar, v3d, rv3d, size);
3158
3159         /* 4px is just a little room from the edge of the area */
3160         xfac = (float)ar->winx / (float)(size[0] + 4);
3161         yfac = (float)ar->winy / (float)(size[1] + 4);
3162
3163         rv3d->camzoom = BKE_screen_view3d_zoom_from_fac(min_ff(xfac, yfac));
3164         CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
3165
3166         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3167
3168         return OPERATOR_FINISHED;
3169 }
3170
3171 void VIEW3D_OT_view_center_camera(wmOperatorType *ot)
3172 {
3173         /* identifiers */
3174         ot->name = "View Camera Center";
3175         ot->description = "Center the camera view";
3176         ot->idname = "VIEW3D_OT_view_center_camera";
3177
3178         /* api callbacks */
3179         ot->exec = view3d_center_camera_exec;
3180         ot->poll = view3d_camera_user_poll;
3181
3182         /* flags */
3183         ot->flag = 0;
3184 }
3185
3186 /** \} */
3187
3188 /* -------------------------------------------------------------------- */
3189 /** \name View Lock Center Operator
3190  * \{ */
3191
3192 static int view3d_center_lock_exec(bContext *C, wmOperator *UNUSED(op)) /* was view3d_home() in 2.4x */
3193 {
3194         RegionView3D *rv3d = CTX_wm_region_view3d(C);
3195
3196         zero_v2(rv3d->ofs_lock);
3197
3198         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
3199
3200         return OPERATOR_FINISHED;
3201 }
3202
3203 void VIEW3D_OT_view_center_lock(wmOperatorType *ot)
3204 {
3205         /* identifiers */
3206         ot->name = "View Lock Center";
3207         ot->description = "Center the view lock offset";
3208         ot->idname = "VIEW3D_OT_view_center_lock";
3209
3210         /* api callbacks */
3211         ot->exec = view3d_center_lock_exec;
3212         ot->poll = view3d_lock_poll;
3213
3214         /* flags */
3215         ot->flag = 0;
3216 }
3217
3218 /** \} */
3219
3220 /* -------------------------------------------------------------------- */
3221 /** \name Set Render Border Operator
3222  * \{ */
3223
3224 static int render_border_exec(bContext *C, wmOperator *op)
3225 {
3226         Depsgraph *depsgraph = CTX_data_depsgraph(C);
3227         View3D *v3d = CTX_wm_view3d(C);
3228         ARegion *ar = CTX_wm_region(C);
3229         RegionView3D *rv3d = ED_view3d_context_rv3d(C);
3230
3231         Scene *scene = CTX_data_scene(C);
3232
3233         rcti rect;
3234         rctf vb, border;
3235
3236         const bool camera_only = RNA_boolean_get(op->ptr, "camera_only");
3237
3238         if (camera_only && rv3d->persp != RV3D_CAMOB)
3239    &nbs