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