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