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