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