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