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