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