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