View-Selected: use custom bones boundbox
[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.1)
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 phi, si, q1[4], dvec[3], newvec[3];
1032
1033                 calctrackballvec(&vod->ar->winrct, x, y, newvec);
1034
1035                 sub_v3_v3v3(dvec, newvec, vod->trackvec);
1036
1037                 si = len_v3(dvec);
1038                 si /= (float)(2.0 * TRACKBALLSIZE);
1039
1040                 cross_v3_v3v3(q1 + 1, vod->trackvec, newvec);
1041                 normalize_v3(q1 + 1);
1042
1043                 /* Allow for rotation beyond the interval [-pi, pi] */
1044                 while (si > 1.0f)
1045                         si -= 2.0f;
1046
1047                 /* This relation is used instead of
1048                  * - phi = asin(si) so that the angle
1049                  * - of rotation is linearly proportional
1050                  * - to the distance that the mouse is
1051                  * - dragged. */
1052                 phi = si * (float)M_PI_2;
1053
1054                 q1[0] = cosf(phi);
1055                 mul_v3_fl(q1 + 1, sinf(phi));
1056                 mul_qt_qtqt(vod->viewquat, q1, vod->oldquat);
1057
1058                 viewrotate_apply_dyn_ofs(vod, vod->viewquat);
1059         }
1060         else {
1061                 /* New turntable view code by John Aughey */
1062                 float quat_local_x[4], quat_global_z[4];
1063                 float m[3][3];
1064                 float m_inv[3][3];
1065                 const float zvec_global[3] = {0.0f, 0.0f, 1.0f};
1066                 float xaxis[3];
1067
1068                 /* Sensitivity will control how fast the viewport rotates.  0.007 was
1069                  * obtained experimentally by looking at viewport rotation sensitivities
1070                  * on other modeling programs. */
1071                 /* Perhaps this should be a configurable user parameter. */
1072                 const float sensitivity = 0.007f;
1073
1074                 /* Get the 3x3 matrix and its inverse from the quaternion */
1075                 quat_to_mat3(m, vod->viewquat);
1076                 invert_m3_m3(m_inv, m);
1077
1078                 /* avoid gimble lock */
1079 #if 1
1080                 if (len_squared_v3v3(zvec_global, m_inv[2]) > 0.001f) {
1081                         float fac;
1082                         cross_v3_v3v3(xaxis, zvec_global, m_inv[2]);
1083                         if (dot_v3v3(xaxis, m_inv[0]) < 0) {
1084                                 negate_v3(xaxis);
1085                         }
1086                         fac = angle_normalized_v3v3(zvec_global, m_inv[2]) / (float)M_PI;
1087                         fac = fabsf(fac - 0.5f) * 2;
1088                         fac = fac * fac;
1089                         interp_v3_v3v3(xaxis, xaxis, m_inv[0], fac);
1090                 }
1091                 else {
1092                         copy_v3_v3(xaxis, m_inv[0]);
1093                 }
1094 #else
1095                 copy_v3_v3(xaxis, m_inv[0]);
1096 #endif
1097
1098                 /* Determine the direction of the x vector (for rotating up and down) */
1099                 /* This can likely be computed directly from the quaternion. */
1100
1101                 /* Perform the up/down rotation */
1102                 axis_angle_to_quat(quat_local_x, xaxis, sensitivity * -(y - vod->oldy));
1103                 mul_qt_qtqt(quat_local_x, vod->viewquat, quat_local_x);
1104
1105                 /* Perform the orbital rotation */
1106                 axis_angle_normalized_to_quat(quat_global_z, zvec_global, sensitivity * vod->reverse * (x - vod->oldx));
1107                 mul_qt_qtqt(vod->viewquat, quat_local_x, quat_global_z);
1108
1109                 viewrotate_apply_dyn_ofs(vod, vod->viewquat);
1110         }
1111
1112         /* avoid precision loss over time */
1113         normalize_qt(vod->viewquat);
1114
1115         /* use a working copy so view rotation locking doesnt overwrite the locked
1116          * rotation back into the view we calculate with */
1117         copy_qt_qt(rv3d->viewquat, vod->viewquat);
1118
1119         /* check for view snap,
1120          * note: don't apply snap to vod->viewquat so the view wont jam up */
1121         if (vod->axis_snap) {
1122                 viewrotate_apply_snap(vod);
1123         }
1124         vod->oldx = x;
1125         vod->oldy = y;
1126
1127         ED_view3d_camera_lock_sync(vod->v3d, rv3d);
1128
1129         ED_region_tag_redraw(vod->ar);
1130 }
1131
1132 static int viewrotate_modal(bContext *C, wmOperator *op, const wmEvent *event)
1133 {
1134         ViewOpsData *vod = op->customdata;
1135         short event_code = VIEW_PASS;
1136         bool use_autokey = false;
1137         int ret = OPERATOR_RUNNING_MODAL;
1138
1139         /* execute the events */
1140         if (event->type == MOUSEMOVE) {
1141                 event_code = VIEW_APPLY;
1142         }
1143         else if (event->type == EVT_MODAL_MAP) {
1144                 switch (event->val) {
1145                         case VIEW_MODAL_CONFIRM:
1146                                 event_code = VIEW_CONFIRM;
1147                                 break;
1148                         case VIEWROT_MODAL_AXIS_SNAP_ENABLE:
1149                                 vod->axis_snap = true;
1150                                 event_code = VIEW_APPLY;
1151                                 break;
1152                         case VIEWROT_MODAL_AXIS_SNAP_DISABLE:
1153                                 vod->axis_snap = false;
1154                                 event_code = VIEW_APPLY;
1155                                 break;
1156                         case VIEWROT_MODAL_SWITCH_ZOOM:
1157                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1158                                 event_code = VIEW_CONFIRM;
1159                                 break;
1160                         case VIEWROT_MODAL_SWITCH_MOVE:
1161                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
1162                                 event_code = VIEW_CONFIRM;
1163                                 break;
1164                 }
1165         }
1166         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
1167                 event_code = VIEW_CONFIRM;
1168         }
1169
1170         if (event_code == VIEW_APPLY) {
1171                 viewrotate_apply(vod, event->x, event->y);
1172                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
1173                         use_autokey = true;
1174                 }
1175         }
1176         else if (event_code == VIEW_CONFIRM) {
1177                 ED_view3d_depth_tag_update(vod->rv3d);
1178                 use_autokey = true;
1179                 ret = OPERATOR_FINISHED;
1180         }
1181
1182         if (use_autokey) {
1183                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, true, true);
1184         }
1185
1186         if (ret & OPERATOR_FINISHED) {
1187                 viewops_data_free(C, op);
1188         }
1189
1190         return ret;
1191 }
1192
1193 /**
1194  * Action to take when rotating the view,
1195  * handle auto-persp and logic for switching out of views.
1196  *
1197  * shared with NDOF.
1198  */
1199 static bool view3d_ensure_persp(struct View3D *v3d, ARegion *ar)
1200 {
1201         RegionView3D *rv3d = ar->regiondata;
1202         const bool autopersp = (U.uiflag & USER_AUTOPERSP) != 0;
1203
1204         BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
1205
1206         if (ED_view3d_camera_lock_check(v3d, rv3d))
1207                 return false;
1208
1209         if (rv3d->persp != RV3D_PERSP) {
1210                 if (rv3d->persp == RV3D_CAMOB) {
1211                         /* If autopersp and previous view was an axis one, switch back to PERSP mode, else reuse previous mode. */
1212                         char persp = (autopersp && RV3D_VIEW_IS_AXIS(rv3d->lview)) ? RV3D_PERSP : rv3d->lpersp;
1213                         view3d_persp_switch_from_camera(v3d, rv3d, persp);
1214                 }
1215                 else if (autopersp && RV3D_VIEW_IS_AXIS(rv3d->view)) {
1216                         rv3d->persp = RV3D_PERSP;
1217                 }
1218                 return true;
1219         }
1220
1221         return false;
1222 }
1223
1224 static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1225 {
1226         ViewOpsData *vod;
1227
1228         /* makes op->customdata */
1229         viewops_data_alloc(C, op);
1230         viewops_data_create(C, op, event);
1231         vod = op->customdata;
1232
1233         /* poll should check but in some cases fails, see poll func for details */
1234         if (vod->rv3d->viewlock & RV3D_LOCKED) {
1235                 viewops_data_free(C, op);
1236                 return OPERATOR_PASS_THROUGH;
1237         }
1238
1239         /* switch from camera view when: */
1240         if (view3d_ensure_persp(vod->v3d, vod->ar)) {
1241                 /* If we're switching from camera view to the perspective one,
1242                  * need to tag viewport update, so camera vuew and borders
1243                  * are properly updated.
1244                  */
1245                 ED_region_tag_redraw(vod->ar);
1246         }
1247
1248         if (ELEM(event->type, MOUSEPAN, MOUSEROTATE)) {
1249                 /* Rotate direction we keep always same */
1250                 int x, y;
1251
1252                 if (event->type == MOUSEPAN) {
1253                         if (U.uiflag2 & USER_TRACKPAD_NATURAL) {
1254                                 x = 2 * event->x - event->prevx;
1255                                 y = 2 * event->y - event->prevy;
1256                         }
1257                         else {
1258                                 x = event->prevx;
1259                                 y = event->prevy;
1260                         }
1261                 }
1262                 else {
1263                         /* MOUSEROTATE performs orbital rotation, so y axis delta is set to 0 */
1264                         x = event->prevx;
1265                         y = event->y;
1266                 }
1267
1268                 viewrotate_apply(vod, x, y);
1269                 ED_view3d_depth_tag_update(vod->rv3d);
1270
1271                 viewops_data_free(C, op);
1272
1273                 return OPERATOR_FINISHED;
1274         }
1275         else {
1276                 /* add temp handler */
1277                 WM_event_add_modal_handler(C, op);
1278
1279                 return OPERATOR_RUNNING_MODAL;
1280         }
1281 }
1282
1283 /* test for unlocked camera view in quad view */
1284 static int view3d_camera_user_poll(bContext *C)
1285 {
1286         View3D *v3d;
1287         ARegion *ar;
1288
1289         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
1290                 RegionView3D *rv3d = ar->regiondata;
1291                 if (rv3d->persp == RV3D_CAMOB) {
1292                         return 1;
1293                 }
1294         }
1295
1296         return 0;
1297 }
1298
1299 static int view3d_lock_poll(bContext *C)
1300 {
1301         View3D *v3d = CTX_wm_view3d(C);
1302         if (v3d) {
1303                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1304                 if (rv3d) {
1305                         return ED_view3d_offset_lock_check(v3d, rv3d);
1306                 }
1307         }
1308         return false;
1309 }
1310
1311 static void viewrotate_cancel(bContext *C, wmOperator *op)
1312 {
1313         viewops_data_free(C, op);
1314 }
1315
1316 void VIEW3D_OT_rotate(wmOperatorType *ot)
1317 {
1318         /* identifiers */
1319         ot->name = "Rotate View";
1320         ot->description = "Rotate the view";
1321         ot->idname = "VIEW3D_OT_rotate";
1322
1323         /* api callbacks */
1324         ot->invoke = viewrotate_invoke;
1325         ot->modal = viewrotate_modal;
1326         ot->poll = ED_operator_region_view3d_active;
1327         ot->cancel = viewrotate_cancel;
1328
1329         /* flags */
1330         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
1331 }
1332
1333 /** \name NDOF Utility Functions
1334  * \{ */
1335
1336 #define NDOF_HAS_TRANSLATE ((!ED_view3d_offset_lock_check(v3d, rv3d)) && !is_zero_v3(ndof->tvec))
1337 #define NDOF_HAS_ROTATE    (((rv3d->viewlock & RV3D_LOCKED) == 0) && !is_zero_v3(ndof->rvec))
1338
1339 /**
1340  * \param depth_pt: A point to calculate the depth (in perspective mode)
1341  */
1342 static float view3d_ndof_pan_speed_calc_ex(RegionView3D *rv3d, const float depth_pt[3])
1343 {
1344         float speed = rv3d->pixsize * NDOF_PIXELS_PER_SECOND;
1345
1346         if (rv3d->is_persp) {
1347                 speed *= ED_view3d_calc_zfac(rv3d, depth_pt, NULL);
1348         }
1349
1350         return speed;
1351 }
1352
1353 static float view3d_ndof_pan_speed_calc_from_dist(RegionView3D *rv3d, const float dist)
1354 {
1355         float viewinv[4];
1356         float tvec[3];
1357
1358         BLI_assert(dist >= 0.0f);
1359
1360         copy_v3_fl3(tvec, 0.0f, 0.0f, dist);
1361         /* rv3d->viewinv isn't always valid */
1362 #if 0
1363         mul_mat3_m4_v3(rv3d->viewinv, tvec);
1364 #else
1365         invert_qt_qt(viewinv, rv3d->viewquat);
1366         mul_qt_v3(viewinv, tvec);
1367 #endif
1368
1369         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1370 }
1371
1372 static float view3d_ndof_pan_speed_calc(RegionView3D *rv3d)
1373 {
1374         float tvec[3];
1375         negate_v3_v3(tvec, rv3d->ofs);
1376
1377         return view3d_ndof_pan_speed_calc_ex(rv3d, tvec);
1378 }
1379
1380 /**
1381  * Zoom and pan in the same function since sometimes zoom is interpreted as dolly (pan forward).
1382  *
1383  * \param has_zoom zoom, otherwise dolly, often `!rv3d->is_persp` since it doesnt make sense to dolly in ortho.
1384  */
1385 static void view3d_ndof_pan_zoom(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1386                                  const bool has_translate, const bool has_zoom)
1387 {
1388         RegionView3D *rv3d = ar->regiondata;
1389         float view_inv[4];
1390         float pan_vec[3];
1391
1392         if (has_translate == false && has_zoom == false) {
1393                 return;
1394         }
1395
1396         WM_event_ndof_pan_get(ndof, pan_vec, false);
1397
1398         if (has_zoom) {
1399                 /* zoom with Z */
1400
1401                 /* Zoom!
1402                  * velocity should be proportional to the linear velocity attained by rotational motion of same strength
1403                  * [got that?]
1404                  * proportional to arclength = radius * angle
1405                  */
1406
1407                 pan_vec[2] = 0.0f;
1408
1409                 /* "zoom in" or "translate"? depends on zoom mode in user settings? */
1410                 if (ndof->tvec[2]) {
1411                         float zoom_distance = rv3d->dist * ndof->dt * ndof->tvec[2];
1412
1413                         if (U.ndof_flag & NDOF_ZOOM_INVERT)
1414                                 zoom_distance = -zoom_distance;
1415
1416                         rv3d->dist += zoom_distance;
1417                 }
1418         }
1419         else {
1420                 /* dolly with Z */
1421
1422                 /* all callers must check */
1423                 if (has_translate) {
1424                         BLI_assert(ED_view3d_offset_lock_check((View3D *)sa->spacedata.first, rv3d) == false);
1425                 }
1426         }
1427
1428         if (has_translate) {
1429                 const float speed = view3d_ndof_pan_speed_calc(rv3d);
1430
1431                 mul_v3_fl(pan_vec, speed * ndof->dt);
1432
1433                 /* transform motion from view to world coordinates */
1434                 invert_qt_qt(view_inv, rv3d->viewquat);
1435                 mul_qt_v3(view_inv, pan_vec);
1436
1437                 /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1438                 sub_v3_v3(rv3d->ofs, pan_vec);
1439
1440                 if (rv3d->viewlock & RV3D_BOXVIEW) {
1441                         view3d_boxview_sync(sa, ar);
1442                 }
1443         }
1444 }
1445
1446
1447 static void view3d_ndof_orbit(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
1448                               /* optional, can be NULL*/
1449                               ViewOpsData *vod)
1450 {
1451         View3D *v3d = sa->spacedata.first;
1452         RegionView3D *rv3d = ar->regiondata;
1453
1454         float view_inv[4];
1455
1456         BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
1457
1458         view3d_ensure_persp(v3d, ar);
1459
1460         rv3d->view = RV3D_VIEW_USER;
1461
1462         invert_qt_qt(view_inv, rv3d->viewquat);
1463
1464         if (U.ndof_flag & NDOF_TURNTABLE) {
1465                 float rot[3];
1466
1467                 /* turntable view code by John Aughey, adapted for 3D mouse by [mce] */
1468                 float angle, quat[4];
1469                 float xvec[3] = {1, 0, 0};
1470
1471                 /* only use XY, ignore Z */
1472                 WM_event_ndof_rotate_get(ndof, rot);
1473
1474                 /* Determine the direction of the x vector (for rotating up and down) */
1475                 mul_qt_v3(view_inv, xvec);
1476
1477                 /* Perform the up/down rotation */
1478                 angle = ndof->dt * rot[0];
1479                 quat[0] = cosf(angle);
1480                 mul_v3_v3fl(quat + 1, xvec, sinf(angle));
1481                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1482
1483                 /* Perform the orbital rotation */
1484                 angle = ndof->dt * rot[1];
1485
1486                 /* update the onscreen doo-dad */
1487                 rv3d->rot_angle = angle;
1488                 rv3d->rot_axis[0] = 0;
1489                 rv3d->rot_axis[1] = 0;
1490                 rv3d->rot_axis[2] = 1;
1491
1492                 quat[0] = cosf(angle);
1493                 quat[1] = 0.0f;
1494                 quat[2] = 0.0f;
1495                 quat[3] = sinf(angle);
1496                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1497
1498         }
1499         else {
1500                 float quat[4];
1501                 float axis[3];
1502                 float angle = WM_event_ndof_to_axis_angle(ndof, axis);
1503
1504                 /* transform rotation axis from view to world coordinates */
1505                 mul_qt_v3(view_inv, axis);
1506
1507                 /* update the onscreen doo-dad */
1508                 rv3d->rot_angle = angle;
1509                 copy_v3_v3(rv3d->rot_axis, axis);
1510
1511                 axis_angle_to_quat(quat, axis, angle);
1512
1513                 /* apply rotation */
1514                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
1515         }
1516
1517         if (vod) {
1518                 viewrotate_apply_dyn_ofs(vod, rv3d->viewquat);
1519         }
1520 }
1521
1522 /**
1523  * Called from both fly mode and walk mode,
1524  */
1525 void view3d_ndof_fly(
1526         const wmNDOFMotionData *ndof,
1527         View3D *v3d, RegionView3D *rv3d,
1528         const bool use_precision, const short protectflag,
1529         bool *r_has_translate, bool *r_has_rotate)
1530 {
1531         bool has_translate = NDOF_HAS_TRANSLATE;
1532         bool has_rotate = NDOF_HAS_ROTATE;
1533
1534         float view_inv[4];
1535         invert_qt_qt(view_inv, rv3d->viewquat);
1536
1537         rv3d->rot_angle = 0.0f;  /* disable onscreen rotation doo-dad */
1538
1539         if (has_translate) {
1540                 /* ignore real 'dist' since fly has its own speed settings,
1541                  * also its overwritten at this point. */
1542                 float speed = view3d_ndof_pan_speed_calc_from_dist(rv3d, 1.0f);
1543                 float trans[3], trans_orig_y;
1544
1545                 if (use_precision)
1546                         speed *= 0.2f;
1547
1548                 WM_event_ndof_pan_get(ndof, trans, false);
1549                 mul_v3_fl(trans, speed * ndof->dt);
1550                 trans_orig_y = trans[1];
1551
1552                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1553                         trans[1] = 0.0f;
1554                 }
1555
1556                 /* transform motion from view to world coordinates */
1557                 mul_qt_v3(view_inv, trans);
1558
1559                 if (U.ndof_flag & NDOF_FLY_HELICOPTER) {
1560                         /* replace world z component with device y (yes it makes sense) */
1561                         trans[2] = trans_orig_y;
1562                 }
1563
1564                 if (rv3d->persp == RV3D_CAMOB) {
1565                         /* respect camera position locks */
1566                         if (protectflag & OB_LOCK_LOCX) trans[0] = 0.0f;
1567                         if (protectflag & OB_LOCK_LOCY) trans[1] = 0.0f;
1568                         if (protectflag & OB_LOCK_LOCZ) trans[2] = 0.0f;
1569                 }
1570
1571                 if (!is_zero_v3(trans)) {
1572                         /* move center of view opposite of hand motion (this is camera mode, not object mode) */
1573                         sub_v3_v3(rv3d->ofs, trans);
1574                         has_translate = true;
1575                 }
1576                 else {
1577                         has_translate = false;
1578                 }
1579         }
1580
1581         if (has_rotate) {
1582                 const float turn_sensitivity = 1.0f;
1583
1584                 float rotation[4];
1585                 float axis[3];
1586                 float angle = turn_sensitivity * WM_event_ndof_to_axis_angle(ndof, axis);
1587
1588                 if (fabsf(angle) > 0.0001f) {
1589                         has_rotate = true;
1590
1591                         if (use_precision)
1592                                 angle *= 0.2f;
1593
1594                         /* transform rotation axis from view to world coordinates */
1595                         mul_qt_v3(view_inv, axis);
1596
1597                         /* apply rotation to view */
1598                         axis_angle_to_quat(rotation, axis, angle);
1599                         mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1600
1601                         if (U.ndof_flag & NDOF_LOCK_HORIZON) {
1602                                 /* force an upright viewpoint
1603                                  * TODO: make this less... sudden */
1604                                 float view_horizon[3] = {1.0f, 0.0f, 0.0f}; /* view +x */
1605                                 float view_direction[3] = {0.0f, 0.0f, -1.0f}; /* view -z (into screen) */
1606
1607                                 /* find new inverse since viewquat has changed */
1608                                 invert_qt_qt(view_inv, rv3d->viewquat);
1609                                 /* could apply reverse rotation to existing view_inv to save a few cycles */
1610
1611                                 /* transform view vectors to world coordinates */
1612                                 mul_qt_v3(view_inv, view_horizon);
1613                                 mul_qt_v3(view_inv, view_direction);
1614
1615
1616                                 /* find difference between view & world horizons
1617                                  * true horizon lives in world xy plane, so look only at difference in z */
1618                                 angle = -asinf(view_horizon[2]);
1619
1620                                 /* rotate view so view horizon = world horizon */
1621                                 axis_angle_to_quat(rotation, view_direction, angle);
1622                                 mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, rotation);
1623                         }
1624
1625                         rv3d->view = RV3D_VIEW_USER;
1626                 }
1627                 else {
1628                         has_rotate = false;
1629                 }
1630         }
1631
1632         *r_has_translate = has_translate;
1633         *r_has_rotate    = has_rotate;
1634 }
1635
1636 /** \} */
1637
1638
1639 /* -- "orbit" navigation (trackball/turntable)
1640  * -- zooming
1641  * -- panning in rotationally-locked views
1642  */
1643 static int ndof_orbit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1644 {
1645         
1646         if (event->type != NDOF_MOTION) {
1647                 return OPERATOR_CANCELLED;
1648         }
1649         else {
1650                 ViewOpsData *vod;
1651                 View3D *v3d;
1652                 RegionView3D *rv3d;
1653
1654                 const wmNDOFMotionData *ndof = event->customdata;
1655
1656                 viewops_data_alloc(C, op);
1657                 viewops_data_create_ex(C, op, event,
1658                                        (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
1659
1660                 vod = op->customdata;
1661                 v3d = vod->v3d;
1662                 rv3d = vod->rv3d;
1663
1664                 /* off by default, until changed later this function */
1665                 rv3d->rot_angle = 0.0f;
1666
1667                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1668
1669                 if (ndof->progress != P_FINISHING) {
1670                         const bool has_rotation = NDOF_HAS_ROTATE;
1671                         /* if we can't rotate, fallback to translate (locked axis views) */
1672                         const bool has_translate = NDOF_HAS_TRANSLATE && (rv3d->viewlock & RV3D_LOCKED);
1673                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1674
1675                         if (has_translate || has_zoom) {
1676                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1677                         }
1678
1679                         if (has_rotation) {
1680                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod);
1681                         }
1682                 }
1683
1684                 ED_view3d_camera_lock_sync(v3d, rv3d);
1685
1686                 ED_region_tag_redraw(vod->ar);
1687
1688                 viewops_data_free(C, op);
1689
1690                 return OPERATOR_FINISHED;
1691         }
1692 }
1693
1694 void VIEW3D_OT_ndof_orbit(struct wmOperatorType *ot)
1695 {
1696         /* identifiers */
1697         ot->name = "NDOF Orbit View";
1698         ot->description = "Orbit the view using the 3D mouse";
1699         ot->idname = "VIEW3D_OT_ndof_orbit";
1700
1701         /* api callbacks */
1702         ot->invoke = ndof_orbit_invoke;
1703         ot->poll = ED_operator_view3d_active;
1704
1705         /* flags */
1706         ot->flag = 0;
1707 }
1708
1709 static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1710 {
1711         
1712         if (event->type != NDOF_MOTION) {
1713                 return OPERATOR_CANCELLED;
1714         }
1715         else {
1716                 ViewOpsData *vod;
1717                 View3D *v3d;
1718                 RegionView3D *rv3d;
1719
1720                 const wmNDOFMotionData *ndof = event->customdata;
1721
1722                 viewops_data_alloc(C, op);
1723                 viewops_data_create_ex(C, op, event,
1724                                        (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
1725
1726                 vod = op->customdata;
1727                 v3d = vod->v3d;
1728                 rv3d = vod->rv3d;
1729
1730                 /* off by default, until changed later this function */
1731                 rv3d->rot_angle = 0.0f;
1732
1733                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1734
1735                 if (ndof->progress == P_FINISHING) {
1736                         /* pass */
1737                 }
1738                 else if ((rv3d->persp == RV3D_ORTHO) && RV3D_VIEW_IS_AXIS(rv3d->view)) {
1739                         /* if we can't rotate, fallback to translate (locked axis views) */
1740                         const bool has_translate = NDOF_HAS_TRANSLATE;
1741                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && ED_view3d_offset_lock_check(v3d, rv3d);
1742
1743                         if (has_translate || has_zoom) {
1744                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, true);
1745                         }
1746                 }
1747                 else if ((U.ndof_flag & NDOF_MODE_ORBIT) ||
1748                          ED_view3d_offset_lock_check(v3d, rv3d))
1749                 {
1750                         const bool has_rotation = NDOF_HAS_ROTATE;
1751                         const bool has_zoom = (ndof->tvec[2] != 0.0f);
1752
1753                         if (has_zoom) {
1754                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, false, has_zoom);
1755                         }
1756
1757                         if (has_rotation) {
1758                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, vod);
1759                         }
1760                 }
1761                 else {  /* free/explore (like fly mode) */
1762                         const bool has_rotation = NDOF_HAS_ROTATE;
1763                         const bool has_translate = NDOF_HAS_TRANSLATE;
1764                         const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1765
1766                         float dist_backup;
1767
1768                         if (has_translate || has_zoom) {
1769                                 view3d_ndof_pan_zoom(ndof, vod->sa, vod->ar, has_translate, has_zoom);
1770                         }
1771
1772                         dist_backup = rv3d->dist;
1773                         ED_view3d_distance_set(rv3d, 0.0f);
1774
1775                         if (has_rotation) {
1776                                 view3d_ndof_orbit(ndof, vod->sa, vod->ar, NULL);
1777                         }
1778
1779                         ED_view3d_distance_set(rv3d, dist_backup);
1780                 }
1781
1782                 ED_view3d_camera_lock_sync(v3d, rv3d);
1783
1784                 ED_region_tag_redraw(vod->ar);
1785
1786                 viewops_data_free(C, op);
1787
1788                 return OPERATOR_FINISHED;
1789         }
1790 }
1791
1792 void VIEW3D_OT_ndof_orbit_zoom(struct wmOperatorType *ot)
1793 {
1794         /* identifiers */
1795         ot->name = "NDOF Orbit View with Zoom";
1796         ot->description = "Orbit and zoom the view using the 3D mouse";
1797         ot->idname = "VIEW3D_OT_ndof_orbit_zoom";
1798
1799         /* api callbacks */
1800         ot->invoke = ndof_orbit_zoom_invoke;
1801         ot->poll = ED_operator_view3d_active;
1802
1803         /* flags */
1804         ot->flag = 0;
1805 }
1806
1807 /* -- "pan" navigation
1808  * -- zoom or dolly?
1809  */
1810 static int ndof_pan_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1811 {
1812         if (event->type != NDOF_MOTION) {
1813                 return OPERATOR_CANCELLED;
1814         }
1815         else {
1816                 View3D *v3d = CTX_wm_view3d(C);
1817                 RegionView3D *rv3d = CTX_wm_region_view3d(C);
1818                 const wmNDOFMotionData *ndof = event->customdata;
1819
1820                 const bool has_translate = NDOF_HAS_TRANSLATE;
1821                 const bool has_zoom = (ndof->tvec[2] != 0.0f) && !rv3d->is_persp;
1822
1823                 /* we're panning here! so erase any leftover rotation from other operators */
1824                 rv3d->rot_angle = 0.0f;
1825
1826                 if (!(has_translate || has_zoom))
1827                         return OPERATOR_CANCELLED;
1828
1829                 ED_view3d_camera_lock_init_ex(v3d, rv3d, false);
1830
1831                 if (ndof->progress != P_FINISHING) {
1832                         ScrArea *sa = CTX_wm_area(C);
1833                         ARegion *ar = CTX_wm_region(C);
1834
1835                         if (has_translate || has_zoom) {
1836                                 view3d_ndof_pan_zoom(ndof, sa, ar, has_translate, has_zoom);
1837                         }
1838                 }
1839
1840                 ED_view3d_camera_lock_sync(v3d, rv3d);
1841
1842                 ED_region_tag_redraw(CTX_wm_region(C));
1843
1844                 return OPERATOR_FINISHED;
1845         }
1846 }
1847
1848 void VIEW3D_OT_ndof_pan(struct wmOperatorType *ot)
1849 {
1850         /* identifiers */
1851         ot->name = "NDOF Pan View";
1852         ot->description = "Pan the view with the 3D mouse";
1853         ot->idname = "VIEW3D_OT_ndof_pan";
1854
1855         /* api callbacks */
1856         ot->invoke = ndof_pan_invoke;
1857         ot->poll = ED_operator_view3d_active;
1858
1859         /* flags */
1860         ot->flag = 0;
1861 }
1862
1863
1864 /**
1865  * wraps #ndof_orbit_zoom but never restrict to orbit.
1866  */
1867 static int ndof_all_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1868 {
1869         /* weak!, but it works */
1870         const int ndof_flag = U.ndof_flag;
1871         int ret;
1872
1873         U.ndof_flag &= ~NDOF_MODE_ORBIT;
1874
1875         ret = ndof_orbit_zoom_invoke(C, op, event);
1876
1877         U.ndof_flag = ndof_flag;
1878
1879         return ret;
1880 }
1881
1882 void VIEW3D_OT_ndof_all(struct wmOperatorType *ot)
1883 {
1884         /* identifiers */
1885         ot->name = "NDOF Move View";
1886         ot->description = "Pan and rotate the view with the 3D mouse";
1887         ot->idname = "VIEW3D_OT_ndof_all";
1888
1889         /* api callbacks */
1890         ot->invoke = ndof_all_invoke;
1891         ot->poll = ED_operator_view3d_active;
1892
1893         /* flags */
1894         ot->flag = 0;
1895 }
1896
1897 /* ************************ viewmove ******************************** */
1898
1899
1900 /* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
1901
1902 /* called in transform_ops.c, on each regeneration of keymaps  */
1903 void viewmove_modal_keymap(wmKeyConfig *keyconf)
1904 {
1905         static EnumPropertyItem modal_items[] = {
1906                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
1907                 
1908                 {VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
1909                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
1910
1911                 {0, NULL, 0, NULL, NULL}
1912         };
1913
1914         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Move Modal");
1915
1916         /* this function is called for each spacetype, only needs to add map once */
1917         if (keymap && keymap->modal_items) return;
1918
1919         keymap = WM_modalkeymap_add(keyconf, "View3D Move Modal", modal_items);
1920
1921         /* items for modal map */
1922         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1923         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
1924
1925         /* disabled mode switching for now, can re-implement better, later on */
1926 #if 0
1927         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1928         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
1929         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
1930 #endif
1931         
1932         /* assign map to operators */
1933         WM_modalkeymap_assign(keymap, "VIEW3D_OT_move");
1934 }
1935
1936
1937 static void viewmove_apply(ViewOpsData *vod, int x, int y)
1938 {
1939         if (ED_view3d_offset_lock_check(vod->v3d, vod->rv3d)) {
1940                 vod->rv3d->ofs_lock[0] -= ((vod->oldx - x) * 2.0f) / (float)vod->ar->winx;
1941                 vod->rv3d->ofs_lock[1] -= ((vod->oldy - y) * 2.0f) / (float)vod->ar->winy;
1942         }
1943         else if ((vod->rv3d->persp == RV3D_CAMOB) && !ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) {
1944                 const float zoomfac = BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
1945                 vod->rv3d->camdx += (vod->oldx - x) / (vod->ar->winx * zoomfac);
1946                 vod->rv3d->camdy += (vod->oldy - y) / (vod->ar->winy * zoomfac);
1947                 CLAMP(vod->rv3d->camdx, -1.0f, 1.0f);
1948                 CLAMP(vod->rv3d->camdy, -1.0f, 1.0f);
1949         }
1950         else {
1951                 float dvec[3];
1952                 float mval_f[2];
1953
1954                 mval_f[0] = x - vod->oldx;
1955                 mval_f[1] = y - vod->oldy;
1956                 ED_view3d_win_to_delta(vod->ar, mval_f, dvec, vod->zfac);
1957
1958                 add_v3_v3(vod->rv3d->ofs, dvec);
1959
1960                 if (vod->rv3d->viewlock & RV3D_BOXVIEW)
1961                         view3d_boxview_sync(vod->sa, vod->ar);
1962         }
1963
1964         vod->oldx = x;
1965         vod->oldy = y;
1966
1967         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
1968
1969         ED_region_tag_redraw(vod->ar);
1970 }
1971
1972
1973 static int viewmove_modal(bContext *C, wmOperator *op, const wmEvent *event)
1974 {
1975
1976         ViewOpsData *vod = op->customdata;
1977         short event_code = VIEW_PASS;
1978         bool use_autokey = false;
1979         int ret = OPERATOR_RUNNING_MODAL;
1980
1981         /* execute the events */
1982         if (event->type == MOUSEMOVE) {
1983                 event_code = VIEW_APPLY;
1984         }
1985         else if (event->type == EVT_MODAL_MAP) {
1986                 switch (event->val) {
1987                         case VIEW_MODAL_CONFIRM:
1988                                 event_code = VIEW_CONFIRM;
1989                                 break;
1990                         case VIEWROT_MODAL_SWITCH_ZOOM:
1991                                 WM_operator_name_call(C, "VIEW3D_OT_zoom", WM_OP_INVOKE_DEFAULT, NULL);
1992                                 event_code = VIEW_CONFIRM;
1993                                 break;
1994                         case VIEWROT_MODAL_SWITCH_ROTATE:
1995                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
1996                                 event_code = VIEW_CONFIRM;
1997                                 break;
1998                 }
1999         }
2000         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
2001                 event_code = VIEW_CONFIRM;
2002         }
2003
2004         if (event_code == VIEW_APPLY) {
2005                 viewmove_apply(vod, event->x, event->y);
2006                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2007                         use_autokey = true;
2008                 }
2009         }
2010         else if (event_code == VIEW_CONFIRM) {
2011                 ED_view3d_depth_tag_update(vod->rv3d);
2012                 use_autokey = true;
2013                 ret = OPERATOR_FINISHED;
2014         }
2015
2016         if (use_autokey) {
2017                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2018         }
2019
2020         if (ret & OPERATOR_FINISHED) {
2021                 viewops_data_free(C, op);
2022         }
2023
2024         return ret;
2025 }
2026
2027 static int viewmove_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2028 {
2029         ViewOpsData *vod;
2030
2031         /* makes op->customdata */
2032         viewops_data_alloc(C, op);
2033         viewops_data_create(C, op, event);
2034         vod = op->customdata;
2035
2036         if (event->type == MOUSEPAN) {
2037                 /* invert it, trackpad scroll follows same principle as 2d windows this way */
2038                 viewmove_apply(vod, 2 * event->x - event->prevx, 2 * event->y - event->prevy);
2039                 ED_view3d_depth_tag_update(vod->rv3d);
2040                 
2041                 viewops_data_free(C, op);
2042                 
2043                 return OPERATOR_FINISHED;
2044         }
2045         else {
2046                 /* add temp handler */
2047                 WM_event_add_modal_handler(C, op);
2048
2049                 return OPERATOR_RUNNING_MODAL;
2050         }
2051 }
2052
2053 static void viewmove_cancel(bContext *C, wmOperator *op)
2054 {
2055         viewops_data_free(C, op);
2056 }
2057
2058 void VIEW3D_OT_move(wmOperatorType *ot)
2059 {
2060
2061         /* identifiers */
2062         ot->name = "Move View";
2063         ot->description = "Move the view";
2064         ot->idname = "VIEW3D_OT_move";
2065
2066         /* api callbacks */
2067         ot->invoke = viewmove_invoke;
2068         ot->modal = viewmove_modal;
2069         ot->poll = ED_operator_view3d_active;
2070         ot->cancel = viewmove_cancel;
2071
2072         /* flags */
2073         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2074 }
2075
2076 /* ************************ viewzoom ******************************** */
2077
2078 /* viewdolly_modal_keymap has an exact copy of this, apply fixes to both */
2079 /* called in transform_ops.c, on each regeneration of keymaps  */
2080 void viewzoom_modal_keymap(wmKeyConfig *keyconf)
2081 {
2082         static EnumPropertyItem modal_items[] = {
2083                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
2084                 
2085                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
2086                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
2087
2088                 {0, NULL, 0, NULL, NULL}
2089         };
2090
2091         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Zoom Modal");
2092
2093         /* this function is called for each spacetype, only needs to add map once */
2094         if (keymap && keymap->modal_items) return;
2095
2096         keymap = WM_modalkeymap_add(keyconf, "View3D Zoom Modal", modal_items);
2097
2098         /* items for modal map */
2099         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2100         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2101
2102         /* disabled mode switching for now, can re-implement better, later on */
2103 #if 0
2104         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2105         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2106         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
2107 #endif
2108         
2109         /* assign map to operators */
2110         WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom");
2111 }
2112
2113 static void view_zoom_mouseloc_camera(
2114         Scene *scene, View3D *v3d,
2115         ARegion *ar, float dfac, int mx, int my)
2116 {
2117         RegionView3D *rv3d = ar->regiondata;
2118         const float zoomfac = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
2119         const float zoomfac_new = CLAMPIS(zoomfac * (1.0f / dfac), RV3D_CAMZOOM_MIN_FACTOR, RV3D_CAMZOOM_MAX_FACTOR);
2120         const float camzoom_new = BKE_screen_view3d_zoom_from_fac(zoomfac_new);
2121
2122
2123         if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
2124                 float zoomfac_px;
2125                 rctf camera_frame_old;
2126                 rctf camera_frame_new;
2127
2128                 const float pt_src[2] = {mx, my};
2129                 float pt_dst[2];
2130                 float delta_px[2];
2131
2132                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &camera_frame_old, false);
2133                 BLI_rctf_translate(&camera_frame_old, ar->winrct.xmin, ar->winrct.ymin);
2134
2135                 rv3d->camzoom = camzoom_new;
2136                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2137
2138                 ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &camera_frame_new, false);
2139                 BLI_rctf_translate(&camera_frame_new, ar->winrct.xmin, ar->winrct.ymin);
2140
2141                 BLI_rctf_transform_pt_v(&camera_frame_new, &camera_frame_old, pt_dst, pt_src);
2142                 sub_v2_v2v2(delta_px, pt_dst, pt_src);
2143
2144                 /* translate the camera offset using pixel space delta
2145                  * mapped back to the camera (same logic as panning in camera view) */
2146                 zoomfac_px = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom) * 2.0f;
2147
2148                 rv3d->camdx += delta_px[0] / (ar->winx * zoomfac_px);
2149                 rv3d->camdy += delta_px[1] / (ar->winy * zoomfac_px);
2150                 CLAMP(rv3d->camdx, -1.0f, 1.0f);
2151                 CLAMP(rv3d->camdy, -1.0f, 1.0f);
2152         }
2153         else {
2154                 rv3d->camzoom = camzoom_new;
2155                 CLAMP(rv3d->camzoom, RV3D_CAMZOOM_MIN, RV3D_CAMZOOM_MAX);
2156         }
2157 }
2158
2159 static void view_zoom_mouseloc_3d(ARegion *ar, float dfac, int mx, int my)
2160 {
2161         RegionView3D *rv3d = ar->regiondata;
2162         const float dist_new = rv3d->dist * dfac;
2163
2164         if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
2165                 float dvec[3];
2166                 float tvec[3];
2167                 float tpos[3];
2168                 float mval_f[2];
2169
2170                 float zfac;
2171
2172                 negate_v3_v3(tpos, rv3d->ofs);
2173
2174                 mval_f[0] = (float)(((mx - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
2175                 mval_f[1] = (float)(((my - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
2176
2177                 /* Project cursor position into 3D space */
2178                 zfac = ED_view3d_calc_zfac(rv3d, tpos, NULL);
2179                 ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
2180
2181                 /* Calculate view target position for dolly */
2182                 add_v3_v3v3(tvec, tpos, dvec);
2183                 negate_v3(tvec);
2184
2185                 /* Offset to target position and dolly */
2186                 copy_v3_v3(rv3d->ofs, tvec);
2187                 rv3d->dist = dist_new;
2188
2189                 /* Calculate final offset */
2190                 madd_v3_v3v3fl(rv3d->ofs, tvec, dvec, dfac);
2191         }
2192         else {
2193                 rv3d->dist = dist_new;
2194         }
2195 }
2196
2197 static float viewzoom_scale_value(
2198         const rcti *winrct,
2199         const short viewzoom,
2200         const bool zoom_invert, const bool zoom_invert_force,
2201         const int xy[2], const int xy_orig[2],
2202         const float val, const float val_orig,
2203         double *r_timer_lastdraw)
2204 {
2205         float zfac;
2206
2207         if (viewzoom == USER_ZOOM_CONT) {
2208                 double time = PIL_check_seconds_timer();
2209                 float time_step = (float)(time - *r_timer_lastdraw);
2210                 float fac;
2211
2212                 if (U.uiflag & USER_ZOOM_HORIZ) {
2213                         fac = (float)(xy_orig[0] - xy[0]);
2214                 }
2215                 else {
2216                         fac = (float)(xy_orig[1] - xy[1]);
2217                 }
2218
2219                 if (zoom_invert != zoom_invert_force) {
2220                         fac = -fac;
2221                 }
2222
2223                 /* oldstyle zoom */
2224                 zfac = 1.0f + ((fac / 20.0f) * time_step);
2225                 *r_timer_lastdraw = time;
2226         }
2227         else if (viewzoom == USER_ZOOM_SCALE) {
2228                 /* method which zooms based on how far you move the mouse */
2229
2230                 const int ctr[2] = {
2231                     BLI_rcti_cent_x(winrct),
2232                     BLI_rcti_cent_y(winrct),
2233                 };
2234                 float len_new = 5 + len_v2v2_int(ctr, xy);
2235                 float len_old = 5 + len_v2v2_int(ctr, xy_orig);
2236
2237                 /* intentionally ignore 'zoom_invert' for scale */
2238                 if (zoom_invert_force) {
2239                         SWAP(float, len_new, len_old);
2240                 }
2241
2242                 zfac = val_orig * (len_old / max_ff(len_new, 1.0f)) / val;
2243         }
2244         else {  /* USER_ZOOM_DOLLY */
2245                 float len_new = 5;
2246                 float len_old = 5;
2247
2248                 if (U.uiflag & USER_ZOOM_HORIZ) {
2249                         len_new += (winrct->xmax - xy[0]);
2250                         len_old += (winrct->xmax - xy_orig[0]);
2251                 }
2252                 else {
2253                         len_new += (winrct->ymax - xy[1]);
2254                         len_old += (winrct->ymax - xy_orig[1]);
2255                 }
2256
2257                 if (zoom_invert != zoom_invert_force) {
2258                         SWAP(float, len_new, len_old);
2259                 }
2260
2261                 zfac = val_orig * (2.0f * ((len_new / max_ff(len_old, 1.0f)) - 1.0f) + 1.0f) / val;
2262         }
2263
2264
2265         return zfac;
2266 }
2267
2268 static void viewzoom_apply_camera(
2269         ViewOpsData *vod, const int xy[2],
2270         const short viewzoom, const bool zoom_invert)
2271 {
2272         float zfac;
2273         float zoomfac_prev = BKE_screen_view3d_zoom_to_fac(vod->camzoom_prev) * 2.0f;
2274         float zoomfac =      BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
2275
2276         zfac = viewzoom_scale_value(
2277                &vod->ar->winrct, viewzoom, zoom_invert, true, xy, &vod->origx,
2278                zoomfac, zoomfac_prev,
2279                &vod->timer_lastdraw);
2280
2281         if (zfac != 1.0f && zfac != 0.0f) {
2282                 /* calculate inverted, then invert again (needed because of camera zoom scaling) */
2283                 zfac = 1.0f / zfac;
2284                 view_zoom_mouseloc_camera(
2285                         vod->scene, vod->v3d,
2286                         vod->ar, zfac, vod->oldx, vod->oldy);
2287         }
2288
2289         ED_region_tag_redraw(vod->ar);
2290 }
2291
2292 static void viewzoom_apply_3d(
2293         ViewOpsData *vod, const int xy[2],
2294         const short viewzoom, const bool zoom_invert)
2295 {
2296         float zfac;
2297         float dist_range[2];
2298
2299         ED_view3d_dist_range_get(vod->v3d, dist_range);
2300
2301         zfac = viewzoom_scale_value(
2302                &vod->ar->winrct, viewzoom, zoom_invert, false, xy, &vod->origx,
2303                vod->rv3d->dist, vod->dist_prev,
2304                &vod->timer_lastdraw);
2305
2306         if (zfac != 1.0f) {
2307                 const float zfac_min = dist_range[0] / vod->rv3d->dist;
2308                 const float zfac_max = dist_range[1] / vod->rv3d->dist;
2309                 CLAMP(zfac, zfac_min, zfac_max);
2310
2311                 view_zoom_mouseloc_3d(
2312                         vod->ar, zfac, vod->oldx, vod->oldy);
2313         }
2314
2315         /* these limits were in old code too */
2316         CLAMP(vod->rv3d->dist, dist_range[0], dist_range[1]);
2317
2318         if (vod->rv3d->viewlock & RV3D_BOXVIEW)
2319                 view3d_boxview_sync(vod->sa, vod->ar);
2320
2321         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
2322
2323         ED_region_tag_redraw(vod->ar);
2324 }
2325
2326 static void viewzoom_apply(
2327         ViewOpsData *vod, const int xy[2],
2328         const short viewzoom, const bool zoom_invert)
2329 {
2330         if ((vod->rv3d->persp == RV3D_CAMOB) &&
2331             (vod->rv3d->is_persp && ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) == 0)
2332         {
2333                 viewzoom_apply_camera(vod, xy, viewzoom, zoom_invert);
2334         }
2335         else {
2336                 viewzoom_apply_3d(vod, xy, viewzoom, zoom_invert);
2337         }
2338 }
2339
2340 static int viewzoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
2341 {
2342         ViewOpsData *vod = op->customdata;
2343         short event_code = VIEW_PASS;
2344         bool use_autokey = false;
2345         int ret = OPERATOR_RUNNING_MODAL;
2346
2347         /* execute the events */
2348         if (event->type == TIMER && event->customdata == vod->timer) {
2349                 /* continuous zoom */
2350                 event_code = VIEW_APPLY;
2351         }
2352         else if (event->type == MOUSEMOVE) {
2353                 event_code = VIEW_APPLY;
2354         }
2355         else if (event->type == EVT_MODAL_MAP) {
2356                 switch (event->val) {
2357                         case VIEW_MODAL_CONFIRM:
2358                                 event_code = VIEW_CONFIRM;
2359                                 break;
2360                         case VIEWROT_MODAL_SWITCH_MOVE:
2361                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2362                                 event_code = VIEW_CONFIRM;
2363                                 break;
2364                         case VIEWROT_MODAL_SWITCH_ROTATE:
2365                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2366                                 event_code = VIEW_CONFIRM;
2367                                 break;
2368                 }
2369         }
2370         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
2371                 event_code = VIEW_CONFIRM;
2372         }
2373
2374         if (event_code == VIEW_APPLY) {
2375                 viewzoom_apply(vod, &event->x, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
2376                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2377                         use_autokey = true;
2378                 }
2379         }
2380         else if (event_code == VIEW_CONFIRM) {
2381                 ED_view3d_depth_tag_update(vod->rv3d);
2382                 use_autokey = true;
2383                 ret = OPERATOR_FINISHED;
2384         }
2385
2386         if (use_autokey) {
2387                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2388         }
2389
2390         if (ret & OPERATOR_FINISHED) {
2391                 viewops_data_free(C, op);
2392         }
2393
2394         return ret;
2395 }
2396
2397 static int viewzoom_exec(bContext *C, wmOperator *op)
2398 {
2399         Scene *scene = CTX_data_scene(C);
2400         View3D *v3d;
2401         RegionView3D *rv3d;
2402         ScrArea *sa;
2403         ARegion *ar;
2404         bool use_cam_zoom;
2405         float dist_range[2];
2406
2407         const int delta = RNA_int_get(op->ptr, "delta");
2408         int mx, my;
2409
2410         if (op->customdata) {
2411                 ViewOpsData *vod = op->customdata;
2412
2413                 sa = vod->sa;
2414                 ar = vod->ar;
2415         }
2416         else {
2417                 sa = CTX_wm_area(C);
2418                 ar = CTX_wm_region(C);
2419         }
2420
2421         v3d = sa->spacedata.first;
2422         rv3d = ar->regiondata;
2423
2424         mx = RNA_struct_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
2425         my = RNA_struct_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
2426
2427         use_cam_zoom = (rv3d->persp == RV3D_CAMOB) && !(rv3d->is_persp && ED_view3d_camera_lock_check(v3d, rv3d));
2428
2429         ED_view3d_dist_range_get(v3d, dist_range);
2430
2431         if (delta < 0) {
2432                 const float step = 1.2f;
2433                 /* this min and max is also in viewmove() */
2434                 if (use_cam_zoom) {
2435                         view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
2436                 }
2437                 else {
2438                         if (rv3d->dist < dist_range[1]) {
2439                                 view_zoom_mouseloc_3d(ar, step, mx, my);
2440                         }
2441                 }
2442         }
2443         else {
2444                 const float step = 1.0f / 1.2f;
2445                 if (use_cam_zoom) {
2446                         view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
2447                 }
2448                 else {
2449                         if (rv3d->dist > dist_range[0]) {
2450                                 view_zoom_mouseloc_3d(ar, step, mx, my);
2451                         }
2452                 }
2453         }
2454
2455         if (rv3d->viewlock & RV3D_BOXVIEW)
2456                 view3d_boxview_sync(sa, ar);
2457
2458         ED_view3d_depth_tag_update(rv3d);
2459
2460         ED_view3d_camera_lock_sync(v3d, rv3d);
2461         ED_view3d_camera_lock_autokey(v3d, rv3d, C, false, true);
2462
2463         ED_region_tag_redraw(ar);
2464
2465         viewops_data_free(C, op);
2466
2467         return OPERATOR_FINISHED;
2468 }
2469
2470 /* this is an exact copy of viewzoom_modal_keymap */
2471 /* called in transform_ops.c, on each regeneration of keymaps  */
2472 void viewdolly_modal_keymap(wmKeyConfig *keyconf)
2473 {
2474         static EnumPropertyItem modal_items[] = {
2475                 {VIEW_MODAL_CONFIRM,    "CONFIRM", 0, "Confirm", ""},
2476
2477                 {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
2478                 {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
2479
2480                 {0, NULL, 0, NULL, NULL}
2481         };
2482
2483         wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
2484
2485         /* this function is called for each spacetype, only needs to add map once */
2486         if (keymap && keymap->modal_items) return;
2487
2488         keymap = WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
2489
2490         /* items for modal map */
2491         WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2492         WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
2493
2494         /* disabled mode switching for now, can re-implement better, later on */
2495 #if 0
2496         WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2497         WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
2498         WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
2499 #endif
2500         
2501         /* assign map to operators */
2502         WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
2503 }
2504
2505 /* viewdolly_invoke() copied this function, changes here may apply there */
2506 static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2507 {
2508         ViewOpsData *vod;
2509
2510         /* makes op->customdata */
2511         viewops_data_alloc(C, op);
2512         viewops_data_create(C, op, event);
2513         vod = op->customdata;
2514
2515         /* if one or the other zoom position aren't set, set from event */
2516         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2517                 RNA_int_set(op->ptr, "mx", event->x);
2518                 RNA_int_set(op->ptr, "my", event->y);
2519         }
2520
2521         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2522                 viewzoom_exec(C, op);
2523         }
2524         else {
2525                 if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
2526
2527                         if (U.uiflag & USER_ZOOM_HORIZ) {
2528                                 vod->origx = vod->oldx = event->x;
2529                                 viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
2530                         }
2531                         else {
2532                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2533                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
2534                                 viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
2535                         }
2536                         ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2537
2538                         ED_view3d_depth_tag_update(vod->rv3d);
2539
2540                         viewops_data_free(C, op);
2541                         return OPERATOR_FINISHED;
2542                 }
2543                 else {
2544                         if (U.viewzoom == USER_ZOOM_CONT) {
2545                                 /* needs a timer to continue redrawing */
2546                                 vod->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
2547                                 vod->timer_lastdraw = PIL_check_seconds_timer();
2548                         }
2549
2550                         /* add temp handler */
2551                         WM_event_add_modal_handler(C, op);
2552
2553                         return OPERATOR_RUNNING_MODAL;
2554                 }
2555         }
2556         return OPERATOR_FINISHED;
2557 }
2558
2559 static void viewzoom_cancel(bContext *C, wmOperator *op)
2560 {
2561         viewops_data_free(C, op);
2562 }
2563
2564 void VIEW3D_OT_zoom(wmOperatorType *ot)
2565 {
2566         PropertyRNA *prop;
2567
2568         /* identifiers */
2569         ot->name = "Zoom View";
2570         ot->description = "Zoom in/out in the view";
2571         ot->idname = "VIEW3D_OT_zoom";
2572
2573         /* api callbacks */
2574         ot->invoke = viewzoom_invoke;
2575         ot->exec = viewzoom_exec;
2576         ot->modal = viewzoom_modal;
2577         ot->poll = ED_operator_region_view3d_active;
2578         ot->cancel = viewzoom_cancel;
2579
2580         /* flags */
2581         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2582
2583         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2584         prop = RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
2585         RNA_def_property_flag(prop, PROP_HIDDEN);
2586         prop = RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
2587         RNA_def_property_flag(prop, PROP_HIDDEN);
2588 }
2589
2590
2591 /* ************************ viewdolly ******************************** */
2592 static void view_dolly_mouseloc(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
2593 {
2594         RegionView3D *rv3d = ar->regiondata;
2595         madd_v3_v3v3fl(rv3d->ofs, orig_ofs, dvec, -(1.0f - dfac));
2596 }
2597
2598 static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_invert)
2599 {
2600         float zfac = 1.0;
2601
2602         {
2603                 float len1, len2;
2604
2605                 if (U.uiflag & USER_ZOOM_HORIZ) {
2606                         len1 = (vod->ar->winrct.xmax - x) + 5;
2607                         len2 = (vod->ar->winrct.xmax - vod->origx) + 5;
2608                 }
2609                 else {
2610                         len1 = (vod->ar->winrct.ymax - y) + 5;
2611                         len2 = (vod->ar->winrct.ymax - vod->origy) + 5;
2612                 }
2613                 if (zoom_invert)
2614                         SWAP(float, len1, len2);
2615
2616                 zfac =  1.0f + ((len1 - len2) * 0.01f * vod->rv3d->dist);
2617         }
2618
2619         if (zfac != 1.0f)
2620                 view_dolly_mouseloc(vod->ar, vod->ofs, vod->mousevec, zfac);
2621
2622         if (vod->rv3d->viewlock & RV3D_BOXVIEW)
2623                 view3d_boxview_sync(vod->sa, vod->ar);
2624
2625         ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
2626
2627         ED_region_tag_redraw(vod->ar);
2628 }
2629
2630
2631 static int viewdolly_modal(bContext *C, wmOperator *op, const wmEvent *event)
2632 {
2633         ViewOpsData *vod = op->customdata;
2634         short event_code = VIEW_PASS;
2635         bool use_autokey = false;
2636         int ret = OPERATOR_RUNNING_MODAL;
2637
2638         /* execute the events */
2639         if (event->type == MOUSEMOVE) {
2640                 event_code = VIEW_APPLY;
2641         }
2642         else if (event->type == EVT_MODAL_MAP) {
2643                 switch (event->val) {
2644                         case VIEW_MODAL_CONFIRM:
2645                                 event_code = VIEW_CONFIRM;
2646                                 break;
2647                         case VIEWROT_MODAL_SWITCH_MOVE:
2648                                 WM_operator_name_call(C, "VIEW3D_OT_move", WM_OP_INVOKE_DEFAULT, NULL);
2649                                 event_code = VIEW_CONFIRM;
2650                                 break;
2651                         case VIEWROT_MODAL_SWITCH_ROTATE:
2652                                 WM_operator_name_call(C, "VIEW3D_OT_rotate", WM_OP_INVOKE_DEFAULT, NULL);
2653                                 event_code = VIEW_CONFIRM;
2654                                 break;
2655                 }
2656         }
2657         else if (event->type == vod->origkey && event->val == KM_RELEASE) {
2658                 event_code = VIEW_CONFIRM;
2659         }
2660
2661         if (event_code == VIEW_APPLY) {
2662                 viewdolly_apply(vod, event->x, event->y, (U.uiflag & USER_ZOOM_INVERT) != 0);
2663                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
2664                         use_autokey = true;
2665                 }
2666         }
2667         else if (event_code == VIEW_CONFIRM) {
2668                 ED_view3d_depth_tag_update(vod->rv3d);
2669                 use_autokey = true;
2670                 ret = OPERATOR_FINISHED;
2671         }
2672
2673         if (use_autokey) {
2674                 ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
2675         }
2676
2677         if (ret & OPERATOR_FINISHED) {
2678                 viewops_data_free(C, op);
2679         }
2680
2681         return ret;
2682 }
2683
2684 static int viewdolly_exec(bContext *C, wmOperator *op)
2685 {
2686         View3D *v3d;
2687         RegionView3D *rv3d;
2688         ScrArea *sa;
2689         ARegion *ar;
2690         float mousevec[3];
2691
2692         const int delta = RNA_int_get(op->ptr, "delta");
2693
2694         if (op->customdata) {
2695                 ViewOpsData *vod = op->customdata;
2696
2697                 sa = vod->sa;
2698                 ar = vod->ar;
2699                 copy_v3_v3(mousevec, vod->mousevec);
2700         }
2701         else {
2702                 sa = CTX_wm_area(C);
2703                 ar = CTX_wm_region(C);
2704                 negate_v3_v3(mousevec, ((RegionView3D *)ar->regiondata)->viewinv[2]);
2705                 normalize_v3(mousevec);
2706         }
2707
2708         v3d = sa->spacedata.first;
2709         rv3d = ar->regiondata;
2710
2711         /* overwrite the mouse vector with the view direction (zoom into the center) */
2712         if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
2713                 normalize_v3_v3(mousevec, rv3d->viewinv[2]);
2714         }
2715
2716         if (delta < 0) {
2717                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 0.2f);
2718         }
2719         else {
2720                 view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 1.8f);
2721         }
2722
2723         if (rv3d->viewlock & RV3D_BOXVIEW)
2724                 view3d_boxview_sync(sa, ar);
2725
2726         ED_view3d_depth_tag_update(rv3d);
2727
2728         ED_view3d_camera_lock_sync(v3d, rv3d);
2729
2730         ED_region_tag_redraw(ar);
2731
2732         viewops_data_free(C, op);
2733
2734         return OPERATOR_FINISHED;
2735 }
2736
2737 /* copied from viewzoom_invoke(), changes here may apply there */
2738 static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2739 {
2740         ViewOpsData *vod;
2741
2742         if (view3d_operator_offset_lock_check(C, op))
2743                 return OPERATOR_CANCELLED;
2744
2745         /* makes op->customdata */
2746         viewops_data_alloc(C, op);
2747         vod = op->customdata;
2748
2749         /* poll should check but in some cases fails, see poll func for details */
2750         if (vod->rv3d->viewlock & RV3D_LOCKED) {
2751                 viewops_data_free(C, op);
2752                 return OPERATOR_PASS_THROUGH;
2753         }
2754
2755         /* needs to run before 'viewops_data_create' so the backup 'rv3d->ofs' is correct */
2756         /* switch from camera view when: */
2757         if (vod->rv3d->persp != RV3D_PERSP) {
2758                 if (vod->rv3d->persp == RV3D_CAMOB) {
2759                         /* ignore rv3d->lpersp because dolly only makes sense in perspective mode */
2760                         view3d_persp_switch_from_camera(vod->v3d, vod->rv3d, RV3D_PERSP);
2761                 }
2762                 else {
2763                         vod->rv3d->persp = RV3D_PERSP;
2764                 }
2765                 ED_region_tag_redraw(vod->ar);
2766         }
2767
2768         viewops_data_create(C, op, event);
2769
2770
2771         /* if one or the other zoom position aren't set, set from event */
2772         if (!RNA_struct_property_is_set(op->ptr, "mx") || !RNA_struct_property_is_set(op->ptr, "my")) {
2773                 RNA_int_set(op->ptr, "mx", event->x);
2774                 RNA_int_set(op->ptr, "my", event->y);
2775         }
2776
2777         if (RNA_struct_property_is_set(op->ptr, "delta")) {
2778                 viewdolly_exec(C, op);
2779         }
2780         else {
2781                 /* overwrite the mouse vector with the view direction (zoom into the center) */
2782                 if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
2783                         negate_v3_v3(vod->mousevec, vod->rv3d->viewinv[2]);
2784                         normalize_v3(vod->mousevec);
2785                 }
2786
2787                 if (event->type == MOUSEZOOM) {
2788                         /* Bypass Zoom invert flag for track pads (pass false always) */
2789
2790                         if (U.uiflag & USER_ZOOM_HORIZ) {
2791                                 vod->origx = vod->oldx = event->x;
2792                                 viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
2793                         }
2794                         else {
2795
2796                                 /* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
2797                                 vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
2798                                 viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
2799                         }
2800                         ED_view3d_depth_tag_update(vod->rv3d);
2801
2802                         viewops_data_free(C, op);
2803                         return OPERATOR_FINISHED;
2804                 }
2805                 else {
2806                         /* add temp handler */
2807                         WM_event_add_modal_handler(C, op);
2808
2809                         return OPERATOR_RUNNING_MODAL;
2810                 }
2811         }
2812         return OPERATOR_FINISHED;
2813 }
2814
2815 static void viewdolly_cancel(bContext *C, wmOperator *op)
2816 {
2817         viewops_data_free(C, op);
2818 }
2819
2820 void VIEW3D_OT_dolly(wmOperatorType *ot)
2821 {
2822         /* identifiers */
2823         ot->name = "Dolly View";
2824         ot->description = "Dolly in/out in the view";
2825         ot->idname = "VIEW3D_OT_dolly";
2826
2827         /* api callbacks */
2828         ot->invoke = viewdolly_invoke;
2829         ot->exec = viewdolly_exec;
2830         ot->modal = viewdolly_modal;
2831         ot->poll = ED_operator_region_view3d_active;
2832         ot->cancel = viewdolly_cancel;
2833
2834         /* flags */
2835         ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
2836
2837         RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
2838         RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
2839         RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
2840 }
2841
2842 static void view3d_from_minmax(bContext *C, View3D *v3d, ARegion *ar,
2843                                const float min[3], const float max[3],
2844                                bool ok_dist, const int smooth_viewtx)
2845 {
2846         RegionView3D *rv3d = ar->regiondata;
2847         float afm[3];
2848         float size;
2849
2850         /* SMOOTHVIEW */
2851         float new_ofs[3];
2852         float new_dist;
2853
2854         sub_v3_v3v3(afm, max, min);
2855         size = max_fff(afm[0], afm[1], afm[2]);
2856
2857         if (ok_dist) {
2858                 char persp;
2859
2860                 if (rv3d->is_persp) {
2861                         if (rv3d->persp == RV3D_CAMOB && ED_view3d_camera_lock_check(v3d, rv3d)) {
2862                                 persp = RV3D_CAMOB;
2863                         }
2864                         else {
2865                                 persp = RV3D_PERSP;
2866                         }
2867                 }
2868                 else { /* ortho */
2869                         if (size < 0.0001f) {
2870                                 /* bounding box was a single point so do not zoom */
2871                                 ok_dist = false;
2872                         }
2873                         else {
2874                                 /* adjust zoom so it looks nicer */
2875                                 persp = RV3D_ORTHO;
2876                         }
2877                 }
2878
2879                 if (ok_dist) {
2880                         new_dist = ED_view3d_radius_to_dist(v3d, ar, persp, true, (size / 2) * VIEW3D_MARGIN);
2881                         if (rv3d->is_persp) {
2882                                 /* don't zoom closer than the near clipping plane */
2883                                 new_dist = max_ff(new_dist, v3d->near * 1.5f);
2884                         }
2885                 }
2886         }
2887
2888         mid_v3_v3v3(new_ofs, min, max);
2889         negate_v3(new_ofs);
2890
2891         if (rv3d->persp == RV3D_CAMOB && !ED_view3d_camera_lock_check(v3d, rv3d)) {
2892                 rv3d->persp = RV3D_PERSP;
2893                 ED_view3d_smooth_view(C, v3d, ar, v3d->camera, NULL,
2894                                       new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL,
2895                                       smooth_viewtx);
2896         }
2897         else {
2898                 ED_view3d_smooth_view(C, v3d, ar, NULL, NULL,
2899                                       new_ofs, NULL, ok_dist ? &new_dist : NULL, NULL,
2900                                       smooth_viewtx);
2901         }
2902
2903         /* smooth view does viewlock RV3D_BOXVIEW copy */
2904 }
2905
2906 /* same as view3d_from_minmax but for all regions (except cameras) */
2907 static void view3d_from_minmax_multi(bContext *C, View3D *v3d,
2908                                      const float min[3], const float max[3],
2909                                      const bool ok_dist, const int smooth_viewtx)
2910 {
2911         ScrArea *sa = CTX_wm_area(C);
2912         ARegion *ar;
2913         for (ar = sa->regionbase.first; ar; ar = ar->next) {
2914                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2915                         RegionView3D *rv3d = ar->regiondata;
2916                         /* when using all regions, don't jump out of camera view,
2917                          * but _do_ allow locked cameras to be moved */
2918                         if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d)) {
2919                                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
2920                         }
2921                 }
2922         }
2923 }
2924
2925 static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in 2.4x */
2926 {
2927         ARegion *ar = CTX_wm_region(C);
2928         View3D *v3d = CTX_wm_view3d(C);
2929         Scene *scene = CTX_data_scene(C);
2930         Base *base;
2931         float *curs;
2932         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
2933         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
2934                                   /* any one of the regions may be locked */
2935                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
2936         const bool center = RNA_boolean_get(op->ptr, "center");
2937         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
2938
2939         float min[3], max[3];
2940         bool changed = false;
2941
2942         if (center) {
2943                 /* in 2.4x this also move the cursor to (0, 0, 0) (with shift+c). */
2944                 curs = ED_view3d_cursor3d_get(scene, v3d);
2945                 zero_v3(min);
2946                 zero_v3(max);
2947                 zero_v3(curs);
2948         }
2949         else {
2950                 INIT_MINMAX(min, max);
2951         }
2952
2953         for (base = scene->base.first; base; base = base->next) {
2954                 if (BASE_VISIBLE(v3d, base)) {
2955                         changed = true;
2956
2957                         if (skip_camera && base->object == v3d->camera) {
2958                                 continue;
2959                         }
2960
2961                         BKE_object_minmax(base->object, min, max, false);
2962                 }
2963         }
2964         if (!changed) {
2965                 ED_region_tag_redraw(ar);
2966                 /* TODO - should this be cancel?
2967                  * I think no, because we always move the cursor, with or without
2968                  * object, but in this case there is no change in the scene,
2969                  * only the cursor so I choice a ED_region_tag like
2970                  * view3d_smooth_view do for the center_cursor.
2971                  * See bug #22640
2972                  */
2973                 return OPERATOR_FINISHED;
2974         }
2975
2976         if (use_all_regions) {
2977                 view3d_from_minmax_multi(C, v3d, min, max, true, smooth_viewtx);
2978         }
2979         else {
2980                 view3d_from_minmax(C, v3d, ar, min, max, true, smooth_viewtx);
2981         }
2982
2983         return OPERATOR_FINISHED;
2984 }
2985
2986
2987 void VIEW3D_OT_view_all(wmOperatorType *ot)
2988 {
2989         PropertyRNA *prop;
2990
2991         /* identifiers */
2992         ot->name = "View All";
2993         ot->description = "View all objects in scene";
2994         ot->idname = "VIEW3D_OT_view_all";
2995
2996         /* api callbacks */
2997         ot->exec = view3d_all_exec;
2998         ot->poll = ED_operator_region_view3d_active;
2999
3000         /* flags */
3001         ot->flag = 0;
3002
3003         prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
3004         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3005         RNA_def_boolean(ot->srna, "center", 0, "Center", "");
3006 }
3007
3008 /* like a localview without local!, was centerview() in 2.4x */
3009 static int viewselected_exec(bContext *C, wmOperator *op)
3010 {
3011         ARegion *ar = CTX_wm_region(C);
3012         View3D *v3d = CTX_wm_view3d(C);
3013         Scene *scene = CTX_data_scene(C);
3014         Object *ob = OBACT;
3015         Object *obedit = CTX_data_edit_object(C);
3016         float min[3], max[3];
3017         bool ok = false, ok_dist = true;
3018         const bool use_all_regions = RNA_boolean_get(op->ptr, "use_all_regions");
3019         const bool skip_camera = (ED_view3d_camera_lock_check(v3d, ar->regiondata) ||
3020                                   /* any one of the regions may be locked */
3021                                   (use_all_regions && v3d->flag2 & V3D_LOCK_CAMERA));
3022         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
3023
3024         INIT_MINMAX(min, max);
3025
3026         if (ob && (ob->mode & OB_MODE_WEIGHT_PAINT)) {
3027                 /* hard-coded exception, we look for the one selected armature */
3028                 /* this is weak code this way, we should make a generic active/selection callback interface once... */
3029                 Base *base;
3030                 for (base = scene->base.first; base; base = base->next) {
3031                         if (TESTBASELIB(v3d, base)) {
3032                                 if (base->object->type == OB_ARMATURE)
3033                                         if (base->object->mode & OB_MODE_POSE)
3034                                                 break;
3035                         }
3036                 }
3037                 if (base)
3038                         ob = base->object;
3039         }
3040
3041
3042         if (obedit) {
3043                 ok = ED_view3d_minmax_verts(obedit, min, max);    /* only selected */
3044         }
3045         else if (ob && (ob->mode & OB_MODE_POSE)) {
3046                 ok = BKE_pose_minmax(ob, min, max, true, true);
3047         }
3048         else if (BKE_paint_select_face_test(ob)) {
3049                 ok = paintface_minmax(ob, min, max);
3050         }
3051         else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT)) {
3052                 ok = PE_minmax(scene, min, max);
3053         }
3054         else if (ob && (ob->mode & (OB_MODE_SCULPT | OB_MODE_TEXTURE_PAINT))) {
3055                 BKE_paint_stroke_get_average(scene, ob, min);
3056                 copy_v3_v3(max, min);
3057                 ok = true;
3058                 ok_dist = 0; /* don't zoom */
3059         }
3060         else {
3061                 Base *base;
3062                 for (base = FIRSTBASE; base; base = base->next) {
3063                         if (TESTBASE(v3d, base)) {
3064
3065                                 if (skip_camera && base->object == v3d->camera) {
3066                                         continue;
3067                                 }
3068
3069                                 /* account for duplis */
3070                                 if (BKE_object_minmax_dupli(scene, base->object, min, max, false) == 0)
3071                                         BKE_object_minmax(base->object, min, max, false);  /* use if duplis not found */
3072
3073                                 ok = 1;
3074                         }
3075                 }
3076         }
3077
3078         if (ok == 0) {
3079                 return OPERATOR_FINISHED;
3080         }
3081
3082         if (use_all_regions) {
3083                 view3d_from_minmax_multi(C, v3d, min, max, ok_dist, smooth_viewtx);
3084         }
3085         else {
3086                 view3d_from_minmax(C, v3d, ar, min, max, ok_dist, smooth_viewtx);
3087         }
3088
3089 // XXX  BIF_view3d_previewrender_signal(curarea, PR_DBASE|PR_DISPRECT);
3090
3091         return OPERATOR_FINISHED;
3092 }
3093
3094 void VIEW3D_OT_view_selected(wmOperatorType *ot)
3095 {
3096         PropertyRNA *prop;
3097
3098         /* identifiers */
3099         ot->name = "View Selected";
3100         ot->description = "Move the view to the selection center";
3101         ot->idname = "VIEW3D_OT_view_selected";
3102
3103         /* api callbacks */
3104         ot->exec = viewselected_exec;
3105         ot->poll = ED_operator_region_view3d_active;
3106
3107         /* flags */
3108         ot->flag = 0;
3109
3110         /* rna later */
3111         prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
3112         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
3113 }
3114
3115 static int view_lock_clear_exec(bContext *C, wmOperator *UNUSED(op))
3116 {
3117         View3D *v3d = CTX_wm_view3d(C);
3118
3119         if (v3d) {
3120                 ED_view3D_lock_clear(v3d);
3121
3122                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3123
3124                 return OPERATOR_FINISHED;
3125         }
3126         else {
3127                 return OPERATOR_CANCELLED;
3128         }
3129 }
3130
3131 void VIEW3D_OT_view_lock_clear(wmOperatorType *ot)
3132 {
3133
3134         /* identifiers */
3135         ot->name = "View Lock Clear";
3136         ot->description = "Clear all view locking";
3137         ot->idname = "VIEW3D_OT_view_lock_clear";
3138
3139         /* api callbacks */
3140         ot->exec = view_lock_clear_exec;
3141         ot->poll = ED_operator_region_view3d_active;
3142
3143         /* flags */
3144         ot->flag = 0;
3145 }
3146
3147 static int view_lock_to_active_exec(bContext *C, wmOperator *UNUSED(op))
3148 {
3149         View3D *v3d = CTX_wm_view3d(C);
3150         Object *obact = CTX_data_active_object(C);
3151
3152         if (v3d) {
3153
3154                 ED_view3D_lock_clear(v3d);
3155
3156                 v3d->ob_centre = obact; /* can be NULL */
3157
3158                 if (obact && obact->type == OB_ARMATURE) {
3159                         if (obact->mode & OB_MODE_POSE) {
3160                                 bPoseChannel *pcham_act = BKE_pose_channel_active(obact);
3161                                 if (pcham_act) {
3162                                         BLI_strncpy(v3d->ob_centre_bone, pcham_act->name, sizeof(v3d->ob_centre_bone));
3163                                 }
3164                         }
3165                         else {
3166                                 EditBone *ebone_act = ((bArmature *)obact->data)->act_edbone;
3167                                 if (ebone_act) {
3168                                         BLI_strncpy(v3d->ob_centre_bone, ebone_act->name, sizeof(v3d->ob_centre_bone));
3169                                 }
3170                         }
3171                 }
3172
3173                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
3174
3175                 return OPERATOR_FINISHED;
3176         }
3177         else {
3178                 return OPERATOR_CANCELLED;
3179         }
3180 }
3181
3182 void VIEW3D_OT_view_lock_to_active(wmOperatorType *ot)
3183 {
3184
3185         /* identifiers */
3186         ot->name = "View Lock to Active";
3187         ot->description = "Lock the view to the active object/bone";
3188         ot->idname = "VIEW3D_OT_view_lock_to_active";
3189
3190         /* api callbacks */
3191         ot->exec = view_lock_to_active_exec;
3192         ot->poll = ED_operator_region_view3d_active;
3193
3194         /* flags */
3195         ot->flag = 0;
3196 }
3197
3198 static int viewcenter_cursor_exec(bContext *C, wmOperator *op)
3199 {
3200         View3D *v3d = CTX_wm_view3d(C);
3201         RegionView3D *rv3d = CTX_wm_region_view3d(C);