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