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