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