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