Merge branch 'master' into blender2.8
[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_object.h"
47 #include "BKE_global.h"
48 #include "BKE_main.h"
49 #include "BKE_report.h"
50 #include "BKE_scene.h"
51 #include "BKE_screen.h"
52
53 #include "DEG_depsgraph.h"
54
55 #include "BIF_glutil.h"
56
57 #include "GPU_glew.h"
58 #include "GPU_select.h"
59 #include "GPU_matrix.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 #include "DRW_engine.h"
68
69
70 #ifdef WITH_GAMEENGINE
71 #  include "BLI_listbase.h"
72 #  include "BLI_callbacks.h"
73
74 #  include "GPU_draw.h"
75
76 #  include "BL_System.h"
77 #endif
78
79
80 #include "view3d_intern.h"  /* own include */
81
82 /* use this call when executing an operator,
83  * event system doesn't set for each event the
84  * opengl drawing context */
85 void view3d_operator_needs_opengl(const bContext *C)
86 {
87         wmWindow *win = CTX_wm_window(C);
88         ARegion *ar = CTX_wm_region(C);
89         
90         view3d_region_operator_needs_opengl(win, ar);
91 }
92
93 void view3d_region_operator_needs_opengl(wmWindow *win, ARegion *ar)
94 {
95         /* for debugging purpose, context should always be OK */
96         if ((ar == NULL) || (ar->regiontype != RGN_TYPE_WINDOW)) {
97                 printf("view3d_region_operator_needs_opengl error, wrong region\n");
98         }
99         else {
100                 RegionView3D *rv3d = ar->regiondata;
101                 
102                 wmSubWindowSet(win, ar->swinid);
103                 gpuLoadProjectionMatrix(rv3d->winmat);
104                 gpuLoadMatrix(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         EvaluationContext eval_ctx;
447
448         CTX_data_eval_ctx(C, &eval_ctx);
449
450         if (rv3d && rv3d->sms) {
451                 rv3d->sms->time_allowed = 0.0;  /* force finishing */
452                 view3d_smoothview_apply(C, v3d, ar, false);
453
454                 /* force update of view matrix so tools that run immediately after
455                  * can use them without redrawing first */
456                 Scene *scene = CTX_data_scene(C);
457                 ED_view3d_update_viewmat(&eval_ctx, scene, v3d, ar, NULL, NULL, NULL);
458         }
459 }
460
461 void VIEW3D_OT_smoothview(wmOperatorType *ot)
462 {
463         
464         /* identifiers */
465         ot->name = "Smooth View";
466         ot->description = "";
467         ot->idname = "VIEW3D_OT_smoothview";
468         
469         /* api callbacks */
470         ot->invoke = view3d_smoothview_invoke;
471         
472         /* flags */
473         ot->flag = OPTYPE_INTERNAL;
474
475         ot->poll = ED_operator_view3d_active;
476 }
477
478 /* ****************** change view operators ****************** */
479
480 static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
481 {
482         View3D *v3d;
483         ARegion *ar;
484         RegionView3D *rv3d;
485
486         ObjectTfmProtectedChannels obtfm;
487
488         ED_view3d_context_user_region(C, &v3d, &ar);
489         rv3d = ar->regiondata;
490
491         ED_view3d_lastview_store(rv3d);
492
493         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
494
495         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
496
497         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag);
498
499         DEG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
500         rv3d->persp = RV3D_CAMOB;
501         
502         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, v3d->camera);
503         
504         return OPERATOR_FINISHED;
505
506 }
507
508 static int view3d_camera_to_view_poll(bContext *C)
509 {
510         View3D *v3d;
511         ARegion *ar;
512
513         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
514                 RegionView3D *rv3d = ar->regiondata;
515                 if (v3d && v3d->camera && !ID_IS_LINKED_DATABLOCK(v3d->camera)) {
516                         if (rv3d && (rv3d->viewlock & RV3D_LOCKED) == 0) {
517                                 if (rv3d->persp != RV3D_CAMOB) {
518                                         return 1;
519                                 }
520                         }
521                 }
522         }
523
524         return 0;
525 }
526
527 void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
528 {
529         /* identifiers */
530         ot->name = "Align Camera To View";
531         ot->description = "Set camera view to active view";
532         ot->idname = "VIEW3D_OT_camera_to_view";
533         
534         /* api callbacks */
535         ot->exec = view3d_camera_to_view_exec;
536         ot->poll = view3d_camera_to_view_poll;
537         
538         /* flags */
539         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
540 }
541
542 /* unlike VIEW3D_OT_view_selected this is for framing a render and not
543  * meant to take into account vertex/bone selection for eg. */
544 static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *op)
545 {
546         Scene *scene = CTX_data_scene(C);
547         SceneLayer *sl = CTX_data_scene_layer(C);
548         View3D *v3d = CTX_wm_view3d(C);  /* can be NULL */
549         Object *camera_ob = v3d ? v3d->camera : scene->camera;
550
551         float r_co[3]; /* the new location to apply */
552         float r_scale; /* only for ortho cameras */
553
554         if (camera_ob == NULL) {
555                 BKE_report(op->reports, RPT_ERROR, "No active camera");
556                 return OPERATOR_CANCELLED;
557         }
558
559         /* this function does all the important stuff */
560         if (BKE_camera_view_frame_fit_to_scene(scene, sl, camera_ob, r_co, &r_scale)) {
561                 ObjectTfmProtectedChannels obtfm;
562                 float obmat_new[4][4];
563
564                 if ((camera_ob->type == OB_CAMERA) && (((Camera *)camera_ob->data)->type == CAM_ORTHO)) {
565                         ((Camera *)camera_ob->data)->ortho_scale = r_scale;
566                 }
567
568                 copy_m4_m4(obmat_new, camera_ob->obmat);
569                 copy_v3_v3(obmat_new[3], r_co);
570
571                 /* only touch location */
572                 BKE_object_tfm_protected_backup(camera_ob, &obtfm);
573                 BKE_object_apply_mat4(camera_ob, obmat_new, true, true);
574                 BKE_object_tfm_protected_restore(camera_ob, &obtfm, OB_LOCK_SCALE | OB_LOCK_ROT4D);
575
576                 /* notifiers */
577                 DEG_id_tag_update(&camera_ob->id, OB_RECALC_OB);
578                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, camera_ob);
579                 return OPERATOR_FINISHED;
580         }
581         else {
582                 return OPERATOR_CANCELLED;
583         }
584 }
585
586 void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
587 {
588         /* identifiers */
589         ot->name = "Camera Fit Frame to Selected";
590         ot->description = "Move the camera so selected objects are framed";
591         ot->idname = "VIEW3D_OT_camera_to_view_selected";
592
593         /* api callbacks */
594         ot->exec = view3d_camera_to_view_selected_exec;
595         ot->poll = ED_operator_scene_editable;
596
597         /* flags */
598         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
599 }
600
601 static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob, const int smooth_viewtx)
602 {
603         Main *bmain = CTX_data_main(C);
604         for (bScreen *screen = bmain->screen.first; screen != NULL; screen = screen->id.next) {
605                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
606                         for (SpaceLink *space_link = area->spacedata.first; space_link != NULL; space_link = space_link->next) {
607                                 if (space_link->spacetype == SPACE_VIEW3D) {
608                                         View3D *other_v3d = (View3D *)space_link;
609                                         if (other_v3d == v3d) {
610                                                 continue;
611                                         }
612                                         if (other_v3d->camera == ob) {
613                                                 continue;
614                                         }
615                                         if (v3d->scenelock) {
616                                                 ListBase *lb = (space_link == area->spacedata.first)
617                                                                    ? &area->regionbase
618                                                                    : &space_link->regionbase;
619                                                 for (ARegion *other_ar = lb->first; other_ar != NULL; other_ar = other_ar->next) {
620                                                         if (other_ar->regiontype == RGN_TYPE_WINDOW) {
621                                                                 if (other_ar->regiondata) {
622                                                                         RegionView3D *other_rv3d = other_ar->regiondata;
623                                                                         if (other_rv3d->persp == RV3D_CAMOB) {
624                                                                                 Object *other_camera_old = other_v3d->camera;
625                                                                                 other_v3d->camera = ob;
626                                                                                 ED_view3d_lastview_store(other_rv3d);
627                                                                                 ED_view3d_smooth_view(
628                                                                                         C, other_v3d, other_ar, smooth_viewtx,
629                                                                                         &(const V3D_SmoothParams) {
630                                                                                             .camera_old = other_camera_old,
631                                                                                             .camera = other_v3d->camera,
632                                                                                             .ofs = other_rv3d->ofs,
633                                                                                             .quat = other_rv3d->viewquat,
634                                                                                             .dist = &other_rv3d->dist,
635                                                                                             .lens = &other_v3d->lens});
636                                                                         }
637                                                                         else {
638                                                                                 other_v3d->camera = ob;
639                                                                         }
640                                                                 }
641                                                         }
642                                                 }
643                                         }
644                                 }
645                         }
646                 }
647         }
648 }
649
650 static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op)
651 {       
652         View3D *v3d;
653         ARegion *ar;
654         RegionView3D *rv3d;
655
656         Scene *scene = CTX_data_scene(C);
657         Object *ob = CTX_data_active_object(C);
658
659         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
660
661         /* no NULL check is needed, poll checks */
662         ED_view3d_context_user_region(C, &v3d, &ar);
663         rv3d = ar->regiondata;
664
665         if (ob) {
666                 Object *camera_old = (rv3d->persp == RV3D_CAMOB) ? V3D_CAMERA_SCENE(scene, v3d) : NULL;
667                 rv3d->persp = RV3D_CAMOB;
668                 v3d->camera = ob;
669                 if (v3d->scenelock)
670                         scene->camera = ob;
671
672                 /* unlikely but looks like a glitch when set to the same */
673                 if (camera_old != ob) {
674                         ED_view3d_lastview_store(rv3d);
675
676                         ED_view3d_smooth_view(
677                                 C, v3d, ar, smooth_viewtx,
678                                 &(const V3D_SmoothParams) {
679                                     .camera_old = camera_old, .camera = v3d->camera,
680                                     .ofs = rv3d->ofs, .quat = rv3d->viewquat,
681                                     .dist = &rv3d->dist, .lens = &v3d->lens});
682                 }
683
684                 if (v3d->scenelock) {
685                         sync_viewport_camera_smoothview(C, v3d, ob, smooth_viewtx);
686                         WM_event_add_notifier(C, NC_SCENE, scene);
687                 }
688                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
689         }
690         
691         return OPERATOR_FINISHED;
692 }
693
694 int ED_operator_rv3d_user_region_poll(bContext *C)
695 {
696         View3D *v3d_dummy;
697         ARegion *ar_dummy;
698
699         return ED_view3d_context_user_region(C, &v3d_dummy, &ar_dummy);
700 }
701
702 void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
703 {
704         
705         /* identifiers */
706         ot->name = "Set Active Object as Camera";
707         ot->description = "Set the active object as the active camera for this view or scene";
708         ot->idname = "VIEW3D_OT_object_as_camera";
709         
710         /* api callbacks */
711         ot->exec = view3d_setobjectascamera_exec;
712         ot->poll = ED_operator_rv3d_user_region_poll;
713         
714         /* flags */
715         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
716 }
717
718 /* ********************************** */
719
720 void ED_view3d_clipping_calc_from_boundbox(float clip[4][4], const BoundBox *bb, const bool is_flip)
721 {
722         int val;
723
724         for (val = 0; val < 4; val++) {
725                 normal_tri_v3(clip[val], bb->vec[val], bb->vec[val == 3 ? 0 : val + 1], bb->vec[val + 4]);
726                 if (UNLIKELY(is_flip)) {
727                         negate_v3(clip[val]);
728                 }
729
730                 clip[val][3] = -dot_v3v3(clip[val], bb->vec[val]);
731         }
732 }
733
734 void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], const ARegion *ar, const Object *ob, const rcti *rect)
735 {
736         /* init in case unproject fails */
737         memset(bb->vec, 0, sizeof(bb->vec));
738
739         /* four clipping planes and bounding volume */
740         /* first do the bounding volume */
741         for (int val = 0; val < 4; val++) {
742                 float xs = (val == 0 || val == 3) ? rect->xmin : rect->xmax;
743                 float ys = (val == 0 || val == 1) ? rect->ymin : rect->ymax;
744
745                 ED_view3d_unproject(ar, xs, ys, 0.0, bb->vec[val]);
746                 ED_view3d_unproject(ar, xs, ys, 1.0, bb->vec[4 + val]);
747         }
748
749         /* optionally transform to object space */
750         if (ob) {
751                 float imat[4][4];
752                 invert_m4_m4(imat, ob->obmat);
753
754                 for (int val = 0; val < 8; val++) {
755                         mul_m4_v3(imat, bb->vec[val]);
756                 }
757         }
758
759         /* verify if we have negative scale. doing the transform before cross
760          * product flips the sign of the vector compared to doing cross product
761          * before transform then, so we correct for that. */
762         int flip_sign = (ob) ? is_negative_m4(ob->obmat) : false;
763
764         ED_view3d_clipping_calc_from_boundbox(planes, bb, flip_sign);
765 }
766
767 static bool view3d_boundbox_clip_m4(const BoundBox *bb, float persmatob[4][4])
768 {
769         int a, flag = -1, fl;
770
771         for (a = 0; a < 8; a++) {
772                 float vec[4], min, max;
773                 copy_v3_v3(vec, bb->vec[a]);
774                 vec[3] = 1.0;
775                 mul_m4_v4(persmatob, vec);
776                 max = vec[3];
777                 min = -vec[3];
778
779                 fl = 0;
780                 if (vec[0] < min) fl += 1;
781                 if (vec[0] > max) fl += 2;
782                 if (vec[1] < min) fl += 4;
783                 if (vec[1] > max) fl += 8;
784                 if (vec[2] < min) fl += 16;
785                 if (vec[2] > max) fl += 32;
786
787                 flag &= fl;
788                 if (flag == 0) return true;
789         }
790
791         return false;
792 }
793
794 bool ED_view3d_boundbox_clip_ex(const RegionView3D *rv3d, const BoundBox *bb, float obmat[4][4])
795 {
796         /* return 1: draw */
797
798         float persmatob[4][4];
799
800         if (bb == NULL) return true;
801         if (bb->flag & BOUNDBOX_DISABLED) return true;
802
803         mul_m4_m4m4(persmatob, (float(*)[4])rv3d->persmat, obmat);
804
805         return view3d_boundbox_clip_m4(bb, persmatob);
806 }
807
808 bool ED_view3d_boundbox_clip(RegionView3D *rv3d, const BoundBox *bb)
809 {
810         if (bb == NULL) return true;
811         if (bb->flag & BOUNDBOX_DISABLED) return true;
812
813         return view3d_boundbox_clip_m4(bb, rv3d->persmatob);
814 }
815
816 /* -------------------------------------------------------------------- */
817
818 /** \name Depth Utilities
819  * \{ */
820
821 float ED_view3d_depth_read_cached(const ViewContext *vc, const int mval[2])
822 {
823         ViewDepths *vd = vc->rv3d->depths;
824                 
825         int x = mval[0];
826         int y = mval[1];
827
828         if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h) {
829                 return vd->depths[y * vd->w + x];
830         }
831         else {
832                 BLI_assert(1.0 <= vd->depth_range[1]);
833                 return 1.0f;
834         }
835 }
836
837 bool ED_view3d_depth_read_cached_normal(
838         const ViewContext *vc, const int mval[2],
839         float r_normal[3])
840 {
841         /* Note: we could support passing in a radius.
842          * For now just read 9 pixels. */
843
844         /* pixels surrounding */
845         bool  depths_valid[9] = {false};
846         float coords[9][3] = {{0}};
847
848         ARegion *ar = vc->ar;
849         const ViewDepths *depths = vc->rv3d->depths;
850
851         for (int x = 0, i = 0; x < 2; x++) {
852                 for (int y = 0; y < 2; y++) {
853                         const int mval_ofs[2] = {mval[0] + (x - 1), mval[1] + (y - 1)};
854
855                         const double depth = (double)ED_view3d_depth_read_cached(vc, mval_ofs);
856                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
857                                 if (ED_view3d_depth_unproject(ar, mval_ofs, depth, coords[i])) {
858                                         depths_valid[i] = true;
859                                 }
860                         }
861                         i++;
862                 }
863         }
864
865         const int edges[2][6][2] = {
866             /* x edges */
867             {{0, 1}, {1, 2},
868              {3, 4}, {4, 5},
869              {6, 7}, {7, 8}},
870             /* y edges */
871             {{0, 3}, {3, 6},
872              {1, 4}, {4, 7},
873              {2, 5}, {5, 8}},
874         };
875
876         float cross[2][3] = {{0.0f}};
877
878         for (int i = 0; i < 6; i++) {
879                 for (int axis = 0; axis < 2; axis++) {
880                         if (depths_valid[edges[axis][i][0]] && depths_valid[edges[axis][i][1]]) {
881                                 float delta[3];
882                                 sub_v3_v3v3(delta, coords[edges[axis][i][0]], coords[edges[axis][i][1]]);
883                                 add_v3_v3(cross[axis], delta);
884                         }
885                 }
886         }
887
888         cross_v3_v3v3(r_normal, cross[0], cross[1]);
889
890         if (normalize_v3(r_normal) != 0.0f) {
891                 return true;
892         }
893         else {
894                 return false;
895         }
896 }
897
898 bool ED_view3d_depth_unproject(
899         const ARegion *ar,
900         const int mval[2], const double depth,
901         float r_location_world[3])
902 {
903         float centx = (float)mval[0] + 0.5f;
904         float centy = (float)mval[1] + 0.5f;
905         return ED_view3d_unproject(ar, centx, centy, depth, r_location_world);
906 }
907
908 /** \} */
909
910 void ED_view3d_depth_tag_update(RegionView3D *rv3d)
911 {
912         if (rv3d->depths)
913                 rv3d->depths->damaged = true;
914 }
915
916 void ED_view3d_dist_range_get(
917         const View3D *v3d,
918         float r_dist_range[2])
919 {
920         r_dist_range[0] = v3d->grid * 0.001f;
921         r_dist_range[1] = v3d->far * 10.0f;
922 }
923
924 /* copies logic of get_view3d_viewplane(), keep in sync */
925 bool ED_view3d_clip_range_get(
926         const View3D *v3d, const RegionView3D *rv3d,
927         float *r_clipsta, float *r_clipend,
928         const bool use_ortho_factor)
929 {
930         CameraParams params;
931
932         BKE_camera_params_init(&params);
933         BKE_camera_params_from_view3d(&params, v3d, rv3d);
934
935         if (use_ortho_factor && params.is_ortho) {
936                 const float fac = 2.0f / (params.clipend - params.clipsta);
937                 params.clipsta *= fac;
938                 params.clipend *= fac;
939         }
940
941         if (r_clipsta) *r_clipsta = params.clipsta;
942         if (r_clipend) *r_clipend = params.clipend;
943
944         return params.is_ortho;
945 }
946
947 bool ED_view3d_viewplane_get(
948         const View3D *v3d, const RegionView3D *rv3d, int winx, int winy,
949         rctf *r_viewplane, float *r_clipsta, float *r_clipend, float *r_pixsize)
950 {
951         CameraParams params;
952
953         BKE_camera_params_init(&params);
954         BKE_camera_params_from_view3d(&params, v3d, rv3d);
955         BKE_camera_params_compute_viewplane(&params, winx, winy, 1.0f, 1.0f);
956
957         if (r_viewplane) *r_viewplane = params.viewplane;
958         if (r_clipsta) *r_clipsta = params.clipsta;
959         if (r_clipend) *r_clipend = params.clipend;
960         if (r_pixsize) *r_pixsize = params.viewdx;
961         
962         return params.is_ortho;
963 }
964
965 /**
966  * Use instead of: ``bglPolygonOffset(rv3d->dist, ...)`` see bug [#37727]
967  */
968 void ED_view3d_polygon_offset(const RegionView3D *rv3d, const float dist)
969 {
970         float viewdist;
971
972         if (rv3d->rflag & RV3D_ZOFFSET_DISABLED) {
973                 return;
974         }
975
976         viewdist = rv3d->dist;
977
978         /* special exception for ortho camera (viewdist isnt used for perspective cameras) */
979         if (dist != 0.0f) {
980                 if (rv3d->persp == RV3D_CAMOB) {
981                         if (rv3d->is_persp == false) {
982                                 viewdist = 1.0f / max_ff(fabsf(rv3d->winmat[0][0]), fabsf(rv3d->winmat[1][1]));
983                         }
984                 }
985         }
986
987         bglPolygonOffset(viewdist, dist);
988 }
989
990 /**
991  * \param rect optional for picking (can be NULL).
992  */
993 void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rcti *rect)
994 {
995         RegionView3D *rv3d = ar->regiondata;
996         rctf viewplane;
997         float clipsta, clipend;
998         bool is_ortho;
999         
1000         is_ortho = ED_view3d_viewplane_get(v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend, NULL);
1001         rv3d->is_persp = !is_ortho;
1002
1003 #if 0
1004         printf("%s: %d %d %f %f %f %f %f %f\n", __func__, winx, winy,
1005                viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax,
1006                clipsta, clipend);
1007 #endif
1008
1009         if (rect) {  /* picking */
1010                 rctf r;
1011                 r.xmin = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmin / (float)ar->winx));
1012                 r.ymin = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymin / (float)ar->winy));
1013                 r.xmax = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmax / (float)ar->winx));
1014                 r.ymax = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymax / (float)ar->winy));
1015                 viewplane = r;
1016         }
1017
1018         if (is_ortho) {
1019                 gpuOrtho(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
1020         }
1021         else {
1022                 gpuFrustum(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
1023         }
1024
1025         /* update matrix in 3d view region */
1026         gpuGetProjectionMatrix(rv3d->winmat);
1027 }
1028
1029 static void obmat_to_viewmat(RegionView3D *rv3d, Object *ob)
1030 {
1031         float bmat[4][4];
1032
1033         rv3d->view = RV3D_VIEW_USER; /* don't show the grid */
1034
1035         normalize_m4_m4(bmat, ob->obmat);
1036         invert_m4_m4(rv3d->viewmat, bmat);
1037
1038         /* view quat calculation, needed for add object */
1039         mat4_normalized_to_quat(rv3d->viewquat, rv3d->viewmat);
1040 }
1041
1042 static float view3d_quat_axis[6][4] = {
1043         {M_SQRT1_2, -M_SQRT1_2, 0.0f, 0.0f},    /* RV3D_VIEW_FRONT */
1044         {0.0f, 0.0f, -M_SQRT1_2, -M_SQRT1_2},   /* RV3D_VIEW_BACK */
1045         {0.5f, -0.5f, 0.5f, 0.5f},              /* RV3D_VIEW_LEFT */
1046         {0.5f, -0.5f, -0.5f, -0.5f},            /* RV3D_VIEW_RIGHT */
1047         {1.0f, 0.0f, 0.0f, 0.0f},               /* RV3D_VIEW_TOP */
1048         {0.0f, -1.0f, 0.0f, 0.0f},              /* RV3D_VIEW_BOTTOM */
1049 };
1050
1051
1052 bool ED_view3d_quat_from_axis_view(const char view, float quat[4])
1053 {
1054         if (RV3D_VIEW_IS_AXIS(view)) {
1055                 copy_qt_qt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]);
1056                 return true;
1057         }
1058         else {
1059                 return false;
1060         }
1061 }
1062
1063 char ED_view3d_quat_to_axis_view(const float quat[4], const float epsilon)
1064 {
1065         /* quat values are all unit length */
1066
1067         char view;
1068
1069         for (view = RV3D_VIEW_FRONT; view <= RV3D_VIEW_BOTTOM; view++) {
1070                 if (angle_qtqt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]) < epsilon) {
1071                         return view;
1072                 }
1073         }
1074
1075         return RV3D_VIEW_USER;
1076 }
1077
1078 char ED_view3d_lock_view_from_index(int index)
1079 {
1080         switch (index) {
1081                 case 0:  return RV3D_VIEW_FRONT;
1082                 case 1:  return RV3D_VIEW_TOP;
1083                 case 2:  return RV3D_VIEW_RIGHT;
1084                 default: return RV3D_VIEW_USER;
1085         }
1086
1087 }
1088
1089 char ED_view3d_axis_view_opposite(char view)
1090 {
1091         switch (view) {
1092                 case RV3D_VIEW_FRONT:   return RV3D_VIEW_BACK;
1093                 case RV3D_VIEW_BACK:    return RV3D_VIEW_FRONT;
1094                 case RV3D_VIEW_LEFT:    return RV3D_VIEW_RIGHT;
1095                 case RV3D_VIEW_RIGHT:   return RV3D_VIEW_LEFT;
1096                 case RV3D_VIEW_TOP:     return RV3D_VIEW_BOTTOM;
1097                 case RV3D_VIEW_BOTTOM:  return RV3D_VIEW_TOP;
1098         }
1099
1100         return RV3D_VIEW_USER;
1101 }
1102
1103
1104 bool ED_view3d_lock(RegionView3D *rv3d)
1105 {
1106         return ED_view3d_quat_from_axis_view(rv3d->view, rv3d->viewquat);
1107 }
1108
1109 /* don't set windows active in here, is used by renderwin too */
1110 void view3d_viewmatrix_set(const EvaluationContext *eval_ctx, Scene *scene, const View3D *v3d, RegionView3D *rv3d)
1111 {
1112         if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
1113                 if (v3d->camera) {
1114                         BKE_object_where_is_calc(eval_ctx, scene, v3d->camera);
1115                         obmat_to_viewmat(rv3d, v3d->camera);
1116                 }
1117                 else {
1118                         quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
1119                         rv3d->viewmat[3][2] -= rv3d->dist;
1120                 }
1121         }
1122         else {
1123                 bool use_lock_ofs = false;
1124
1125
1126                 /* should be moved to better initialize later on XXX */
1127                 if (rv3d->viewlock & RV3D_LOCKED)
1128                         ED_view3d_lock(rv3d);
1129                 
1130                 quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
1131                 if (rv3d->persp == RV3D_PERSP) rv3d->viewmat[3][2] -= rv3d->dist;
1132                 if (v3d->ob_centre) {
1133                         Object *ob = v3d->ob_centre;
1134                         float vec[3];
1135                         
1136                         copy_v3_v3(vec, ob->obmat[3]);
1137                         if (ob->type == OB_ARMATURE && v3d->ob_centre_bone[0]) {
1138                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, v3d->ob_centre_bone);
1139                                 if (pchan) {
1140                                         copy_v3_v3(vec, pchan->pose_mat[3]);
1141                                         mul_m4_v3(ob->obmat, vec);
1142                                 }
1143                         }
1144                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
1145                         use_lock_ofs = true;
1146                 }
1147                 else if (v3d->ob_centre_cursor) {
1148                         float vec[3];
1149                         copy_v3_v3(vec, ED_view3d_cursor3d_get(scene, (View3D *)v3d));
1150                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
1151                         use_lock_ofs = true;
1152                 }
1153                 else {
1154                         translate_m4(rv3d->viewmat, rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2]);
1155                 }
1156
1157                 /* lock offset */
1158                 if (use_lock_ofs) {
1159                         float persmat[4][4], persinv[4][4];
1160                         float vec[3];
1161
1162                         /* we could calculate the real persmat/persinv here
1163                          * but it would be unreliable so better to later */
1164                         mul_m4_m4m4(persmat, rv3d->winmat, rv3d->viewmat);
1165                         invert_m4_m4(persinv, persmat);
1166
1167                         mul_v2_v2fl(vec, rv3d->ofs_lock, rv3d->is_persp ? rv3d->dist : 1.0f);
1168                         vec[2] = 0.0f;
1169                         mul_mat3_m4_v3(persinv, vec);
1170                         translate_m4(rv3d->viewmat, vec[0], vec[1], vec[2]);
1171                 }
1172                 /* end lock offset */
1173         }
1174 }
1175
1176 /**
1177  * Optionally cache data for multiple calls to #view3d_opengl_select
1178  *
1179  * just avoid GPU_select headers outside this file
1180  */
1181 void view3d_opengl_select_cache_begin(void)
1182 {
1183         GPU_select_cache_begin();
1184 }
1185
1186 void view3d_opengl_select_cache_end(void)
1187 {
1188         GPU_select_cache_end();
1189 }
1190
1191 /**
1192  * \warning be sure to account for a negative return value
1193  * This is an error, "Too many objects in select buffer"
1194  * and no action should be taken (can crash blender) if this happens
1195  *
1196  * \note (vc->obedit == NULL) can be set to explicitly skip edit-object selection.
1197  */
1198 int view3d_opengl_select(
1199         const EvaluationContext *eval_ctx, ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input,
1200         eV3DSelectMode select_mode)
1201 {
1202         Depsgraph *graph = vc->depsgraph;
1203         Scene *scene = vc->scene;
1204         View3D *v3d = vc->v3d;
1205         ARegion *ar = vc->ar;
1206         rcti rect;
1207         int hits;
1208         const bool use_obedit_skip = (scene->obedit != NULL) && (vc->obedit == NULL);
1209         const bool is_pick_select = (U.gpu_select_pick_deph != 0);
1210         const bool do_passes = (
1211                 (is_pick_select == false) &&
1212                 (select_mode == VIEW3D_SELECT_PICK_NEAREST) &&
1213                 GPU_select_query_check_active());
1214         const bool use_nearest = (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST);
1215
1216         char gpu_select_mode;
1217
1218         /* case not a border select */
1219         if (input->xmin == input->xmax) {
1220                 /* seems to be default value for bones only now */
1221                 BLI_rcti_init_pt_radius(&rect, (const int[2]){input->xmin, input->ymin}, 12);
1222         }
1223         else {
1224                 rect = *input;
1225         }
1226
1227         if (is_pick_select) {
1228                 if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST) {
1229                         gpu_select_mode = GPU_SELECT_PICK_NEAREST;
1230                 }
1231                 else if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_ALL) {
1232                         gpu_select_mode = GPU_SELECT_PICK_ALL;
1233                 }
1234                 else {
1235                         gpu_select_mode = GPU_SELECT_ALL;
1236                 }
1237         }
1238         else {
1239                 if (do_passes) {
1240                         gpu_select_mode = GPU_SELECT_NEAREST_FIRST_PASS;
1241                 }
1242                 else {
1243                         gpu_select_mode = GPU_SELECT_ALL;
1244                 }
1245         }
1246
1247         /* Re-use cache (rect must be smaller then the cached)
1248          * other context is assumed to be unchanged */
1249         if (GPU_select_is_cached()) {
1250                 GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
1251                 GPU_select_cache_load_id();
1252                 hits = GPU_select_end();
1253                 goto finally;
1254         }
1255
1256         G.f |= G_PICKSEL;
1257
1258         /* Important we use the 'viewmat' and don't re-calculate since
1259          * the object & bone view locking takes 'rect' into account, see: T51629. */
1260         ED_view3d_draw_setup_view(vc->win, eval_ctx, scene, ar, v3d, vc->rv3d->viewmat, NULL, &rect);
1261
1262         if (v3d->drawtype > OB_WIRE) {
1263                 v3d->zbuf = true;
1264                 glEnable(GL_DEPTH_TEST);
1265         }
1266         
1267         if (vc->rv3d->rflag & RV3D_CLIPPING)
1268                 ED_view3d_clipping_set(vc->rv3d);
1269         
1270         GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
1271
1272 #ifdef WITH_OPENGL_LEGACY
1273         if (IS_VIEWPORT_LEGACY(vc->v3d)) {
1274                 ED_view3d_draw_select_loop(vc, scene, sl, v3d, ar, use_obedit_skip, use_nearest);
1275         }
1276         else
1277 #else
1278         {
1279                 DRW_draw_select_loop(graph, ar, v3d, use_obedit_skip, use_nearest, &rect);
1280         }
1281 #endif /* WITH_OPENGL_LEGACY */
1282
1283         hits = GPU_select_end();
1284         
1285         /* second pass, to get the closest object to camera */
1286         if (do_passes && (hits > 0)) {
1287                 GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
1288
1289 #ifdef WITH_OPENGL_LEGACY
1290                 if (IS_VIEWPORT_LEGACY(vc->v3d)) {
1291                         ED_view3d_draw_select_loop(vc, scene, sl, v3d, ar, use_obedit_skip, use_nearest);
1292                 }
1293                 else
1294 #else
1295                 {
1296                         DRW_draw_select_loop(graph, ar, v3d, use_obedit_skip, use_nearest, &rect);
1297                 }
1298 #endif /* WITH_OPENGL_LEGACY */
1299
1300                 GPU_select_end();
1301         }
1302
1303         G.f &= ~G_PICKSEL;
1304         ED_view3d_draw_setup_view(vc->win, eval_ctx, scene, ar, v3d, vc->rv3d->viewmat, NULL, NULL);
1305         
1306         if (v3d->drawtype > OB_WIRE) {
1307                 v3d->zbuf = 0;
1308                 glDisable(GL_DEPTH_TEST);
1309         }
1310         
1311         if (vc->rv3d->rflag & RV3D_CLIPPING)
1312                 ED_view3d_clipping_disable();
1313
1314 finally:
1315         if (hits < 0) printf("Too many objects in select buffer\n");  /* XXX make error message */
1316
1317         return hits;
1318 }
1319
1320 int ED_view3d_scene_layer_set(int lay, const int *values, int *active)
1321 {
1322         int i, tot = 0;
1323         
1324         /* ensure we always have some layer selected */
1325         for (i = 0; i < 20; i++)
1326                 if (values[i])
1327                         tot++;
1328         
1329         if (tot == 0)
1330                 return lay;
1331         
1332         for (i = 0; i < 20; i++) {
1333                 
1334                 if (active) {
1335                         /* if this value has just been switched on, make that layer active */
1336                         if (values[i] && (lay & (1 << i)) == 0) {
1337                                 *active = (1 << i);
1338                         }
1339                 }
1340                         
1341                 if (values[i]) lay |= (1 << i);
1342                 else lay &= ~(1 << i);
1343         }
1344         
1345         /* ensure always an active layer */
1346         if (active && (lay & *active) == 0) {
1347                 for (i = 0; i < 20; i++) {
1348                         if (lay & (1 << i)) {
1349                                 *active = 1 << i;
1350                                 break;
1351                         }
1352                 }
1353         }
1354         
1355         return lay;
1356 }
1357
1358 #ifdef WITH_GAMEENGINE
1359
1360 static ListBase queue_back;
1361 static void SaveState(bContext *C, wmWindow *win)
1362 {
1363         Object *obact = CTX_data_active_object(C);
1364         
1365         glPushAttrib(GL_ALL_ATTRIB_BITS);
1366
1367         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1368                 GPU_paint_set_mipmap(1);
1369         
1370         queue_back = win->queue;
1371         
1372         BLI_listbase_clear(&win->queue);
1373         
1374         //XXX waitcursor(1);
1375 }
1376
1377 static void RestoreState(bContext *C, wmWindow *win)
1378 {
1379         Object *obact = CTX_data_active_object(C);
1380         
1381         if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
1382                 GPU_paint_set_mipmap(0);
1383
1384         //XXX curarea->win_swap = 0;
1385         //XXX curarea->head_swap = 0;
1386         //XXX allqueue(REDRAWVIEW3D, 1);
1387         //XXX allqueue(REDRAWBUTSALL, 0);
1388         //XXX reset_slowparents();
1389         //XXX waitcursor(0);
1390         //XXX G.qual = 0;
1391         
1392         if (win) /* check because closing win can set to NULL */
1393                 win->queue = queue_back;
1394         
1395         GPU_state_init();
1396
1397         glPopAttrib();
1398 }
1399
1400 /* was space_set_commmandline_options in 2.4x */
1401 static void game_set_commmandline_options(GameData *gm)
1402 {
1403         SYS_SystemHandle syshandle;
1404         int test;
1405
1406         if ((syshandle = SYS_GetSystem())) {
1407                 /* User defined settings */
1408                 test = (U.gameflags & USER_DISABLE_MIPMAP);
1409                 GPU_set_mipmap(!test);
1410                 SYS_WriteCommandLineInt(syshandle, "nomipmap", test);
1411
1412                 /* File specific settings: */
1413                 /* Only test the first one. These two are switched
1414                  * simultaneously. */
1415                 test = (gm->flag & GAME_SHOW_FRAMERATE);
1416                 SYS_WriteCommandLineInt(syshandle, "show_framerate", test);
1417                 SYS_WriteCommandLineInt(syshandle, "show_profile", test);
1418
1419                 test = (gm->flag & GAME_SHOW_DEBUG_PROPS);
1420                 SYS_WriteCommandLineInt(syshandle, "show_properties", test);
1421
1422                 test = (gm->flag & GAME_SHOW_PHYSICS);
1423                 SYS_WriteCommandLineInt(syshandle, "show_physics", test);
1424
1425                 test = (gm->flag & GAME_ENABLE_ALL_FRAMES);
1426                 SYS_WriteCommandLineInt(syshandle, "fixedtime", test);
1427
1428                 test = (gm->flag & GAME_ENABLE_ANIMATION_RECORD);
1429                 SYS_WriteCommandLineInt(syshandle, "animation_record", test);
1430
1431                 test = (gm->flag & GAME_IGNORE_DEPRECATION_WARNINGS);
1432                 SYS_WriteCommandLineInt(syshandle, "ignore_deprecation_warnings", test);
1433
1434                 test = (gm->matmode == GAME_MAT_MULTITEX);
1435                 SYS_WriteCommandLineInt(syshandle, "blender_material", test);
1436                 test = (gm->matmode == GAME_MAT_GLSL);
1437                 SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", test);
1438         }
1439 }
1440
1441 #endif /* WITH_GAMEENGINE */
1442
1443 static int game_engine_poll(bContext *C)
1444 {
1445         const wmWindow *win = CTX_wm_window(C);
1446         const Scene *scene = WM_window_get_active_scene(win);
1447
1448         /* we need a context and area to launch BGE
1449          * it's a temporary solution to avoid crash at load time
1450          * if we try to auto run the BGE. Ideally we want the
1451          * context to be set as soon as we load the file. */
1452
1453         if (win == NULL) return 0;
1454         if (CTX_wm_screen(C) == NULL) return 0;
1455
1456         if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT)
1457                 return 0;
1458
1459         if (!BKE_scene_uses_blender_game(scene))
1460                 return 0;
1461
1462         return 1;
1463 }
1464
1465 bool ED_view3d_context_activate(bContext *C)
1466 {
1467         bScreen *sc = CTX_wm_screen(C);
1468         ScrArea *sa = CTX_wm_area(C);
1469         ARegion *ar;
1470
1471         /* sa can be NULL when called from python */
1472         if (sa == NULL || sa->spacetype != SPACE_VIEW3D) {
1473                 sa = BKE_screen_find_big_area(sc, SPACE_VIEW3D, 0);
1474         }
1475
1476         if (sa == NULL) {
1477                 return false;
1478         }
1479         
1480         ar = BKE_area_find_region_active_win(sa);
1481         if (ar == NULL) {
1482                 return false;
1483         }
1484         
1485         /* bad context switch .. */
1486         CTX_wm_area_set(C, sa);
1487         CTX_wm_region_set(C, ar);
1488
1489         return true;
1490 }
1491
1492 static int game_engine_exec(bContext *C, wmOperator *op)
1493 {
1494 #ifdef WITH_GAMEENGINE
1495         Scene *startscene = CTX_data_scene(C);
1496         Main *bmain = CTX_data_main(C);
1497         ScrArea /* *sa, */ /* UNUSED */ *prevsa = CTX_wm_area(C);
1498         ARegion *ar, *prevar = CTX_wm_region(C);
1499         wmWindow *prevwin = CTX_wm_window(C);
1500         RegionView3D *rv3d;
1501         rcti cam_frame;
1502
1503         (void)op; /* unused */
1504         
1505         /* bad context switch .. */
1506         if (!ED_view3d_context_activate(C))
1507                 return OPERATOR_CANCELLED;
1508         
1509         /* redraw to hide any menus/popups, we don't go back to
1510          * the window manager until after this operator exits */
1511         WM_redraw_windows(C);
1512
1513         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_PRE);
1514
1515         rv3d = CTX_wm_region_view3d(C);
1516         /* sa = CTX_wm_area(C); */ /* UNUSED */
1517         ar = CTX_wm_region(C);
1518
1519         view3d_operator_needs_opengl(C);
1520         
1521         game_set_commmandline_options(&startscene->gm);
1522
1523         if ((rv3d->persp == RV3D_CAMOB) &&
1524             (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) &&
1525             (startscene->gm.stereoflag != STEREO_DOME))
1526         {
1527                 /* Letterbox */
1528                 rctf cam_framef;
1529                 ED_view3d_calc_camera_border(startscene, ar, CTX_wm_view3d(C), rv3d, &cam_framef, false);
1530                 cam_frame.xmin = cam_framef.xmin + ar->winrct.xmin;
1531                 cam_frame.xmax = cam_framef.xmax + ar->winrct.xmin;
1532                 cam_frame.ymin = cam_framef.ymin + ar->winrct.ymin;
1533                 cam_frame.ymax = cam_framef.ymax + ar->winrct.ymin;
1534                 BLI_rcti_isect(&ar->winrct, &cam_frame, &cam_frame);
1535         }
1536         else {
1537                 cam_frame.xmin = ar->winrct.xmin;
1538                 cam_frame.xmax = ar->winrct.xmax;
1539                 cam_frame.ymin = ar->winrct.ymin;
1540                 cam_frame.ymax = ar->winrct.ymax;
1541         }
1542
1543
1544         SaveState(C, prevwin);
1545
1546         StartKetsjiShell(C, ar, &cam_frame, 1);
1547
1548         /* window wasnt closed while the BGE was running */
1549         if (BLI_findindex(&CTX_wm_manager(C)->windows, prevwin) == -1) {
1550                 prevwin = NULL;
1551                 CTX_wm_window_set(C, NULL);
1552         }
1553         
1554         ED_area_tag_redraw(CTX_wm_area(C));
1555
1556         if (prevwin) {
1557                 /* restore context, in case it changed in the meantime, for
1558                  * example by working in another window or closing it */
1559                 CTX_wm_region_set(C, prevar);
1560                 CTX_wm_window_set(C, prevwin);
1561                 CTX_wm_area_set(C, prevsa);
1562         }
1563
1564         RestoreState(C, prevwin);
1565
1566         //XXX restore_all_scene_cfra(scene_cfra_store);
1567         BKE_scene_set_background(CTX_data_main(C), startscene);
1568         //XXX BKE_scene_update_for_newframe(bmain->eval_ctx, bmain, scene);
1569
1570         BLI_callback_exec(bmain, &startscene->id, BLI_CB_EVT_GAME_POST);
1571
1572         return OPERATOR_FINISHED;
1573 #else
1574         (void)C; /* unused */
1575         BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build");
1576         return OPERATOR_CANCELLED;
1577 #endif
1578 }
1579
1580 void VIEW3D_OT_game_start(wmOperatorType *ot)
1581 {
1582         
1583         /* identifiers */
1584         ot->name = "Start Game Engine";
1585         ot->description = "Start game engine";
1586         ot->idname = "VIEW3D_OT_game_start";
1587         
1588         /* api callbacks */
1589         ot->exec = game_engine_exec;
1590         
1591         ot->poll = game_engine_poll;
1592 }
1593
1594 /* ************************************** */
1595
1596 float ED_view3d_pixel_size(const RegionView3D *rv3d, const float co[3])
1597 {
1598         return mul_project_m4_v3_zfac((float(*)[4])rv3d->persmat, co) * rv3d->pixsize * U.pixelsize;
1599 }
1600
1601 float ED_view3d_radius_to_dist_persp(const float angle, const float radius)
1602 {
1603         return radius * (1.0f / tanf(angle / 2.0f));
1604 }
1605
1606 float ED_view3d_radius_to_dist_ortho(const float lens, const float radius)
1607 {
1608         return radius / (DEFAULT_SENSOR_WIDTH / lens);
1609 }
1610
1611 /**
1612  * Return a new RegionView3D.dist value to fit the \a radius.
1613  *
1614  * \note Depth isn't taken into account, this will fit a flat plane exactly,
1615  * but points towards the view (with a perspective projection),
1616  * may be within the radius but outside the view. eg:
1617  *
1618  * <pre>
1619  *           +
1620  * pt --> + /^ radius
1621  *         / |
1622  *        /  |
1623  * view  +   +
1624  *        \  |
1625  *         \ |
1626  *          \|
1627  *           +
1628  * </pre>
1629  *
1630  * \param ar  Can be NULL if \a use_aspect is false.
1631  * \param persp  Allow the caller to tell what kind of perspective to use (ortho/view/camera)
1632  * \param use_aspect  Increase the distance to account for non 1:1 view aspect.
1633  * \param radius  The radius will be fitted exactly, typically pre-scaled by a margin (#VIEW3D_MARGIN).
1634  */
1635 float ED_view3d_radius_to_dist(
1636         const View3D *v3d, const ARegion *ar,
1637         const char persp, const bool use_aspect,
1638         const float radius)
1639 {
1640         float dist;
1641
1642         BLI_assert(ELEM(persp, RV3D_ORTHO, RV3D_PERSP, RV3D_CAMOB));
1643         BLI_assert((persp != RV3D_CAMOB) || v3d->camera);
1644
1645         if (persp == RV3D_ORTHO) {
1646                 dist = ED_view3d_radius_to_dist_ortho(v3d->lens, radius);
1647         }
1648         else {
1649                 float lens, sensor_size, zoom;
1650                 float angle;
1651
1652                 if (persp == RV3D_CAMOB) {
1653                         CameraParams params;
1654                         BKE_camera_params_init(&params);
1655                         params.clipsta = v3d->near;
1656                         params.clipend = v3d->far;
1657                         BKE_camera_params_from_object(&params, v3d->camera);
1658
1659                         lens = params.lens;
1660                         sensor_size = BKE_camera_sensor_size(params.sensor_fit, params.sensor_x, params.sensor_y);
1661
1662                         /* ignore 'rv3d->camzoom' because we want to fit to the cameras frame */
1663                         zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB;
1664                 }
1665                 else {
1666                         lens = v3d->lens;
1667                         sensor_size = DEFAULT_SENSOR_WIDTH;
1668                         zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
1669                 }
1670
1671                 angle = focallength_to_fov(lens, sensor_size);
1672
1673                 /* zoom influences lens, correct this by scaling the angle as a distance (by the zoom-level) */
1674                 angle = atanf(tanf(angle / 2.0f) * zoom) * 2.0f;
1675
1676                 dist = ED_view3d_radius_to_dist_persp(angle, radius);
1677         }
1678
1679         if (use_aspect) {
1680                 const RegionView3D *rv3d = ar->regiondata;
1681
1682                 float winx, winy;
1683
1684                 if (persp == RV3D_CAMOB) {
1685                         /* camera frame x/y in pixels */
1686                         winx = ar->winx / rv3d->viewcamtexcofac[0];
1687                         winy = ar->winy / rv3d->viewcamtexcofac[1];
1688                 }
1689                 else {
1690                         winx = ar->winx;
1691                         winy = ar->winy;
1692                 }
1693
1694                 if (winx && winy) {
1695                         float aspect = winx / winy;
1696                         if (aspect < 1.0f) {
1697                                 aspect = 1.0f / aspect;
1698                         }
1699                         dist *= aspect;
1700                 }
1701         }
1702
1703         return dist;
1704 }
1705
1706 /* view matrix properties utilities */
1707
1708 /* unused */
1709 #if 0
1710 void ED_view3d_operator_properties_viewmat(wmOperatorType *ot)
1711 {
1712         PropertyRNA *prop;
1713
1714         prop = RNA_def_int(ot->srna, "region_width", 0, 0, INT_MAX, "Region Width", "", 0, INT_MAX);
1715         RNA_def_property_flag(prop, PROP_HIDDEN);
1716
1717         prop = RNA_def_int(ot->srna, "region_height", 0, 0, INT_MAX, "Region height", "", 0, INT_MAX);
1718         RNA_def_property_flag(prop, PROP_HIDDEN);
1719
1720         prop = RNA_def_float_matrix(ot->srna, "perspective_matrix", 4, 4, NULL, 0.0f, 0.0f, "", "Perspective Matrix", 0.0f, 0.0f);
1721         RNA_def_property_flag(prop, PROP_HIDDEN);
1722 }
1723
1724 void ED_view3d_operator_properties_viewmat_set(bContext *C, wmOperator *op)
1725 {
1726         ARegion *ar = CTX_wm_region(C);
1727         RegionView3D *rv3d = ED_view3d_context_rv3d(C);
1728
1729         if (!RNA_struct_property_is_set(op->ptr, "region_width"))
1730                 RNA_int_set(op->ptr, "region_width", ar->winx);
1731
1732         if (!RNA_struct_property_is_set(op->ptr, "region_height"))
1733                 RNA_int_set(op->ptr, "region_height", ar->winy);
1734
1735         if (!RNA_struct_property_is_set(op->ptr, "perspective_matrix"))
1736                 RNA_float_set_array(op->ptr, "perspective_matrix", (float *)rv3d->persmat);
1737 }
1738
1739 void ED_view3d_operator_properties_viewmat_get(wmOperator *op, int *winx, int *winy, float persmat[4][4])
1740 {
1741         *winx = RNA_int_get(op->ptr, "region_width");
1742         *winy = RNA_int_get(op->ptr, "region_height");
1743
1744         RNA_float_get_array(op->ptr, "perspective_matrix", (float *)persmat);
1745 }
1746 #endif