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