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