WM: refactor gestures for use as tools
[blender.git] / source / blender / editors / space_view3d / view3d_view.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_view.c
28  *  \ingroup spview3d
29  */
30
31
32 #include "DNA_camera_types.h"
33 #include "DNA_scene_types.h"
34 #include "DNA_object_types.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_rect.h"
40 #include "BLI_utildefines.h"
41
42 #include "BKE_anim.h"
43 #include "BKE_action.h"
44 #include "BKE_camera.h"
45 #include "BKE_context.h"
46 #include "BKE_depsgraph.h"
47 #include "BKE_object.h"
48 #include "BKE_global.h"
49 #include "BKE_main.h"
50 #include "BKE_report.h"
51 #include "BKE_scene.h"
52 #include "BKE_screen.h"
53
54 #include "BIF_gl.h"
55 #include "BIF_glutil.h"
56
57 #include "UI_resources.h"
58
59 #include "GPU_select.h"
60
61 #include "WM_api.h"
62 #include "WM_types.h"
63
64 #include "ED_screen.h"
65 #include "ED_armature.h"
66
67
68 #ifdef WITH_GAMEENGINE
69 #  include "BLI_listbase.h"
70 #  include "BLI_callbacks.h"
71
72 #  include "GPU_draw.h"
73
74 #  include "BL_System.h"
75 #endif
76
77
78 #include "view3d_intern.h"  /* own include */
79
80 /* use this call when executing an operator,
81  * event system doesn't set for each event the
82  * opengl drawing context */
83 void view3d_operator_needs_opengl(const bContext *C)
84 {
85         wmWindow *win = CTX_wm_window(C);
86         ARegion *ar = CTX_wm_region(C);
87         
88         view3d_region_operator_needs_opengl(win, ar);
89 }
90
91 void view3d_region_operator_needs_opengl(wmWindow *win, ARegion *ar)
92 {
93         /* for debugging purpose, context should always be OK */
94         if ((ar == NULL) || (ar->regiontype != RGN_TYPE_WINDOW)) {
95                 printf("view3d_region_operator_needs_opengl error, wrong region\n");
96         }
97         else {
98                 RegionView3D *rv3d = ar->regiondata;
99                 
100                 wmSubWindowSet(win, ar->swinid);
101                 glMatrixMode(GL_PROJECTION);
102                 glLoadMatrixf(rv3d->winmat);
103                 glMatrixMode(GL_MODELVIEW);
104                 glLoadMatrixf(rv3d->viewmat);
105         }
106 }
107
108 float *ED_view3d_cursor3d_get(Scene *scene, View3D *v3d)
109 {
110         if (v3d && v3d->localvd) return v3d->cursor;
111         else return scene->cursor;
112 }
113
114 Camera *ED_view3d_camera_data_get(View3D *v3d, RegionView3D *rv3d)
115 {
116         /* establish the camera object, so we can default to view mapping if anything is wrong with it */
117         if ((rv3d->persp == RV3D_CAMOB) && v3d->camera && (v3d->camera->type == OB_CAMERA)) {
118                 return v3d->camera->data;
119         }
120         else {
121                 return NULL;
122         }
123 }
124
125 /* ****************** smooth view operator ****************** */
126 /* This operator is one of the 'timer refresh' ones like animation playback */
127
128 struct SmoothView3DState {
129         float dist;
130         float lens;
131         float quat[4];
132         float ofs[3];
133 };
134
135 struct SmoothView3DStore {
136         /* source*/
137         struct SmoothView3DState src;  /* source */
138         struct SmoothView3DState dst;  /* destination */
139         struct SmoothView3DState org;  /* original */
140
141         bool to_camera;
142
143         bool use_dyn_ofs;
144         float dyn_ofs[3];
145
146         /* When smooth-view is enabled, store the 'rv3d->view' here,
147          * assign back when the view motion is completed. */
148         char org_view;
149
150         double time_allowed;
151 };
152
153 static void view3d_smooth_view_state_backup(struct SmoothView3DState *sms_state,
154                                             const View3D *v3d, const RegionView3D *rv3d)
155 {
156         copy_v3_v3(sms_state->ofs,   rv3d->ofs);
157         copy_qt_qt(sms_state->quat,  rv3d->viewquat);
158         sms_state->dist            = rv3d->dist;
159         sms_state->lens            = v3d->lens;
160 }
161
162 static void view3d_smooth_view_state_restore(const struct SmoothView3DState *sms_state,
163                                              View3D *v3d, RegionView3D *rv3d)
164 {
165         copy_v3_v3(rv3d->ofs,      sms_state->ofs);
166         copy_qt_qt(rv3d->viewquat, sms_state->quat);
167         rv3d->dist               = sms_state->dist;
168         v3d->lens                = sms_state->lens;
169 }
170
171 /* will start timer if appropriate */
172 /* the arguments are the desired situation */
173 void ED_view3d_smooth_view_ex(
174         /* avoid passing in the context */
175         wmWindowManager *wm, wmWindow *win, ScrArea *sa,
176         View3D *v3d, ARegion *ar, const int smooth_viewtx,
177         const V3D_SmoothParams *sview)
178 {
179         RegionView3D *rv3d = ar->regiondata;
180         struct SmoothView3DStore sms = {{0}};
181         bool ok = false;
182         
183         /* initialize sms */
184         view3d_smooth_view_state_backup(&sms.dst, v3d, rv3d);
185         view3d_smooth_view_state_backup(&sms.src, v3d, rv3d);
186         /* if smoothview runs multiple times... */
187         if (rv3d->sms == NULL) {
188                 view3d_smooth_view_state_backup(&sms.org, v3d, rv3d);
189         }
190         else {
191                 sms.org = rv3d->sms->org;
192         }
193         sms.org_view = rv3d->view;
194
195         /* sms.to_camera = false; */  /* initizlized to zero anyway */
196
197         /* note on camera locking, this is a little confusing but works ok.
198          * we may be changing the view 'as if' there is no active camera, but in fact
199          * there is an active camera which is locked to the view.
200          *
201          * In the case where smooth view is moving _to_ a camera we don't want that
202          * camera to be moved or changed, so only when the camera is not being set should
203          * we allow camera option locking to initialize the view settings from the camera.
204          */
205         if (sview->camera == NULL && sview->camera_old == NULL) {
206                 ED_view3d_camera_lock_init(v3d, rv3d);
207         }
208
209         /* store the options we want to end with */
210         if (sview->ofs)
211                 copy_v3_v3(sms.dst.ofs, sview->ofs);
212         if (sview->quat)
213                 copy_qt_qt(sms.dst.quat, sview->quat);
214         if (sview->dist)
215                 sms.dst.dist = *sview->dist;
216         if (sview->lens)
217                 sms.dst.lens = *sview->lens;
218
219         if (sview->dyn_ofs) {
220                 BLI_assert(sview->ofs  == NULL);
221                 BLI_assert(sview->quat != NULL);
222
223                 copy_v3_v3(sms.dyn_ofs, sview->dyn_ofs);
224                 sms.use_dyn_ofs = true;
225
226                 /* calculate the final destination offset */
227                 view3d_orbit_apply_dyn_ofs(sms.dst.ofs, sms.src.ofs, sms.src.quat, sms.dst.quat, sms.dyn_ofs);
228         }
229
230         if (sview->camera) {
231                 sms.dst.dist = ED_view3d_offset_distance(sview->camera->obmat, sview->ofs, VIEW3D_DIST_FALLBACK);
232                 ED_view3d_from_object(sview->camera, sms.dst.ofs, sms.dst.quat, &sms.dst.dist, &sms.dst.lens);
233                 sms.to_camera = true; /* restore view3d values in end */
234         }
235         
236         /* skip smooth viewing for render engine draw */
237         if (smooth_viewtx && v3d->drawtype != OB_RENDER) {
238                 bool changed = false; /* zero means no difference */
239                 
240                 if (sview->camera_old != sview->camera)
241                         changed = true;
242                 else if (sms.dst.dist != rv3d->dist)
243                         changed = true;
244                 else if (sms.dst.lens != v3d->lens)
245                         changed = true;
246                 else if (!equals_v3v3(sms.dst.ofs, rv3d->ofs))
247                         changed = true;
248                 else if (!equals_v4v4(sms.dst.quat, rv3d->viewquat))
249                         changed = true;
250                 
251                 /* The new view is different from the old one
252                  * so animate the view */
253                 if (changed) {
254                         /* original values */
255                         if (sview->camera_old) {
256                                 sms.src.dist = ED_view3d_offset_distance(sview->camera_old->obmat, rv3d->ofs, 0.0f);
257                                 /* this */
258                                 ED_view3d_from_object(sview->camera_old, sms.src.ofs, sms.src.quat, &sms.src.dist, &sms.src.lens);
259                         }
260                         /* grid draw as floor */
261                         if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
262                                 /* use existing if exists, means multiple calls to smooth view wont loose the original 'view' setting */
263                                 rv3d->view = RV3D_VIEW_USER;
264                         }
265
266                         sms.time_allowed = (double)smooth_viewtx / 1000.0;
267                         
268                         /* if this is view rotation only
269                          * we can decrease the time allowed by
270                          * the angle between quats 
271                          * this means small rotations wont lag */
272                         if (sview->quat && !sview->ofs && !sview->dist) {
273                                 /* scale the time allowed by the rotation */
274                                 sms.time_allowed *= (double)angle_normalized_qtqt(sms.dst.quat, sms.src.quat) / M_PI; /* 180deg == 1.0 */
275                         }
276
277                         /* ensure it shows correct */
278                         if (sms.to_camera) {
279                                 /* use ortho if we move from an ortho view to an ortho camera */
280                                 rv3d->persp = (((rv3d->is_persp == false) &&
281                                                 (sview->camera->type == OB_CAMERA) &&
282                                                 (((Camera *)sview->camera->data)->type == CAM_ORTHO)) ?
283                                                 RV3D_ORTHO : RV3D_PERSP);
284                         }
285
286                         rv3d->rflag |= RV3D_NAVIGATING;
287                         
288                         /* not essential but in some cases the caller will tag the area for redraw,
289                          * and in that case we can get a flicker of the 'org' user view but we want to see 'src' */
290                         view3d_smooth_view_state_restore(&sms.src, v3d, rv3d);
291
292                         /* keep track of running timer! */
293                         if (rv3d->sms == NULL) {
294                                 rv3d->sms = MEM_mallocN(sizeof(struct SmoothView3DStore), "smoothview v3d");
295                         }
296                         *rv3d->sms = sms;
297                         if (rv3d->smooth_timer) {
298                                 WM_event_remove_timer(wm, win, rv3d->smooth_timer);
299                         }
300                         /* TIMER1 is hardcoded in keymap */
301                         rv3d->smooth_timer = WM_event_add_timer(wm, win, TIMER1, 1.0 / 100.0); /* max 30 frs/sec */
302
303                         ok = true;
304                 }
305         }
306         
307         /* if we get here nothing happens */
308         if (ok == false) {
309                 if (sms.to_camera == false) {
310                         copy_v3_v3(rv3d->ofs, sms.dst.ofs);
311                         copy_qt_qt(rv3d->viewquat, sms.dst.quat);
312                         rv3d->dist = sms.dst.dist;
313                         v3d->lens = sms.dst.lens;
314
315                         ED_view3d_camera_lock_sync(v3d, rv3d);
316                 }
317
318                 if (rv3d->viewlock & RV3D_BOXVIEW) {
319                         view3d_boxview_copy(sa, ar);
320                 }
321
322                 ED_region_tag_redraw(ar);
323         }
324 }
325
326 void ED_view3d_smooth_view(
327         bContext *C,
328         View3D *v3d, ARegion *ar, const int smooth_viewtx,
329         const struct V3D_SmoothParams *sview)
330 {
331         wmWindowManager *wm = CTX_wm_manager(C);
332         wmWindow *win = CTX_wm_window(C);
333         ScrArea *sa = CTX_wm_area(C);
334
335         ED_view3d_smooth_view_ex(
336                 wm, win, sa,
337                 v3d, ar, smooth_viewtx,
338                 sview);
339 }
340
341 /* only meant for timer usage */
342 static void view3d_smoothview_apply(bContext *C, View3D *v3d, ARegion *ar, bool sync_boxview)
343 {
344         RegionView3D *rv3d = ar->regiondata;
345         struct SmoothView3DStore *sms = rv3d->sms;
346         float step, step_inv;
347         
348         if (sms->time_allowed != 0.0)
349                 step = (float)((rv3d->smooth_timer->duration) / sms->time_allowed);
350         else
351                 step = 1.0f;
352         
353         /* end timer */
354         if (step >= 1.0f) {
355                 
356                 /* if we went to camera, store the original */
357                 if (sms->to_camera) {
358                         rv3d->persp = RV3D_CAMOB;
359                         view3d_smooth_view_state_restore(&sms->org, v3d, rv3d);
360                 }
361                 else {
362                         view3d_smooth_view_state_restore(&sms->dst, v3d, rv3d);
363
364                         ED_view3d_camera_lock_sync(v3d, rv3d);
365                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
366                 }
367                 
368                 if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
369                         rv3d->view = sms->org_view;
370                 }
371
372                 MEM_freeN(rv3d->sms);
373                 rv3d->sms = NULL;
374                 
375                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rv3d->smooth_timer);
376                 rv3d->smooth_timer = NULL;
377                 rv3d->rflag &= ~RV3D_NAVIGATING;
378         }
379         else {
380                 /* ease in/out */
381                 step = (3.0f * step * step - 2.0f * step * step * step);
382
383                 step_inv = 1.0f - step;
384
385                 interp_qt_qtqt(rv3d->viewquat, sms->src.quat, sms->dst.quat, step);
386
387                 if (sms->use_dyn_ofs) {
388                         view3d_orbit_apply_dyn_ofs(rv3d->ofs, sms->src.ofs, sms->src.quat, rv3d->viewquat, sms->dyn_ofs);
389                 }
390                 else {
391                         interp_v3_v3v3(rv3d->ofs, sms->src.ofs,  sms->dst.ofs,  step);
392                 }
393                 
394                 rv3d->dist = sms->dst.dist * step + sms->src.dist * step_inv;
395                 v3d->lens  = sms->dst.lens * step + sms->src.lens * step_inv;
396
397                 ED_view3d_camera_lock_sync(v3d, rv3d);
398                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
399                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
400                 }
401
402         }
403         
404         if (sync_boxview && (rv3d->viewlock & RV3D_BOXVIEW)) {
405                 view3d_boxview_copy(CTX_wm_area(C), ar);
406         }
407
408         /* note: this doesn't work right because the v3d->lens is now used in ortho mode r51636,
409          * when switching camera in quad-view the other ortho views would zoom & reset.
410          *
411          * For now only redraw all regions when smoothview finishes.
412          */
413         if (step >= 1.0f) {
414                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
415         }
416         else {
417                 ED_region_tag_redraw(ar);
418         }
419 }
420
421 static int view3d_smoothview_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
422 {
423         View3D *v3d = CTX_wm_view3d(C);
424         ARegion *ar = CTX_wm_region(C);
425         RegionView3D *rv3d = ar->regiondata;
426
427         /* escape if not our timer */
428         if (rv3d->smooth_timer == NULL || rv3d->smooth_timer != event->customdata) {
429                 return OPERATOR_PASS_THROUGH;
430         }
431
432         view3d_smoothview_apply(C, v3d, ar, true);
433
434         return OPERATOR_FINISHED;
435 }
436
437 /**
438  * Apply the smoothview immediately, use when we need to start a new view operation.
439  * (so we don't end up half-applying a view operation when pressing keys quickly).
440  */
441 void ED_view3d_smooth_view_force_finish(
442         bContext *C,
443         View3D *v3d, ARegion *ar)
444 {
445         RegionView3D *rv3d = ar->regiondata;
446
447         if (rv3d && rv3d->sms) {
448                 rv3d->sms->time_allowed = 0.0;  /* force finishing */
449                 view3d_smoothview_apply(C, v3d, ar, false);
450
451                 /* force update of view matrix so tools that run immediately after
452                  * can use them without redrawing first */
453                 Scene *scene = CTX_data_scene(C);
454                 ED_view3d_update_viewmat(scene, v3d, ar, NULL, NULL, NULL);
455         }
456 }
457
458 void VIEW3D_OT_smoothview(wmOperatorType *ot)
459 {
460         
461         /* identifiers */
462         ot->name = "Smooth View";
463         ot->description = "";
464         ot->idname = "VIEW3D_OT_smoothview";
465         
466         /* api callbacks */
467         ot->invoke = view3d_smoothview_invoke;
468         
469         /* flags */
470         ot->flag = OPTYPE_INTERNAL;
471
472         ot->poll = ED_operator_view3d_active;
473 }
474
475 /* ****************** change view operators ****************** */
476
477 static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
478 {
479         View3D *v3d;
480         ARegion *ar;
481         RegionView3D *rv3d;
482
483         ObjectTfmProtectedChannels obtfm;
484
485         ED_view3d_context_user_region(C, &v3d, &ar);
486         rv3d = ar->regiondata;
487
488         ED_view3d_lastview_store(rv3d);
489
490         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
491
492         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
493
494         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag);
495
496         DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
497         rv3d->persp = RV3D_CAMOB;
498         
499         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, v3d->camera);
500         
501         return OPERATOR_FINISHED;
502
503 }
504
505 static int view3d_camera_to_view_poll(bContext *C)
506 {
507         View3D *v3d;
508         ARegion *ar;
509
510         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
511                 RegionView3D *rv3d = ar->regiondata;
512                 if (v3d && v3d->camera && !ID_IS_LINKED_DATABLOCK(v3d->camera)) {
513                         if (rv3d && (rv3d->viewlock & RV3D_LOCKED) == 0) {
514                                 if (rv3d->persp != RV3D_CAMOB) {
515                                         return 1;
516                                 }
517                         }
518                 }
519         }
520
521         return 0;
522 }
523
524 void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
525 {
526         /* identifiers */
527         ot->name = "Align Camera To View";
528         ot->description = "Set camera view to active view";
529         ot->idname = "VIEW3D_OT_camera_to_view";
530         
531         /* api callbacks */
532         ot->exec = view3d_camera_to_view_exec;
533         ot->poll = view3d_camera_to_view_poll;
534         
535         /* flags */
536         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
537 }
538
539 /* unlike VIEW3D_OT_view_selected this is for framing a render and not
540  * meant to take into account vertex/bone selection for eg. */
541 static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *op)
542 {
543         Scene *scene = CTX_data_scene(C);
544         View3D *v3d = CTX_wm_view3d(C);  /* can be NULL */
545         Object *camera_ob = v3d ? v3d->camera : scene->camera;
546
547         float r_co[3]; /* the new location to apply */
548         float r_scale; /* only for ortho cameras */
549
550         if (camera_ob == NULL) {
551                 BKE_report(op->reports, RPT_ERROR, "No active camera");
552                 return OPERATOR_CANCELLED;
553         }
554
555         /* this function does all the important stuff */
556         if (BKE_camera_view_frame_fit_to_scene(scene, v3d, camera_ob, r_co, &r_scale)) {
557                 ObjectTfmProtectedChannels obtfm;
558                 float obmat_new[4][4];
559
560                 if ((camera_ob->type == OB_CAMERA) && (((Camera *)camera_ob->data)->type == CAM_ORTHO)) {
561                         ((Camera *)camera_ob->data)->ortho_scale = r_scale;
562                 }
563
564                 copy_m4_m4(obmat_new, camera_ob->obmat);
565                 copy_v3_v3(obmat_new[3], r_co);
566
567                 /* only touch location */
568                 BKE_object_tfm_protected_backup(camera_ob, &obtfm);
569                 BKE_object_apply_mat4(camera_ob, obmat_new, true, true);
570                 BKE_object_tfm_protected_restore(camera_ob, &obtfm, OB_LOCK_SCALE | OB_LOCK_ROT4D);
571
572                 /* notifiers */
573                 DAG_id_tag_update(&camera_ob->id, OB_RECALC_OB);
574                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, camera_ob);
575                 return OPERATOR_FINISHED;
576         }
577         else {
578                 return OPERATOR_CANCELLED;
579         }
580 }
581
582 void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
583 {
584         /* identifiers */
585         ot->name = "Camera Fit Frame to Selected";
586         ot->description = "Move the camera so selected objects are framed";
587         ot->idname = "VIEW3D_OT_camera_to_view_selected";
588
589         /* api callbacks */
590         ot->exec = view3d_camera_to_view_selected_exec;
591         ot->poll = ED_operator_scene_editable;
592
593         /* flags */
594         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
595 }
596
597 static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob, const int smooth_viewtx)
598 {
599         Main *bmain = CTX_data_main(C);
600         for (bScreen *screen = bmain->screen.first; screen != NULL; screen = screen->id.next) {
601                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
602                         for (SpaceLink *space_link = area->spacedata.first; space_link != NULL; space_link = space_link->next) {
603                                 if (space_link->spacetype == SPACE_VIEW3D) {
604                                         View3D *other_v3d = (View3D *)space_link;
605                                         if (other_v3d == v3d) {
606                                                 continue;
607                                         }
608                                         if (other_v3d->camera == ob) {
609                                                 continue;
610                                         }
611                                         if (v3d->scenelock) {
612                                                 ListBase *lb = (space_link == area->spacedata.first)
613                                                                    ? &area->regionbase
614                                                                    : &space_link->regionbase;
615                                                 for (ARegion *other_ar = lb->first; other_ar != NULL; other_ar = other_ar->next) {
616                                                         if (other_ar->regiontype == RGN_TYPE_WINDOW) {
617                                                                 if (other_ar->regiondata) {
618                                                                         RegionView3D *other_rv3d = other_ar->regiondata;
619                                                                         if (other_rv3d->persp == RV3D_CAMOB) {
620                                                                                 Object *other_camera_old = other_v3d->camera;
621                                                                                 other_v3d->camera = ob;
622                                                                                 ED_view3d_lastview_store(other_rv3d);
623                                                                                 ED_view3d_smooth_view(
624                                                                                         C, other_v3d, other_ar, smooth_viewtx,
625                                                                                         &(const V3D_SmoothParams) {
626                                                                                             .camera_old = other_camera_old,
627                                                                                             .camera = other_v3d->camera,
628                                                                                             .ofs = other_rv3d->ofs,
629                                                                                             .quat = other_rv3d->viewquat,
630                                                                                             .dist = &other_rv3d->dist,
631                                                                                             .lens = &other_v3d->lens});
632                                                                         }
633                                                                         else {
634                                                                                 other_v3d->camera = ob;
635                                                                         }
636                                                                 }
637                                                         }
638                                                 }
639                                         }
640                                 }
641                         }
642                 }
643         }
644 }
645
646 static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op)
647 {       
648         View3D *v3d;
649         ARegion *ar;
650         RegionView3D *rv3d;
651
652         Scene *scene = CTX_data_scene(C);
653         Object *ob = CTX_data_active_object(C);
654
655         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
656
657         /* no NULL check is needed, poll checks */
658         ED_view3d_context_user_region(C, &v3d, &ar);
659         rv3d = ar->regiondata;
660
661         if (ob) {
662                 Object *camera_old = (rv3d->persp == RV3D_CAMOB) ? V3D_CAMERA_SCENE(scene, v3d) : NULL;
663                 rv3d->persp = RV3D_CAMOB;
664                 v3d->camera = ob;
665                 if (v3d->scenelock)
666                         scene->camera = ob;
667
668                 /* unlikely but looks like a glitch when set to the same */
669                 if (camera_old != ob) {
670                         ED_view3d_lastview_store(rv3d);
671
672                         ED_view3d_smooth_view(
673                                 C, v3d, ar, smooth_viewtx,
674                                 &(const V3D_SmoothParams) {
675                                     .camera_old = camera_old, .camera = v3d->camera,
676                                     .ofs = rv3d->ofs, .quat = rv3d->viewquat,
677                                     .dist = &rv3d->dist, .lens = &v3d->lens});
678                 }
679
680                 if (v3d->scenelock) {
681                         sync_viewport_camera_smoothview(C, v3d, ob, smooth_viewtx);
682                         WM_event_add_notifier(C, NC_SCENE, scene);
683                 }
684                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
685         }
686         
687         return OPERATOR_FINISHED;
688 }
689
690 int ED_operator_rv3d_user_region_poll(bContext *C)
691 {
692         View3D *v3d_dummy;
693         ARegion *ar_dummy;
694
695         return ED_view3d_context_user_region(C, &v3d_dummy, &ar_dummy);
696 }
697
698 void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
699 {
700         
701         /* identifiers */
702         ot->name = "Set Active Object as Camera";
703         ot->description = "Set the active object as the active camera for this view or scene";
704         ot->idname = "VIEW3D_OT_object_as_camera";
705         
706         /* api callbacks */
707         ot->exec = view3d_setobjectascamera_exec;
708         ot->poll = ED_operator_rv3d_user_region_poll;
709         
710         /* flags */
711         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
712 }
713
714 /* ********************************** */
715
716 void ED_view3d_clipping_calc_from_boundbox(float clip[4][4], const BoundBox *bb, const bool is_flip)
717 {
718         int val;
719
720         for (val = 0; val < 4; val++) {
721                 normal_tri_v3(clip[val], bb->vec[val], bb->vec[val == 3 ? 0 : val + 1], bb->vec[val + 4]);
722                 if (UNLIKELY(is_flip)) {
723                         negate_v3(clip[val]);
724                 }
725
726                 clip[val][3] = -dot_v3v3(clip[val], bb->vec[val]);
727         }
728 }
729
730 void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
731 {
732         float modelview[4][4];
733         double xs, ys, p[3];
734         int val, flip_sign, a;
735
736         /* near zero floating point values can give issues with gluUnProject
737          * in side view on some implementations */
738         if (fabs(mats->modelview[0]) < 1e-6) mats->modelview[0] = 0.0;
739         if (fabs(mats->modelview[5]) < 1e-6) mats->modelview[5] = 0.0;
740
741         /* Set up viewport so that gluUnProject will give correct values */
742         mats->viewport[0] = 0;
743         mats->viewport[1] = 0;
744
745         /* four clipping planes and bounding volume */
746         /* first do the bounding volume */
747         for (val = 0; val < 4; val++) {
748                 xs = (val == 0 || val == 3) ? rect->xmin : rect->xmax;
749                 ys = (val == 0 || val == 1) ? rect->ymin : rect->ymax;
750
751                 gluUnProject(xs, ys, 0.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
752                 copy_v3fl_v3db(bb->vec[val], p);
753
754                 gluUnProject(xs, ys, 1.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
755                 copy_v3fl_v3db(bb->vec[4 + val], p);
756         }
757
758         /* verify if we have negative scale. doing the transform before cross
759          * product flips the sign of the vector compared to doing cross product
760          * before transform then, so we correct for that. */
761         for (a = 0; a < 16; a++)
762                 ((float *)modelview)[a] = mats->modelview[a];
763         flip_sign = is_negative_m4(modelview);
764
765         ED_view3d_clipping_calc_from_boundbox(planes, bb, flip_sign);
766 }
767
768 static bool view3d_boundbox_clip_m4(const BoundBox *bb, float persmatob[4][4])
769 {
770         int a, flag = -1, fl;
771
772         for (a = 0; a < 8; a++) {
773                 float vec[4], min, max;
774                 copy_v3_v3(vec, bb->vec[a]);
775                 vec[3] = 1.0;
776                 mul_m4_v4(persmatob, vec);
777                 max = vec[3];
778                 min = -vec[3];
779
780                 fl = 0;
781                 if (vec[0] < min) fl += 1;
782                 if (vec[0] > max) fl += 2;
783                 if (vec[1] < min) fl += 4;
784                 if (vec[1] > max) fl += 8;
785                 if (vec[2] < min) fl += 16;
786                 if (vec[2] > max) fl += 32;
787
788                 flag &= fl;
789                 if (flag == 0) return true;
790         }
791
792         return false;
793 }
794
795 bool ED_view3d_boundbox_clip_ex(const RegionView3D *rv3d, const BoundBox *bb, float obmat[4][4])
796 {
797         /* return 1: draw */
798
799         float persmatob[4][4];
800
801         if (bb == NULL) return true;
802         if (bb->flag & BOUNDBOX_DISABLED) return true;
803
804         mul_m4_m4m4(persmatob, (float(*)[4])rv3d->persmat, obmat);
805
806         return view3d_boundbox_clip_m4(bb, persmatob);
807 }
808
809 bool ED_view3d_boundbox_clip(RegionView3D *rv3d, const BoundBox *bb)
810 {
811         if (bb == NULL) return true;
812         if (bb->flag & BOUNDBOX_DISABLED) return true;
813
814         return view3d_boundbox_clip_m4(bb, rv3d->persmatob);
815 }
816
817 /* -------------------------------------------------------------------- */
818
819 /** \name Depth Utilities
820  * \{ */
821
822 float ED_view3d_depth_read_cached(const ViewContext *vc, const int mval[2])
823 {
824         ViewDepths *vd = vc->rv3d->depths;
825                 
826         int x = mval[0];
827         int y = mval[1];
828
829         if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h) {
830                 return vd->depths[y * vd->w + x];
831         }
832         else {
833                 BLI_assert(1.0 <= vd->depth_range[1]);
834                 return 1.0f;
835         }
836 }
837
838 bool ED_view3d_depth_read_cached_normal(
839         const ViewContext *vc, const bglMats *mats, const int mval[2],
840         float r_normal[3])
841 {
842         /* Note: we could support passing in a radius.
843          * For now just read 9 pixels. */
844
845         /* pixels surrounding */
846         bool  depths_valid[9] = {false};
847         float coords[9][3] = {{0}};
848
849         ARegion *ar = vc->ar;
850         const ViewDepths *depths = vc->rv3d->depths;
851
852         for (int x = 0, i = 0; x < 2; x++) {
853                 for (int y = 0; y < 2; y++) {
854                         const int mval_ofs[2] = {mval[0] + (x - 1), mval[1] + (y - 1)};
855
856                         const double depth = (double)ED_view3d_depth_read_cached(vc, mval_ofs);
857                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
858                                 if (ED_view3d_depth_unproject(ar, mats, mval_ofs, depth, coords[i])) {
859                                         depths_valid[i] = true;
860                                 }
861                         }
862                         i++;
863                 }
864         }
865
866         const int edges[2][6][2] = {
867             /* x edges */
868             {{0, 1}, {1, 2},
869              {3, 4}, {4, 5},
870              {6, 7}, {7, 8}},
871             /* y edges */
872             {{0, 3}, {3, 6},
873              {1, 4}, {4, 7},
874              {2, 5}, {5, 8}},
875         };
876
877         float cross[2][3] = {{0.0f}};
878
879         for (int i = 0; i < 6; i++) {
880                 for (int axis = 0; axis < 2; axis++) {
881                         if (depths_valid[edges[axis][i][0]] && depths_valid[edges[axis][i][1]]) {
882                                 float delta[3];
883                                 sub_v3_v3v3(delta, coords[edges[axis][i][0]], coords[edges[axis][i][1]]);
884                                 add_v3_v3(cross[axis], delta);
885                         }
886                 }
887         }
888
889         cross_v3_v3v3(r_normal, cross[0], cross[1]);
890
891         if (normalize_v3(r_normal) != 0.0f) {
892                 return true;
893         }
894         else {
895                 return false;
896         }
897 }
898
899 bool ED_view3d_depth_unproject(
900         const ARegion *ar, const bglMats *mats,
901         const int mval[2], const double depth,
902         float r_location_world[3])
903 {
904         double p[3];
905         if (gluUnProject(
906                 (double)ar->winrct.xmin + mval[0] + 0.5,
907                 (double)ar->winrct.ymin + mval[1] + 0.5,
908                 depth, mats->modelview, mats->projection, (const GLint *)mats->viewport,
909                 &p[0], &p[1], &p[2]))
910         {
911                 copy_v3fl_v3db(r_location_world, p);
912                 return true;
913         }
914         return false;
915 }
916
917 /** \} */
918
919 void ED_view3d_depth_tag_update(RegionView3D *rv3d)
920 {
921         if (rv3d->depths)
922                 rv3d->depths->damaged = true;
923 }
924
925 void ED_view3d_dist_range_get(
926         const View3D *v3d,
927         float r_dist_range[2])
928 {
929         r_dist_range[0] = v3d->grid * 0.001f;
930         r_dist_range[1] = v3d->far * 10.0f;
931 }
932
933 /* copies logic of get_view3d_viewplane(), keep in sync */
934 bool ED_view3d_clip_range_get(
935         const View3D *v3d, const RegionView3D *rv3d,
936         float *r_clipsta, float *r_clipend,
937         const bool use_ortho_factor)
938 {
939         CameraParams params;
940
941         BKE_camera_params_init(&params);
942         BKE_camera_params_from_view3d(&params, v3d, rv3d);
943
944         if (use_ortho_factor && params.is_ortho) {
945                 const float fac = 2.0f / (params.clipend - params.clipsta);
946                 params.clipsta *= fac;
947                 params.clipend *= fac;
948         }
949
950         if (r_clipsta) *r_clipsta = params.clipsta;
951         if (r_clipend) *r_clipend = params.clipend;
952
953         return params.is_ortho;
954 }
955
956 bool ED_view3d_viewplane_get(
957         const View3D *v3d, const RegionView3D *rv3d, int winx, int winy,
958         rctf *r_viewplane, float *r_clipsta, float *r_clipend, float *r_pixsize)
959 {
960         CameraParams params;
961
962         BKE_camera_params_init(&params);
963         BKE_camera_params_from_view3d(&params, v3d, rv3d);
964         BKE_camera_params_compute_viewplane(&params, winx, winy, 1.0f, 1.0f);
965
966         if (r_viewplane) *r_viewplane = params.viewplane;
967         if (r_clipsta) *r_clipsta = params.clipsta;
968         if (r_clipend) *r_clipend = params.clipend;
969         if (r_pixsize) *r_pixsize = params.viewdx;
970         
971         return params.is_ortho;
972 }
973
974 /**
975  * Use instead of: ``bglPolygonOffset(rv3d->dist, ...)`` see bug [#37727]
976  */
977 void ED_view3d_polygon_offset(const RegionView3D *rv3d, const float dist)
978 {
979         float viewdist;
980
981         if (rv3d->rflag & RV3D_ZOFFSET_DISABLED) {
982                 return;
983         }
984
985         viewdist = rv3d->dist;
986
987         /* special exception for ortho camera (viewdist isnt used for perspective cameras) */
988         if (dist != 0.0f) {
989                 if (rv3d->persp == RV3D_CAMOB) {
990                         if (rv3d->is_persp == false) {
991                                 viewdist = 1.0f / max_ff(fabsf(rv3d->winmat[0][0]), fabsf(rv3d->winmat[1][1]));
992                         }
993                 }
994         }
995
996         bglPolygonOffset(viewdist, dist);
997 }
998
999 /**
1000  * \param rect optional for picking (can be NULL).
1001  */
1002 void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rcti *rect)
1003 {
1004         RegionView3D *rv3d = ar->regiondata;
1005         rctf viewplane;
1006         float clipsta, clipend;
1007         bool is_ortho;
1008         
1009         is_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend, NULL);
1010         rv3d->is_persp = !is_ortho;
1011
1012 #if 0
1013         printf("%s: %d %d %f %f %f %f %f %f\n", __func__, winx, winy,
1014                viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax,
1015                clipsta, clipend);
1016 #endif
1017
1018         if (rect) {  /* picking */
1019                 rctf r;
1020                 r.xmin = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmin / (float)ar->winx));
1021                 r.ymin = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymin / (float)ar->winy));
1022                 r.xmax = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmax / (float)ar->winx));
1023                 r.ymax = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymax / (float)ar->winy));
1024                 viewplane = r;
1025         }
1026
1027         if (is_ortho) {
1028                 wmOrtho(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
1029         }
1030         else {
1031                 wmFrustum(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
1032         }
1033
1034         /* update matrix in 3d view region */
1035         glGetFloatv(GL_PROJECTION_MATRIX, (float *)rv3d->winmat);
1036 }
1037
1038 static void obmat_to_viewmat(RegionView3D *rv3d, Object *ob)
1039 {
1040         float bmat[4][4];
1041
1042         rv3d->view = RV3D_VIEW_USER; /* don't show the grid */
1043
1044         normalize_m4_m4(bmat, ob->obmat);
1045         invert_m4_m4(rv3d->viewmat, bmat);
1046
1047         /* view quat calculation, needed for add object */
1048         mat4_normalized_to_quat(rv3d->viewquat, rv3d->viewmat);
1049 }
1050
1051 static float view3d_quat_axis[6][4] = {
1052         {M_SQRT1_2, -M_SQRT1_2, 0.0f, 0.0f},    /* RV3D_VIEW_FRONT */
1053         {0.0f, 0.0f, -M_SQRT1_2, -M_SQRT1_2},   /* RV3D_VIEW_BACK */
1054         {0.5f, -0.5f, 0.5f, 0.5f},              /* RV3D_VIEW_LEFT */
1055         {0.5f, -0.5f, -0.5f, -0.5f},            /* RV3D_VIEW_RIGHT */
1056         {1.0f, 0.0f, 0.0f, 0.0f},               /* RV3D_VIEW_TOP */
1057         {0.0f, -1.0f, 0.0f, 0.0f},              /* RV3D_VIEW_BOTTOM */
1058 };
1059
1060
1061 bool ED_view3d_quat_from_axis_view(const char view, float quat[4])
1062 {
1063         if (RV3D_VIEW_IS_AXIS(view)) {
1064                 copy_qt_qt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]);
1065                 return true;
1066         }
1067         else {
1068                 return false;
1069         }
1070 }
1071
1072 char ED_view3d_quat_to_axis_view(const float quat[4], const float epsilon)
1073 {
1074         /* quat values are all unit length */
1075
1076         char view;
1077
1078         for (view = RV3D_VIEW_FRONT; view <= RV3D_VIEW_BOTTOM; view++) {
1079                 if (angle_qtqt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]) < epsilon) {
1080                         return view;
1081                 }
1082         }
1083
1084         return RV3D_VIEW_USER;
1085 }
1086
1087 char ED_view3d_lock_view_from_index(int index)
1088 {
1089         switch (index) {
1090                 case 0:  return RV3D_VIEW_FRONT;
1091                 case 1:  return RV3D_VIEW_TOP;
1092                 case 2:  return RV3D_VIEW_RIGHT;
1093                 default: return RV3D_VIEW_USER;
1094         }
1095
1096 }
1097
1098 char ED_view3d_axis_view_opposite(char view)
1099 {
1100         switch (view) {
1101                 case RV3D_VIEW_FRONT:   return RV3D_VIEW_BACK;
1102                 case RV3D_VIEW_BACK:    return RV3D_VIEW_FRONT;
1103                 case RV3D_VIEW_LEFT:    return RV3D_VIEW_RIGHT;
1104                 case RV3D_VIEW_RIGHT:   return RV3D_VIEW_LEFT;
1105                 case RV3D_VIEW_TOP:     return RV3D_VIEW_BOTTOM;
1106                 case RV3D_VIEW_BOTTOM:  return RV3D_VIEW_TOP;
1107         }
1108
1109         return RV3D_VIEW_USER;
1110 }
1111
1112
1113 bool ED_view3d_lock(RegionView3D *rv3d)
1114 {
1115         return ED_view3d_quat_from_axis_view(rv3d->view, rv3d->viewquat);
1116 }
1117
1118 /* don't set windows active in here, is used by renderwin too */
1119 void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d)
1120 {
1121         if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
1122                 if (v3d->camera) {
1123                         BKE_object_where_is_calc(scene, v3d->camera);
1124                         obmat_to_viewmat(rv3d, v3d->camera);
1125                 }
1126                 else {
1127                         quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
1128                         rv3d->viewmat[3][2] -= rv3d->dist;
1129                 }
1130         }
1131         else {
1132                 bool use_lock_ofs = false;
1133
1134
1135                 /* should be moved to better initialize later on XXX */
1136                 if (rv3d->viewlock & RV3D_LOCKED)
1137                         ED_view3d_lock(rv3d);
1138                 
1139                 quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
1140                 if (rv3d->persp == RV3D_PERSP) rv3d->viewmat[3][2] -= rv3d->dist;
1141                 if (v3d->ob_centre) {
1142                         Object *ob = v3d->ob_centre;
1143                         float vec[3];
1144                         
1145                         copy_v3_v3(vec, ob->obmat[3]);
1146                         if (ob->type == OB_ARMATURE && v3d->ob_centre_bone[0]) {
1147                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, v3d->ob_centre_bone);
1148                                 if (pchan) {
1149                                         copy_v3_v3(vec, pchan->pose_mat[3]);
1150                                         mul_m4_v3(ob->obmat, vec);
1151                                 }
1152                         }
1153                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
1154                         use_lock_ofs = true;
1155                 }
1156                 else if (v3d->ob_centre_cursor) {
1157                         float vec[3];
1158                         copy_v3_v3(vec, ED_view3d_cursor3d_get(scene, (View3D *)v3d));
1159                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
1160                         use_lock_ofs = true;
1161                 }
1162                 else {
1163                         translate_m4(rv3d->viewmat, rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2]);
1164                 }
1165
1166                 /* lock offset */
1167                 if (use_lock_ofs) {
1168                         float persmat[4][4], persinv[4][4];
1169                         float vec[3];
1170
1171                         /* we could calculate the real persmat/persinv here
1172                          * but it would be unreliable so better to later */
1173                         mul_m4_m4m4(persmat, rv3d->winmat, rv3d->viewmat);
1174                         invert_m4_m4(persinv, persmat);
1175
1176                         mul_v2_v2fl(vec, rv3d->ofs_lock, rv3d->is_persp ? rv3d->dist : 1.0f);
1177                         vec[2] = 0.0f;
1178                         mul_mat3_m4_v3(persinv, vec);
1179                         translate_m4(rv3d->viewmat, vec[0], vec[1], vec[2]);
1180                 }
1181                 /* end lock offset */
1182         }
1183 }
1184
1185 /**
1186  * Optionally cache data for multiple calls to #view3d_opengl_select
1187  *
1188  * just avoid GPU_select headers outside this file
1189  */
1190 void view3d_opengl_select_cache_begin(void)
1191 {
1192         GPU_select_cache_begin();
1193 }
1194
1195 void view3d_opengl_select_cache_end(void)
1196 {
1197         GPU_select_cache_end();
1198 }
1199
1200 /**
1201  * \warning be sure to account for a negative return value
1202  * This is an error, "Too many objects in select buffer"
1203  * and no action should be taken (can crash blender) if this happens
1204  *
1205  * \note (vc->obedit == NULL) can be set to explicitly skip edit-object selection.
1206  */
1207 int view3d_opengl_select(
1208         ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input,
1209         eV3DSelectMode select_mode)
1210 {
1211         struct bThemeState theme_state;
1212         Scene *scene = vc->scene;
1213         View3D *v3d = vc->v3d;
1214         ARegion *ar = vc->ar;
1215         rcti rect;
1216         int hits;
1217         const bool use_obedit_skip = (scene->obedit != NULL) && (vc->obedit == NULL);
1218         const bool is_pick_select = (U.gpu_select_pick_deph != 0);
1219         const bool do_passes = (
1220                 (is_pick_select == false) &&
1221                 (select_mode == VIEW3D_SELECT_PICK_NEAREST) &&
1222                 GPU_select_query_check_active());
1223         const bool use_nearest = (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST);
1224
1225         char gpu_select_mode;
1226
1227         /* case not a border select */
1228         if (input->xmin == input->xmax) {
1229                 /* seems to be default value for bones only now */
1230                 BLI_rcti_init_pt_radius(&rect, (const int[2]){input->xmin, input->ymin}, 12);
1231         }
1232         else {
1233                 rect = *input;
1234         }
1235
1236         if (is_pick_select) {
1237                 if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST) {
1238                         gpu_select_mode = GPU_SELECT_PICK_NEAREST;
1239                 }
1240                 else if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_ALL) {
1241                         gpu_select_mode = GPU_SELECT_PICK_ALL;
1242                 }
1243                 else {
1244                         gpu_select_mode = GPU_SELECT_ALL;
1245                 }
1246         }
1247         else {
1248                 if (do_passes) {
1249                         gpu_select_mode = GPU_SELECT_NEAREST_FIRST_PASS;
1250                 }
1251                 else {
1252                         gpu_select_mode = GPU_SELECT_ALL;
1253                 }
1254         }
1255
1256         /* Tools may request depth outside of regular drawing code. */
1257         UI_Theme_Store(&theme_state);
1258         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
1259
1260         /* Re-use cache (rect must be smaller then the cached)
1261          * other context is assumed to be unchanged */
1262         if (GPU_select_is_cached()) {
1263                 GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
1264                 GPU_select_cache_load_id();
1265                 hits = GPU_select_end();
1266                 goto finally;
1267         }
1268
1269         G.f |= G_PICKSEL;
1270
1271         /* Important we use the 'viewmat' and don't re-calculate since
1272          * the object & bone view locking takes 'rect' into account, see: T51629. */
1273         ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, &rect);
1274
1275         if (v3d->drawtype > OB_WIRE) {
1276                 v3d->zbuf = true;
1277                 glEnable(GL_DEPTH_TEST);
1278         }
1279         
1280         if (vc->rv3d->rflag & RV3D_CLIPPING)
1281                 ED_view3d_clipping_set(vc->rv3d);
1282         
1283         GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
1284
1285         ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
1286
1287         hits = GPU_select_end();
1288         
1289         /* second pass, to get the closest object to camera */
1290         if (do_passes && (hits > 0)) {
1291                 GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
1292
1293                 ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
1294
1295                 GPU_select_end();
1296         }
1297
1298         G.f &= ~G_PICKSEL;
1299         ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, NULL);
1300         
1301         if (v3d->drawtype > OB_WIRE) {
1302                 v3d->zbuf = 0;
1303                 glDisable(GL_DEPTH_TEST);
1304         }
1305         
1306         if (vc->rv3d->rflag & RV3D_CLIPPING)
1307                 ED_view3d_clipping_disable();
1308
1309 finally:
1310         if (hits < 0) printf("Too many objects in select buffer\n");  /* XXX make error message */
1311
1312         UI_Theme_Restore(&theme_state);
1313
1314         return hits;
1315 }
1316
1317 /* ********************** local view operator ******************** */
1318
1319 static unsigned int free_localbit(Main *bmain)
1320 {
1321         unsigned int lay;
1322         ScrArea *sa;
1323         bScreen *sc;
1324         
1325         lay = 0;
1326         
1327         /* sometimes we loose a localview: when an area is closed */
1328         /* check all areas: which localviews are in use? */
1329         for (sc = bmain->screen.first; sc; sc = sc->id.next) {
1330                 for (sa = sc->areabase.first; sa; sa = sa->next) {
1331                         SpaceLink *sl = sa->spacedata.first;
1332                         for (; sl; sl = sl->next) {
1333                                 if (sl->spacetype == SPACE_VIEW3D) {
1334                                         View3D *v3d = (View3D *) sl;
1335                                         lay |= v3d->lay;
1336                                 }
1337                         }
1338                 }
1339         }
1340         
1341         if ((lay & 0x01000000) == 0) return 0x01000000;
1342         if ((lay & 0x02000000) == 0) return 0x02000000;
1343         if ((lay & 0x04000000) == 0) return 0x04000000;
1344         if ((lay & 0x08000000) == 0) return 0x08000000;
1345         if ((lay & 0x10000000) == 0) return 0x10000000;
1346         if ((lay & 0x20000000) == 0) return 0x20000000;
1347         if ((lay & 0x40000000) == 0) return 0x40000000;
1348         if ((lay & 0x80000000) == 0) return 0x80000000;
1349         
1350         return 0;
1351 }
1352
1353 int ED_view3d_scene_layer_set(int lay, const int *values, int *active)
1354 {
1355         int i, tot = 0;
1356         
1357         /* ensure we always have some layer selected */
1358         for (i = 0; i < 20; i++)
1359                 if (values[i])
1360                         tot++;
1361         
1362         if (tot == 0)
1363                 return lay;
1364         
1365         for (i = 0; i < 20; i++) {
1366                 
1367                 if (active) {
1368                         /* if this value has just been switched on, make that layer active */
1369                         if (values[i] && (lay & (1 << i)) == 0) {
1370                                 *active = (1 << i);
1371                         }
1372                 }
1373                         
1374                 if (values[i]) lay |= (1 << i);
1375                 else lay &= ~(1 << i);
1376         }
1377         
1378         /* ensure always an active layer */
1379         if (active && (lay & *active) == 0) {
1380                 for (i = 0; i < 20; i++) {
1381                         if (lay & (1 << i)) {
1382                                 *active = 1 << i;
1383                                 break;
1384                         }
1385                 }
1386         }
1387         
1388         return lay;
1389 }
1390
1391 static bool view3d_localview_init(
1392         wmWindowManager *wm, wmWindow *win,
1393         Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx,
1394         ReportList *reports)
1395 {
1396         View3D *v3d = sa->spacedata.first;
1397         Base *base;
1398         float min[3], max[3], box[3], mid[3];
1399         float size = 0.0f;
1400         unsigned int locallay;
1401         bool ok = false;
1402
1403         if (v3d->localvd) {
1404                 return ok;
1405         }
1406
1407         INIT_MINMAX(min, max);
1408
1409         locallay = free_localbit(bmain);
1410
1411         if (locallay == 0) {
1412                 BKE_report(reports, RPT_ERROR, "No more than 8 local views");
1413                 ok = false;
1414         }
1415         else {
1416                 if (scene->obedit) {
1417                         BKE_object_minmax(scene->obedit, min, max, false);
1418                         
1419                         ok = true;
1420                 
1421                         BASACT->lay |= locallay;
1422                         scene->obedit->lay = BASACT->lay;
1423                 }
1424                 else {
1425                         for (base = FIRSTBASE; base; base = base->next) {
1426                                 if (TESTBASE(v3d, base)) {
1427                                         BKE_object_minmax(base->object, min, max, false);
1428                                         base->lay |= locallay;
1429                                         base->object->lay = base->lay;
1430                                         ok = true;
1431                                 }
1432                         }
1433                 }
1434
1435                 sub_v3_v3v3(box, max, min);
1436                 size = max_fff(box[0], box[1], box[2]);
1437         }
1438         
1439         if (ok == true) {
1440                 ARegion *ar;
1441                 
1442                 v3d->localvd = MEM_mallocN(sizeof(View3D), "localview");
1443                 
1444                 memcpy(v3d->localvd, v3d, sizeof(View3D));
1445
1446                 mid_v3_v3v3(mid, min, max);
1447
1448                 copy_v3_v3(v3d->cursor, mid);
1449
1450                 for (ar = sa->regionbase.first; ar; ar = ar->next) {
1451                         if (ar->regiontype == RGN_TYPE_WINDOW) {
1452                                 RegionView3D *rv3d = ar->regiondata;
1453                                 bool ok_dist = true;
1454
1455                                 /* new view values */
1456                                 Object *camera_old = NULL;
1457                                 float dist_new, ofs_new[3];
1458
1459                                 rv3d->localvd = MEM_mallocN(sizeof(RegionView3D), "localview region");
1460                                 memcpy(rv3d->localvd, rv3d, sizeof(RegionView3D));
1461
1462                                 negate_v3_v3(ofs_new, mid);
1463
1464                                 if (rv3d->persp == RV3D_CAMOB) {
1465                                         rv3d->persp = RV3D_PERSP;
1466                                         camera_old = v3d->camera;
1467                                 }
1468
1469                                 if (rv3d->persp == RV3D_ORTHO) {
1470                                         if (size < 0.0001f) {
1471                                                 ok_dist = false;
1472                                         }
1473                                 }
1474
1475                                 if (ok_dist) {
1476                                         dist_new = ED_view3d_radius_to_dist(v3d, ar, rv3d->persp, true, (size / 2) * VIEW3D_MARGIN);
1477                                         if (rv3d->persp == RV3D_PERSP) {
1478                                                 /* don't zoom closer than the near clipping plane */
1479                                                 dist_new = max_ff(dist_new, v3d->near * 1.5f);
1480                                         }
1481                                 }
1482
1483                                 ED_view3d_smooth_view_ex(
1484                                         wm, win, sa, v3d, ar, smooth_viewtx,
1485                                             &(const V3D_SmoothParams) {
1486                                                 .camera_old = camera_old,
1487                                                 .ofs = ofs_new, .quat = rv3d->viewquat,
1488                                                 .dist = ok_dist ? &dist_new : NULL, .lens = &v3d->lens});
1489                         }
1490                 }
1491                 
1492                 v3d->lay = locallay;
1493         }
1494         else {
1495                 /* clear flags */ 
1496                 for (base = FIRSTBASE; base; base = base->next) {
1497                         if (base->lay & locallay) {
1498                                 base->lay -= locallay;
1499                                 if (base->lay == 0) base->lay = v3d->layact;
1500                                 if (base->object != scene->obedit) base->flag |= SELECT;
1501                                 base->object->lay = base->lay;
1502                         }
1503                 }
1504         }
1505
1506         DAG_on_visible_update(bmain, false);
1507
1508         return ok;
1509 }
1510
1511 static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx)
1512 {
1513         const bool free = true;
1514         ARegion *ar;
1515         View3D *v3d = sa->spacedata.first;
1516         Object *camera_old, *camera_new;
1517         
1518         if (v3d->localvd == NULL) return;
1519         
1520         camera_old = v3d->camera;
1521         camera_new = v3d->localvd->camera;
1522
1523         v3d->near = v3d->localvd->near;
1524         v3d->far = v3d->localvd->far;
1525         v3d->lay = v3d->localvd->lay;
1526         v3d->layact = v3d->localvd->layact;
1527         v3d->drawtype = v3d->localvd->drawtype;
1528         v3d->camera = v3d->localvd->camera;
1529         
1530         if (free) {
1531                 MEM_freeN(v3d->localvd);
1532                 v3d->localvd = NULL;
1533         }
1534         
1535         for (ar = sa->regionbase.first; ar; ar = ar->next) {
1536                 if (ar->regiontype == RGN_TYPE_WINDOW) {
1537                         RegionView3D *rv3d = ar->regiondata;
1538                         
1539                         if (rv3d->localvd) {
1540                                 Object *camera_old_rv3d, *camera_new_rv3d;
1541
1542                                 camera_old_rv3d = (rv3d->persp          == RV3D_CAMOB) ? camera_old : NULL;
1543                                 camera_new_rv3d = (rv3d->localvd->persp == RV3D_CAMOB) ? camera_new : NULL;
1544
1545                                 rv3d->view = rv3d->localvd->view;
1546                                 rv3d->persp = rv3d->localvd->persp;
1547                                 rv3d->camzoom = rv3d->localvd->camzoom;
1548
1549                                 ED_view3d_smooth_view_ex(
1550                                         wm, win, sa,
1551                                         v3d, ar, smooth_viewtx,
1552                                         &(const V3D_SmoothParams) {
1553                                             .camera_old = camera_old_rv3d, .camera = camera_new_rv3d,
1554                                             .ofs = rv3d->localvd->ofs, .quat = rv3d->localvd->viewquat,
1555                                             .dist = &rv3d->localvd->dist});
1556
1557                                 if (free) {
1558                                         MEM_freeN(rv3d->localvd);
1559                                         rv3d->localvd = NULL;
1560                                 }
1561                         }
1562
1563                         ED_view3d_shade_update(bmain, scene, v3d, sa);
1564                 }
1565         }
1566 }
1567
1568 static bool view3d_localview_exit(
1569         wmWindowManager *wm, wmWindow *win,
1570         Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx)
1571 {
1572         View3D *v3d = sa->spacedata.first;
1573         struct Base *base;
1574         unsigned int locallay;
1575         
1576         if (v3d->localvd) {
1577                 
1578                 locallay = v3d->lay & 0xFF000000;
1579
1580                 restore_localviewdata(wm, win, bmain, scene, sa, smooth_viewtx);
1581
1582                 /* for when in other window the layers have changed */
1583                 if (v3d->scenelock) v3d->lay = scene->lay;
1584                 
1585                 for (base = FIRSTBASE; base; base = base->next) {
1586                         if (base->lay & locallay) {
1587                                 base->lay -= locallay;
1588                                 if (base->lay == 0) base->lay = v3d->layact;
1589                                 if (base->object != scene->obedit) {
1590                                         base->flag |= SELECT;
1591                                         base->object->flag |= SELECT;
1592                                 }
1593                                 base->object->lay = base->lay;
1594                         }
1595                 }
1596                 
1597                 DAG_on_visible_update(bmain, false);
1598
1599                 return true;
1600         }
1601         else {
1602                 return false;
1603         }
1604 }
1605
1606 static int localview_exec(bContext *C, wmOperator *op)
1607 {
1608         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
1609         wmWindowManager *wm = CTX_wm_manager(C);
1610         wmWindow *win = CTX_wm_window(C);
1611         Main *bmain = CTX_data_main(C);
1612         Scene *scene = CTX_data_scene(C);
1613         ScrArea *sa = CTX_wm_area(C);
1614         View3D *v3d = CTX_wm_view3d(C);
1615         bool changed;
1616         
1617         if (v3d->localvd) {
1618                 changed = view3d_localview_exit(wm, win, bmain, scene, sa, smooth_viewtx);
1619         }
1620         else {
1621                 changed = view3d_localview_init(wm, win, bmain, scene, sa, smooth_viewtx, op->reports);
1622         }
1623
1624         if (changed) {
1625                 DAG_id_type_tag(bmain, ID_OB);
1626                 ED_area_tag_redraw(sa);
1627
1628                 /* unselected objects become selected when exiting */
1629                 if (v3d->localvd == NULL) {
1630                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1631                 }
1632
1633                 return OPERATOR_FINISHED;
1634         }
1635         else {
1636                 return OPERATOR_CANCELLED;
1637         }
1638 }
1639
1640 void VIEW3D_OT_localview(wmOperatorType *ot)
1641 {
1642         /* identifiers */
1643         ot->name = "Local View";
1644         ot->description = "Toggle display of selected object(s) separately and centered in view";
1645         ot->idname = "VIEW3D_OT_localview";
1646         
1647         /* api callbacks */
1648         ot->exec = localview_exec;
1649         ot->flag = OPTYPE_UNDO; /* localview changes object layer bitflags */
1650         
1651         ot->poll = ED_operator_view3d_active;
1652 }
1653
1654 #ifdef WITH_GAMEENGINE
1655
1656 static ListBase queue_back;
1657 static void SaveState(bContext *C, wmWindow *win)
1658 {
1659         Object *obact = CTX_data_active_object(C);
1660         
1661         glPushAttrib(GL_ALL_ATTRIB_BITS);
1662
1663         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1664                 GPU_paint_set_mipmap(1);
1665         
1666         queue_back = win->queue;
1667         
1668         BLI_listbase_clear(&win->queue);
1669         
1670         //XXX waitcursor(1);
1671 }
1672
1673 static void RestoreState(bContext *C, wmWindow *win)
1674 {
1675         Object *obact = CTX_data_active_object(C);
1676         
1677         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1678                 GPU_paint_set_mipmap(0);
1679
1680         //XXX curarea->win_swap = 0;
1681         //XXX curarea->head_swap = 0;
1682         //XXX allqueue(REDRAWVIEW3D, 1);
1683         //XXX allqueue(REDRAWBUTSALL, 0);
1684         //XXX reset_slowparents();
1685         //XXX waitcursor(0);
1686         //XXX G.qual = 0;
1687         
1688         if (win) /* check because closing win can set to NULL */
1689                 win->queue = queue_back;
1690         
1691         GPU_state_init();
1692         GPU_set_tpage(NULL, 0, 0);
1693
1694         glPopAttrib();
1695 }
1696
1697 /* was space_set_commmandline_options in 2.4x */
1698 static void game_set_commmandline_options(GameData *gm)
1699 {
1700         SYS_SystemHandle syshandle;
1701         int test;
1702
1703         if ((syshandle = SYS_GetSystem())) {
1704                 /* User defined settings */
1705                 test = (U.gameflags & USER_DISABLE_MIPMAP);
1706                 GPU_set_mipmap(!test);
1707                 SYS_WriteCommandLineInt(syshandle, "nomipmap", test);
1708
1709                 /* File specific settings: */
1710                 /* Only test the first one. These two are switched
1711                  * simultaneously. */
1712                 test = (gm->flag & GAME_SHOW_FRAMERATE);
1713                 SYS_WriteCommandLineInt(syshandle, "show_framerate", test);
1714                 SYS_WriteCommandLineInt(syshandle, "show_profile", test);
1715
1716                 test = (gm->flag & GAME_SHOW_DEBUG_PROPS);
1717                 SYS_WriteCommandLineInt(syshandle, "show_properties", test);
1718
1719                 test = (gm->flag & GAME_SHOW_PHYSICS);
1720                 SYS_WriteCommandLineInt(syshandle, "show_physics", test);
1721
1722                 test = (gm->flag & GAME_ENABLE_ALL_FRAMES);
1723                 SYS_WriteCommandLineInt(syshandle, "fixedtime", test);
1724
1725                 test = (gm->flag & GAME_ENABLE_ANIMATION_RECORD);
1726                 SYS_WriteCommandLineInt(syshandle, "animation_record", test);
1727
1728                 test = (gm->flag & GAME_IGNORE_DEPRECATION_WARNINGS);
1729                 SYS_WriteCommandLineInt(syshandle, "ignore_deprecation_warnings", test);
1730
1731                 test = (gm->matmode == GAME_MAT_MULTITEX);
1732                 SYS_WriteCommandLineInt(syshandle, "blender_material", test);
1733                 test = (gm->matmode == GAME_MAT_GLSL);
1734                 SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", test);
1735                 test = (gm->flag & GAME_DISPLAY_LISTS);
1736                 SYS_WriteCommandLineInt(syshandle, "displaylists", test);
1737
1738
1739         }
1740 }
1741
1742 #endif /* WITH_GAMEENGINE */
1743
1744 static int game_engine_poll(bContext *C)
1745 {
1746         bScreen *screen;
1747         /* we need a context and area to launch BGE
1748          * it's a temporary solution to avoid crash at load time
1749          * if we try to auto run the BGE. Ideally we want the
1750          * context to be set as soon as we load the file. */
1751
1752         if (CTX_wm_window(C) == NULL) return 0;
1753         if ((screen = CTX_wm_screen(C)) == NULL) return 0;
1754
1755         if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT)
1756                 return 0;
1757
1758         if (!BKE_scene_uses_blender_game(screen->scene))
1759                 return 0;
1760
1761         return 1;
1762 }
1763
1764 bool ED_view3d_context_activate(bContext *C)
1765 {
1766         bScreen *sc = CTX_wm_screen(C);
1767         ScrArea *sa = CTX_wm_area(C);
1768         ARegion *ar;
1769
1770         /* sa can be NULL when called from python */
1771         if (sa == NULL || sa->spacetype != SPACE_VIEW3D) {
1772                 sa = BKE_screen_find_big_area(sc, SPACE_VIEW3D, 0);
1773         }
1774
1775         if (sa == NULL) {
1776                 return false;
1777         }
1778         
1779         ar = BKE_area_find_region_active_win(sa);
1780         if (ar == NULL) {
1781                 return false;
1782         }
1783         
1784         /* bad context switch .. */
1785         CTX_wm_area_set(C, sa);
1786         CTX_wm_region_set(C, ar);
1787
1788         return true;
1789 }
1790
1791 static int game_engine_exec(bContext *C, wmOperator *op)
1792 {
1793 #ifdef WITH_GAMEENGINE
1794         Scene *startscene = CTX_data_scene(C);
1795         Main *bmain = CTX_data_main(C);
1796         ScrArea /* *sa, */ /* UNUSED */ *prevsa = CTX_wm_area(C);
1797         ARegion *ar, *prevar = CTX_wm_region(C);
1798         wmWindow *prevwin = CTX_wm_window(C);
1799         RegionView3D *rv3d;
1800         rcti cam_frame;
1801
1802         (void)op; /* unused */
1803         
1804         /* bad context switch .. */
1805         if (!ED_view3d_context_activate(C))
1806                 return OPERATOR_CANCELLED;
1807         
1808         /* redraw to hide any menus/popups, we don't go back to
1809          * the window manager until after this operator exits */
1810         WM_redraw_windows(C);
1811
1812         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_PRE);
1813
1814         rv3d = CTX_wm_region_view3d(C);
1815         /* sa = CTX_wm_area(C); */ /* UNUSED */
1816         ar = CTX_wm_region(C);
1817
1818         view3d_operator_needs_opengl(C);
1819         
1820         game_set_commmandline_options(&startscene->gm);
1821
1822         if ((rv3d->persp == RV3D_CAMOB) &&
1823             (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) &&
1824             (startscene->gm.stereoflag != STEREO_DOME))
1825         {
1826                 /* Letterbox */
1827                 rctf cam_framef;
1828                 ED_view3d_calc_camera_border(startscene, ar, CTX_wm_view3d(C), rv3d, &cam_framef, false);
1829                 cam_frame.xmin = cam_framef.xmin + ar->winrct.xmin;
1830                 cam_frame.xmax = cam_framef.xmax + ar->winrct.xmin;
1831                 cam_frame.ymin = cam_framef.ymin + ar->winrct.ymin;
1832                 cam_frame.ymax = cam_framef.ymax + ar->winrct.ymin;
1833                 BLI_rcti_isect(&ar->winrct, &cam_frame, &cam_frame);
1834         }
1835         else {
1836                 cam_frame.xmin = ar->winrct.xmin;
1837                 cam_frame.xmax = ar->winrct.xmax;
1838                 cam_frame.ymin = ar->winrct.ymin;
1839                 cam_frame.ymax = ar->winrct.ymax;
1840         }
1841
1842
1843         SaveState(C, prevwin);
1844
1845         StartKetsjiShell(C, ar, &cam_frame, 1);
1846
1847         /* window wasnt closed while the BGE was running */
1848         if (BLI_findindex(&CTX_wm_manager(C)->windows, prevwin) == -1) {
1849                 prevwin = NULL;
1850                 CTX_wm_window_set(C, NULL);
1851         }
1852         
1853         ED_area_tag_redraw(CTX_wm_area(C));
1854
1855         if (prevwin) {
1856                 /* restore context, in case it changed in the meantime, for
1857                  * example by working in another window or closing it */
1858                 CTX_wm_region_set(C, prevar);
1859                 CTX_wm_window_set(C, prevwin);
1860                 CTX_wm_area_set(C, prevsa);
1861         }
1862
1863         RestoreState(C, prevwin);
1864
1865         //XXX restore_all_scene_cfra(scene_cfra_store);
1866         BKE_scene_set_background(CTX_data_main(C), startscene);
1867         //XXX BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene, scene->lay);
1868
1869         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_POST);
1870
1871         return OPERATOR_FINISHED;
1872 #else
1873         (void)C; /* unused */
1874         BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build");
1875         return OPERATOR_CANCELLED;
1876 #endif
1877 }
1878
1879 void VIEW3D_OT_game_start(wmOperatorType *ot)
1880 {
1881         
1882         /* identifiers */
1883         ot->name = "Start Game Engine";
1884         ot->description = "Start game engine";
1885         ot->idname = "VIEW3D_OT_game_start";
1886         
1887         /* api callbacks */
1888         ot->exec = game_engine_exec;
1889         
1890         ot->poll = game_engine_poll;
1891 }
1892
1893 /* ************************************** */
1894
1895 float ED_view3d_pixel_size(const RegionView3D *rv3d, const float co[3])
1896 {
1897         return mul_project_m4_v3_zfac((float(*)[4])rv3d->persmat, co) * rv3d->pixsize * U.pixelsize;
1898 }
1899
1900 float ED_view3d_radius_to_dist_persp(const float angle, const float radius)
1901 {
1902         return radius * (1.0f / tanf(angle / 2.0f));
1903 }
1904
1905 float ED_view3d_radius_to_dist_ortho(const float lens, const float radius)
1906 {
1907         return radius / (DEFAULT_SENSOR_WIDTH / lens);
1908 }
1909
1910 /**
1911  * Return a new RegionView3D.dist value to fit the \a radius.
1912  *
1913  * \note Depth isn't taken into account, this will fit a flat plane exactly,
1914  * but points towards the view (with a perspective projection),
1915  * may be within the radius but outside the view. eg:
1916  *
1917  * <pre>
1918  *           +
1919  * pt --> + /^ radius
1920  *         / |
1921  *        /  |
1922  * view  +   +
1923  *        \  |
1924  *         \ |
1925  *          \|
1926  *           +
1927  * </pre>
1928  *
1929  * \param ar  Can be NULL if \a use_aspect is false.
1930  * \param persp  Allow the caller to tell what kind of perspective to use (ortho/view/camera)
1931  * \param use_aspect  Increase the distance to account for non 1:1 view aspect.
1932  * \param radius  The radius will be fitted exactly, typically pre-scaled by a margin (#VIEW3D_MARGIN).
1933  */
1934 float ED_view3d_radius_to_dist(
1935         const View3D *v3d, const ARegion *ar,
1936         const char persp, const bool use_aspect,
1937         const float radius)
1938 {
1939         float dist;
1940
1941         BLI_assert(ELEM(persp, RV3D_ORTHO, RV3D_PERSP, RV3D_CAMOB));
1942         BLI_assert((persp != RV3D_CAMOB) || v3d->camera);
1943
1944         if (persp == RV3D_ORTHO) {
1945                 dist = ED_view3d_radius_to_dist_ortho(v3d->lens, radius);
1946         }
1947         else {
1948                 float lens, sensor_size, zoom;
1949                 float angle;
1950
1951                 if (persp == RV3D_CAMOB) {
1952                         CameraParams params;
1953                         BKE_camera_params_init(&params);
1954                         params.clipsta = v3d->near;
1955                         params.clipend = v3d->far;
1956                         BKE_camera_params_from_object(&params, v3d->camera);
1957
1958                         lens = params.lens;
1959                         sensor_size = BKE_camera_sensor_size(params.sensor_fit, params.sensor_x, params.sensor_y);
1960
1961                         /* ignore 'rv3d->camzoom' because we want to fit to the cameras frame */
1962                         zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB;
1963                 }
1964                 else {
1965                         lens = v3d->lens;
1966                         sensor_size = DEFAULT_SENSOR_WIDTH;
1967                         zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
1968                 }
1969
1970                 angle = focallength_to_fov(lens, sensor_size);
1971
1972                 /* zoom influences lens, correct this by scaling the angle as a distance (by the zoom-level) */
1973                 angle = atanf(tanf(angle / 2.0f) * zoom) * 2.0f;
1974
1975                 dist = ED_view3d_radius_to_dist_persp(angle, radius);
1976         }
1977
1978         if (use_aspect) {
1979                 const RegionView3D *rv3d = ar->regiondata;
1980
1981                 float winx, winy;
1982
1983                 if (persp == RV3D_CAMOB) {
1984                         /* camera frame x/y in pixels */
1985                         winx = ar->winx / rv3d->viewcamtexcofac[0];
1986                         winy = ar->winy / rv3d->viewcamtexcofac[1];
1987                 }
1988                 else {
1989                         winx = ar->winx;
1990                         winy = ar->winy;
1991                 }
1992
1993                 if (winx && winy) {
1994                         float aspect = winx / winy;
1995                         if (aspect < 1.0f) {
1996                                 aspect = 1.0f / aspect;
1997                         }
1998                         dist *= aspect;
1999                 }
2000         }
2001
2002         return dist;
2003 }
2004
2005 /* view matrix properties utilities */
2006
2007 /* unused */
2008 #if 0
2009 void ED_view3d_operator_properties_viewmat(wmOperatorType *ot)
2010 {
2011         PropertyRNA *prop;
2012
2013         prop = RNA_def_int(ot->srna, "region_width", 0, 0, INT_MAX, "Region Width", "", 0, INT_MAX);
2014         RNA_def_property_flag(prop, PROP_HIDDEN);
2015
2016         prop = RNA_def_int(ot->srna, "region_height", 0, 0, INT_MAX, "Region height", "", 0, INT_MAX);
2017         RNA_def_property_flag(prop, PROP_HIDDEN);
2018
2019         prop = RNA_def_float_matrix(ot->srna, "perspective_matrix", 4, 4, NULL, 0.0f, 0.0f, "", "Perspective Matrix", 0.0f, 0.0f);
2020         RNA_def_property_flag(prop, PROP_HIDDEN);
2021 }
2022
2023 void ED_view3d_operator_properties_viewmat_set(bContext *C, wmOperator *op)
2024 {
2025         ARegion *ar = CTX_wm_region(C);
2026         RegionView3D *rv3d = ED_view3d_context_rv3d(C);
2027
2028         if (!RNA_struct_property_is_set(op->ptr, "region_width"))
2029                 RNA_int_set(op->ptr, "region_width", ar->winx);
2030
2031         if (!RNA_struct_property_is_set(op->ptr, "region_height"))
2032                 RNA_int_set(op->ptr, "region_height", ar->winy);
2033
2034         if (!RNA_struct_property_is_set(op->ptr, "perspective_matrix"))
2035                 RNA_float_set_array(op->ptr, "perspective_matrix", (float *)rv3d->persmat);
2036 }
2037
2038 void ED_view3d_operator_properties_viewmat_get(wmOperator *op, int *winx, int *winy, float persmat[4][4])
2039 {
2040         *winx = RNA_int_get(op->ptr, "region_width");
2041         *winy = RNA_int_get(op->ptr, "region_height");
2042
2043         RNA_float_get_array(op->ptr, "perspective_matrix", (float *)persmat);
2044 }
2045 #endif