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