Orientation for 3D cursor
[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 #include "DNA_camera_types.h"
32 #include "DNA_scene_types.h"
33 #include "DNA_object_types.h"
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_math.h"
38 #include "BLI_rect.h"
39 #include "BLI_utildefines.h"
40
41 #include "BKE_action.h"
42 #include "BKE_camera.h"
43 #include "BKE_context.h"
44 #include "BKE_object.h"
45 #include "BKE_global.h"
46 #include "BKE_main.h"
47 #include "BKE_report.h"
48 #include "BKE_scene.h"
49
50 #include "DEG_depsgraph.h"
51
52 #include "UI_resources.h"
53
54 #include "GPU_glew.h"
55 #include "GPU_select.h"
56 #include "GPU_matrix.h"
57
58 #include "WM_api.h"
59 #include "WM_types.h"
60
61 #include "ED_screen.h"
62
63 #include "DRW_engine.h"
64
65 #include "DEG_depsgraph_query.h"
66
67 #include "view3d_intern.h"  /* own include */
68
69 /* -------------------------------------------------------------------- */
70 /** \name Smooth View Operator & Utilities
71  *
72  * Use for view transitions to have smooth (animated) transitions.
73  * \{ */
74
75 /* This operator is one of the 'timer refresh' ones like animation playback */
76
77 struct SmoothView3DState {
78         float dist;
79         float lens;
80         float quat[4];
81         float ofs[3];
82 };
83
84 struct SmoothView3DStore {
85         /* source*/
86         struct SmoothView3DState src;  /* source */
87         struct SmoothView3DState dst;  /* destination */
88         struct SmoothView3DState org;  /* original */
89
90         bool to_camera;
91
92         bool use_dyn_ofs;
93         float dyn_ofs[3];
94
95         /* When smooth-view is enabled, store the 'rv3d->view' here,
96          * assign back when the view motion is completed. */
97         char org_view;
98
99         double time_allowed;
100 };
101
102 static void view3d_smooth_view_state_backup(struct SmoothView3DState *sms_state,
103                                             const View3D *v3d, const RegionView3D *rv3d)
104 {
105         copy_v3_v3(sms_state->ofs,   rv3d->ofs);
106         copy_qt_qt(sms_state->quat,  rv3d->viewquat);
107         sms_state->dist            = rv3d->dist;
108         sms_state->lens            = v3d->lens;
109 }
110
111 static void view3d_smooth_view_state_restore(const struct SmoothView3DState *sms_state,
112                                              View3D *v3d, RegionView3D *rv3d)
113 {
114         copy_v3_v3(rv3d->ofs,      sms_state->ofs);
115         copy_qt_qt(rv3d->viewquat, sms_state->quat);
116         rv3d->dist               = sms_state->dist;
117         v3d->lens                = sms_state->lens;
118 }
119
120 /* will start timer if appropriate */
121 /* the arguments are the desired situation */
122 void ED_view3d_smooth_view_ex(
123         /* avoid passing in the context */
124         wmWindowManager *wm, wmWindow *win, ScrArea *sa,
125         View3D *v3d, ARegion *ar, const int smooth_viewtx,
126         const V3D_SmoothParams *sview)
127 {
128         RegionView3D *rv3d = ar->regiondata;
129         struct SmoothView3DStore sms = {{0}};
130         bool ok = false;
131         
132         /* initialize sms */
133         view3d_smooth_view_state_backup(&sms.dst, v3d, rv3d);
134         view3d_smooth_view_state_backup(&sms.src, v3d, rv3d);
135         /* if smoothview runs multiple times... */
136         if (rv3d->sms == NULL) {
137                 view3d_smooth_view_state_backup(&sms.org, v3d, rv3d);
138         }
139         else {
140                 sms.org = rv3d->sms->org;
141         }
142         sms.org_view = rv3d->view;
143
144         /* sms.to_camera = false; */  /* initizlized to zero anyway */
145
146         /* note on camera locking, this is a little confusing but works ok.
147          * we may be changing the view 'as if' there is no active camera, but in fact
148          * there is an active camera which is locked to the view.
149          *
150          * In the case where smooth view is moving _to_ a camera we don't want that
151          * camera to be moved or changed, so only when the camera is not being set should
152          * we allow camera option locking to initialize the view settings from the camera.
153          */
154         if (sview->camera == NULL && sview->camera_old == NULL) {
155                 ED_view3d_camera_lock_init(v3d, rv3d);
156         }
157
158         /* store the options we want to end with */
159         if (sview->ofs)
160                 copy_v3_v3(sms.dst.ofs, sview->ofs);
161         if (sview->quat)
162                 copy_qt_qt(sms.dst.quat, sview->quat);
163         if (sview->dist)
164                 sms.dst.dist = *sview->dist;
165         if (sview->lens)
166                 sms.dst.lens = *sview->lens;
167
168         if (sview->dyn_ofs) {
169                 BLI_assert(sview->ofs  == NULL);
170                 BLI_assert(sview->quat != NULL);
171
172                 copy_v3_v3(sms.dyn_ofs, sview->dyn_ofs);
173                 sms.use_dyn_ofs = true;
174
175                 /* calculate the final destination offset */
176                 view3d_orbit_apply_dyn_ofs(sms.dst.ofs, sms.src.ofs, sms.src.quat, sms.dst.quat, sms.dyn_ofs);
177         }
178
179         if (sview->camera) {
180                 sms.dst.dist = ED_view3d_offset_distance(sview->camera->obmat, sview->ofs, VIEW3D_DIST_FALLBACK);
181                 ED_view3d_from_object(sview->camera, sms.dst.ofs, sms.dst.quat, &sms.dst.dist, &sms.dst.lens);
182                 sms.to_camera = true; /* restore view3d values in end */
183         }
184         
185         /* skip smooth viewing for render engine draw */
186         if (smooth_viewtx && v3d->drawtype != OB_RENDER) {
187                 bool changed = false; /* zero means no difference */
188                 
189                 if (sview->camera_old != sview->camera)
190                         changed = true;
191                 else if (sms.dst.dist != rv3d->dist)
192                         changed = true;
193                 else if (sms.dst.lens != v3d->lens)
194                         changed = true;
195                 else if (!equals_v3v3(sms.dst.ofs, rv3d->ofs))
196                         changed = true;
197                 else if (!equals_v4v4(sms.dst.quat, rv3d->viewquat))
198                         changed = true;
199                 
200                 /* The new view is different from the old one
201                  * so animate the view */
202                 if (changed) {
203                         /* original values */
204                         if (sview->camera_old) {
205                                 sms.src.dist = ED_view3d_offset_distance(sview->camera_old->obmat, rv3d->ofs, 0.0f);
206                                 /* this */
207                                 ED_view3d_from_object(sview->camera_old, sms.src.ofs, sms.src.quat, &sms.src.dist, &sms.src.lens);
208                         }
209                         /* grid draw as floor */
210                         if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
211                                 /* use existing if exists, means multiple calls to smooth view wont loose the original 'view' setting */
212                                 rv3d->view = RV3D_VIEW_USER;
213                         }
214
215                         sms.time_allowed = (double)smooth_viewtx / 1000.0;
216                         
217                         /* if this is view rotation only
218                          * we can decrease the time allowed by
219                          * the angle between quats 
220                          * this means small rotations wont lag */
221                         if (sview->quat && !sview->ofs && !sview->dist) {
222                                 /* scale the time allowed by the rotation */
223                                 sms.time_allowed *= (double)fabsf(angle_signed_normalized_qtqt(sms.dst.quat, sms.src.quat)) / M_PI; /* 180deg == 1.0 */
224                         }
225
226                         /* ensure it shows correct */
227                         if (sms.to_camera) {
228                                 /* use ortho if we move from an ortho view to an ortho camera */
229                                 rv3d->persp = (((rv3d->is_persp == false) &&
230                                                 (sview->camera->type == OB_CAMERA) &&
231                                                 (((Camera *)sview->camera->data)->type == CAM_ORTHO)) ?
232                                                 RV3D_ORTHO : RV3D_PERSP);
233                         }
234
235                         rv3d->rflag |= RV3D_NAVIGATING;
236                         
237                         /* not essential but in some cases the caller will tag the area for redraw,
238                          * and in that case we can get a flicker of the 'org' user view but we want to see 'src' */
239                         view3d_smooth_view_state_restore(&sms.src, v3d, rv3d);
240
241                         /* keep track of running timer! */
242                         if (rv3d->sms == NULL) {
243                                 rv3d->sms = MEM_mallocN(sizeof(struct SmoothView3DStore), "smoothview v3d");
244                         }
245                         *rv3d->sms = sms;
246                         if (rv3d->smooth_timer) {
247                                 WM_event_remove_timer(wm, win, rv3d->smooth_timer);
248                         }
249                         /* TIMER1 is hardcoded in keymap */
250                         rv3d->smooth_timer = WM_event_add_timer(wm, win, TIMER1, 1.0 / 100.0); /* max 30 frs/sec */
251
252                         ok = true;
253                 }
254         }
255         
256         /* if we get here nothing happens */
257         if (ok == false) {
258                 if (sms.to_camera == false) {
259                         copy_v3_v3(rv3d->ofs, sms.dst.ofs);
260                         copy_qt_qt(rv3d->viewquat, sms.dst.quat);
261                         rv3d->dist = sms.dst.dist;
262                         v3d->lens = sms.dst.lens;
263
264                         ED_view3d_camera_lock_sync(v3d, rv3d);
265                 }
266
267                 if (rv3d->viewlock & RV3D_BOXVIEW) {
268                         view3d_boxview_copy(sa, ar);
269                 }
270
271                 ED_region_tag_redraw(ar);
272         }
273 }
274
275 void ED_view3d_smooth_view(
276         bContext *C,
277         View3D *v3d, ARegion *ar, const int smooth_viewtx,
278         const struct V3D_SmoothParams *sview)
279 {
280         wmWindowManager *wm = CTX_wm_manager(C);
281         wmWindow *win = CTX_wm_window(C);
282         ScrArea *sa = CTX_wm_area(C);
283
284         ED_view3d_smooth_view_ex(
285                 wm, win, sa,
286                 v3d, ar, smooth_viewtx,
287                 sview);
288 }
289
290 /* only meant for timer usage */
291 static void view3d_smoothview_apply(bContext *C, View3D *v3d, ARegion *ar, bool sync_boxview)
292 {
293         RegionView3D *rv3d = ar->regiondata;
294         struct SmoothView3DStore *sms = rv3d->sms;
295         float step, step_inv;
296         
297         if (sms->time_allowed != 0.0)
298                 step = (float)((rv3d->smooth_timer->duration) / sms->time_allowed);
299         else
300                 step = 1.0f;
301         
302         /* end timer */
303         if (step >= 1.0f) {
304                 
305                 /* if we went to camera, store the original */
306                 if (sms->to_camera) {
307                         rv3d->persp = RV3D_CAMOB;
308                         view3d_smooth_view_state_restore(&sms->org, v3d, rv3d);
309                 }
310                 else {
311                         view3d_smooth_view_state_restore(&sms->dst, v3d, rv3d);
312
313                         ED_view3d_camera_lock_sync(v3d, rv3d);
314                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
315                 }
316                 
317                 if ((rv3d->viewlock & RV3D_LOCKED) == 0) {
318                         rv3d->view = sms->org_view;
319                 }
320
321                 MEM_freeN(rv3d->sms);
322                 rv3d->sms = NULL;
323                 
324                 WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), rv3d->smooth_timer);
325                 rv3d->smooth_timer = NULL;
326                 rv3d->rflag &= ~RV3D_NAVIGATING;
327         }
328         else {
329                 /* ease in/out */
330                 step = (3.0f * step * step - 2.0f * step * step * step);
331
332                 step_inv = 1.0f - step;
333
334                 interp_qt_qtqt(rv3d->viewquat, sms->src.quat, sms->dst.quat, step);
335
336                 if (sms->use_dyn_ofs) {
337                         view3d_orbit_apply_dyn_ofs(rv3d->ofs, sms->src.ofs, sms->src.quat, rv3d->viewquat, sms->dyn_ofs);
338                 }
339                 else {
340                         interp_v3_v3v3(rv3d->ofs, sms->src.ofs,  sms->dst.ofs,  step);
341                 }
342                 
343                 rv3d->dist = sms->dst.dist * step + sms->src.dist * step_inv;
344                 v3d->lens  = sms->dst.lens * step + sms->src.lens * step_inv;
345
346                 ED_view3d_camera_lock_sync(v3d, rv3d);
347                 if (ED_screen_animation_playing(CTX_wm_manager(C))) {
348                         ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
349                 }
350
351                 /* Event handling won't know if a UI item has been moved under the pointer. */
352                 WM_event_add_mousemove(C);
353         }
354         
355         if (sync_boxview && (rv3d->viewlock & RV3D_BOXVIEW)) {
356                 view3d_boxview_copy(CTX_wm_area(C), ar);
357         }
358
359         /* note: this doesn't work right because the v3d->lens is now used in ortho mode r51636,
360          * when switching camera in quad-view the other ortho views would zoom & reset.
361          *
362          * For now only redraw all regions when smoothview finishes.
363          */
364         if (step >= 1.0f) {
365                 WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
366         }
367         else {
368                 ED_region_tag_redraw(ar);
369         }
370 }
371
372 static int view3d_smoothview_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
373 {
374         View3D *v3d = CTX_wm_view3d(C);
375         ARegion *ar = CTX_wm_region(C);
376         RegionView3D *rv3d = ar->regiondata;
377
378         /* escape if not our timer */
379         if (rv3d->smooth_timer == NULL || rv3d->smooth_timer != event->customdata) {
380                 return OPERATOR_PASS_THROUGH;
381         }
382
383         view3d_smoothview_apply(C, v3d, ar, true);
384
385         return OPERATOR_FINISHED;
386 }
387
388 /**
389  * Apply the smoothview immediately, use when we need to start a new view operation.
390  * (so we don't end up half-applying a view operation when pressing keys quickly).
391  */
392 void ED_view3d_smooth_view_force_finish(
393         bContext *C,
394         View3D *v3d, ARegion *ar)
395 {
396         RegionView3D *rv3d = ar->regiondata;
397
398         if (rv3d && rv3d->sms) {
399                 rv3d->sms->time_allowed = 0.0;  /* force finishing */
400                 view3d_smoothview_apply(C, v3d, ar, false);
401
402                 /* force update of view matrix so tools that run immediately after
403                  * can use them without redrawing first */
404                 Depsgraph *depsgraph = CTX_data_depsgraph(C);
405                 Scene *scene = CTX_data_scene(C);
406                 ED_view3d_update_viewmat(depsgraph, scene, v3d, ar, NULL, NULL, NULL);
407         }
408 }
409
410 void VIEW3D_OT_smoothview(wmOperatorType *ot)
411 {
412         /* identifiers */
413         ot->name = "Smooth View";
414         ot->description = "";
415         ot->idname = "VIEW3D_OT_smoothview";
416
417         /* api callbacks */
418         ot->invoke = view3d_smoothview_invoke;
419
420         /* flags */
421         ot->flag = OPTYPE_INTERNAL;
422
423         ot->poll = ED_operator_view3d_active;
424 }
425
426 /** \} */
427
428 /* -------------------------------------------------------------------- */
429 /** \name Camera to View Operator
430  * \{ */
431
432 static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
433 {
434         View3D *v3d;
435         ARegion *ar;
436         RegionView3D *rv3d;
437
438         ObjectTfmProtectedChannels obtfm;
439
440         ED_view3d_context_user_region(C, &v3d, &ar);
441         rv3d = ar->regiondata;
442
443         ED_view3d_lastview_store(rv3d);
444
445         BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
446
447         ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
448
449         BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag);
450
451         DEG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
452         rv3d->persp = RV3D_CAMOB;
453         
454         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, v3d->camera);
455         
456         return OPERATOR_FINISHED;
457
458 }
459
460 static int view3d_camera_to_view_poll(bContext *C)
461 {
462         View3D *v3d;
463         ARegion *ar;
464
465         if (ED_view3d_context_user_region(C, &v3d, &ar)) {
466                 RegionView3D *rv3d = ar->regiondata;
467                 if (v3d && v3d->camera && !ID_IS_LINKED(v3d->camera)) {
468                         if (rv3d && (rv3d->viewlock & RV3D_LOCKED) == 0) {
469                                 if (rv3d->persp != RV3D_CAMOB) {
470                                         return 1;
471                                 }
472                         }
473                 }
474         }
475
476         return 0;
477 }
478
479 void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
480 {
481         /* identifiers */
482         ot->name = "Align Camera To View";
483         ot->description = "Set camera view to active view";
484         ot->idname = "VIEW3D_OT_camera_to_view";
485         
486         /* api callbacks */
487         ot->exec = view3d_camera_to_view_exec;
488         ot->poll = view3d_camera_to_view_poll;
489         
490         /* flags */
491         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
492 }
493
494 /** \} */
495
496 /* -------------------------------------------------------------------- */
497 /** \name Camera Fit Frame to Selected Operator
498  * \{ */
499
500 /* unlike VIEW3D_OT_view_selected this is for framing a render and not
501  * meant to take into account vertex/bone selection for eg. */
502 static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *op)
503 {
504         Depsgraph *depsgraph = CTX_data_depsgraph(C);
505         Scene *scene = CTX_data_scene(C);
506         ViewLayer *view_layer = CTX_data_view_layer(C);
507         View3D *v3d = CTX_wm_view3d(C);  /* can be NULL */
508         Object *camera_ob = v3d ? v3d->camera : scene->camera;
509
510         float r_co[3]; /* the new location to apply */
511         float r_scale; /* only for ortho cameras */
512
513         if (camera_ob == NULL) {
514                 BKE_report(op->reports, RPT_ERROR, "No active camera");
515                 return OPERATOR_CANCELLED;
516         }
517
518         /* this function does all the important stuff */
519         if (BKE_camera_view_frame_fit_to_scene(depsgraph, scene, view_layer, camera_ob, r_co, &r_scale)) {
520                 ObjectTfmProtectedChannels obtfm;
521                 float obmat_new[4][4];
522
523                 if ((camera_ob->type == OB_CAMERA) && (((Camera *)camera_ob->data)->type == CAM_ORTHO)) {
524                         ((Camera *)camera_ob->data)->ortho_scale = r_scale;
525                 }
526
527                 copy_m4_m4(obmat_new, camera_ob->obmat);
528                 copy_v3_v3(obmat_new[3], r_co);
529
530                 /* only touch location */
531                 BKE_object_tfm_protected_backup(camera_ob, &obtfm);
532                 BKE_object_apply_mat4(camera_ob, obmat_new, true, true);
533                 BKE_object_tfm_protected_restore(camera_ob, &obtfm, OB_LOCK_SCALE | OB_LOCK_ROT4D);
534
535                 /* notifiers */
536                 DEG_id_tag_update(&camera_ob->id, OB_RECALC_OB);
537                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, camera_ob);
538                 return OPERATOR_FINISHED;
539         }
540         else {
541                 return OPERATOR_CANCELLED;
542         }
543 }
544
545 void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
546 {
547         /* identifiers */
548         ot->name = "Camera Fit Frame to Selected";
549         ot->description = "Move the camera so selected objects are framed";
550         ot->idname = "VIEW3D_OT_camera_to_view_selected";
551
552         /* api callbacks */
553         ot->exec = view3d_camera_to_view_selected_exec;
554         ot->poll = ED_operator_scene_editable;
555
556         /* flags */
557         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
558 }
559
560 /** \} */
561
562 /* -------------------------------------------------------------------- */
563 /** \name Object as Camera Operator
564  * \{ */
565
566 static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob, const int smooth_viewtx)
567 {
568         Main *bmain = CTX_data_main(C);
569         for (bScreen *screen = bmain->screen.first; screen != NULL; screen = screen->id.next) {
570                 for (ScrArea *area = screen->areabase.first; area != NULL; area = area->next) {
571                         for (SpaceLink *space_link = area->spacedata.first; space_link != NULL; space_link = space_link->next) {
572                                 if (space_link->spacetype == SPACE_VIEW3D) {
573                                         View3D *other_v3d = (View3D *)space_link;
574                                         if (other_v3d == v3d) {
575                                                 continue;
576                                         }
577                                         if (other_v3d->camera == ob) {
578                                                 continue;
579                                         }
580                                         if (v3d->scenelock) {
581                                                 ListBase *lb = (space_link == area->spacedata.first)
582                                                                    ? &area->regionbase
583                                                                    : &space_link->regionbase;
584                                                 for (ARegion *other_ar = lb->first; other_ar != NULL; other_ar = other_ar->next) {
585                                                         if (other_ar->regiontype == RGN_TYPE_WINDOW) {
586                                                                 if (other_ar->regiondata) {
587                                                                         RegionView3D *other_rv3d = other_ar->regiondata;
588                                                                         if (other_rv3d->persp == RV3D_CAMOB) {
589                                                                                 Object *other_camera_old = other_v3d->camera;
590                                                                                 other_v3d->camera = ob;
591                                                                                 ED_view3d_lastview_store(other_rv3d);
592                                                                                 ED_view3d_smooth_view(
593                                                                                         C, other_v3d, other_ar, smooth_viewtx,
594                                                                                         &(const V3D_SmoothParams) {
595                                                                                             .camera_old = other_camera_old,
596                                                                                             .camera = other_v3d->camera,
597                                                                                             .ofs = other_rv3d->ofs,
598                                                                                             .quat = other_rv3d->viewquat,
599                                                                                             .dist = &other_rv3d->dist,
600                                                                                             .lens = &other_v3d->lens});
601                                                                         }
602                                                                         else {
603                                                                                 other_v3d->camera = ob;
604                                                                         }
605                                                                 }
606                                                         }
607                                                 }
608                                         }
609                                 }
610                         }
611                 }
612         }
613 }
614
615 static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op)
616 {
617         View3D *v3d;
618         ARegion *ar;
619         RegionView3D *rv3d;
620
621         Scene *scene = CTX_data_scene(C);
622         Object *ob = CTX_data_active_object(C);
623
624         const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
625
626         /* no NULL check is needed, poll checks */
627         ED_view3d_context_user_region(C, &v3d, &ar);
628         rv3d = ar->regiondata;
629
630         if (ob) {
631                 Object *camera_old = (rv3d->persp == RV3D_CAMOB) ? V3D_CAMERA_SCENE(scene, v3d) : NULL;
632                 rv3d->persp = RV3D_CAMOB;
633                 v3d->camera = ob;
634                 if (v3d->scenelock)
635                         scene->camera = ob;
636
637                 /* unlikely but looks like a glitch when set to the same */
638                 if (camera_old != ob) {
639                         ED_view3d_lastview_store(rv3d);
640
641                         ED_view3d_smooth_view(
642                                 C, v3d, ar, smooth_viewtx,
643                                 &(const V3D_SmoothParams) {
644                                     .camera_old = camera_old, .camera = v3d->camera,
645                                     .ofs = rv3d->ofs, .quat = rv3d->viewquat,
646                                     .dist = &rv3d->dist, .lens = &v3d->lens});
647                 }
648
649                 if (v3d->scenelock) {
650                         sync_viewport_camera_smoothview(C, v3d, ob, smooth_viewtx);
651                         WM_event_add_notifier(C, NC_SCENE, scene);
652                 }
653                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
654         }
655         
656         return OPERATOR_FINISHED;
657 }
658
659 int ED_operator_rv3d_user_region_poll(bContext *C)
660 {
661         View3D *v3d_dummy;
662         ARegion *ar_dummy;
663
664         return ED_view3d_context_user_region(C, &v3d_dummy, &ar_dummy);
665 }
666
667 void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
668 {
669         /* identifiers */
670         ot->name = "Set Active Object as Camera";
671         ot->description = "Set the active object as the active camera for this view or scene";
672         ot->idname = "VIEW3D_OT_object_as_camera";
673         
674         /* api callbacks */
675         ot->exec = view3d_setobjectascamera_exec;
676         ot->poll = ED_operator_rv3d_user_region_poll;
677         
678         /* flags */
679         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
680 }
681
682 /** \} */
683
684 /* -------------------------------------------------------------------- */
685 /** \name Window and View Matrix Calculation
686  * \{ */
687
688 /**
689  * \param rect optional for picking (can be NULL).
690  */
691 void view3d_winmatrix_set(Depsgraph *depsgraph, ARegion *ar, const View3D *v3d, const rcti *rect)
692 {
693         RegionView3D *rv3d = ar->regiondata;
694         rctf viewplane;
695         float clipsta, clipend;
696         bool is_ortho;
697         
698         is_ortho = ED_view3d_viewplane_get(depsgraph, v3d, rv3d, ar->winx, ar->winy, &viewplane, &clipsta, &clipend, NULL);
699         rv3d->is_persp = !is_ortho;
700
701 #if 0
702         printf("%s: %d %d %f %f %f %f %f %f\n", __func__, winx, winy,
703                viewplane.xmin, viewplane.ymin, viewplane.xmax, viewplane.ymax,
704                clipsta, clipend);
705 #endif
706
707         if (rect) {  /* picking */
708                 rctf r;
709                 r.xmin = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmin / (float)ar->winx));
710                 r.ymin = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymin / (float)ar->winy));
711                 r.xmax = viewplane.xmin + (BLI_rctf_size_x(&viewplane) * (rect->xmax / (float)ar->winx));
712                 r.ymax = viewplane.ymin + (BLI_rctf_size_y(&viewplane) * (rect->ymax / (float)ar->winy));
713                 viewplane = r;
714         }
715
716         if (is_ortho) {
717                 gpuOrtho(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
718         }
719         else {
720                 gpuFrustum(viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
721         }
722
723         /* update matrix in 3d view region */
724         gpuGetProjectionMatrix(rv3d->winmat);
725 }
726
727 static void obmat_to_viewmat(RegionView3D *rv3d, Object *ob)
728 {
729         float bmat[4][4];
730
731         rv3d->view = RV3D_VIEW_USER; /* don't show the grid */
732
733         normalize_m4_m4(bmat, ob->obmat);
734         invert_m4_m4(rv3d->viewmat, bmat);
735
736         /* view quat calculation, needed for add object */
737         mat4_normalized_to_quat(rv3d->viewquat, rv3d->viewmat);
738 }
739
740 /**
741  * Sets #RegionView3D.viewmat
742  *
743  * \param depsgraph: Depsgraph.
744  * \param scene: Scene for camera and cursor location.
745  * \param v3d: View 3D space data.
746  * \param rv3d: 3D region which stores the final matrices.
747  * \param rect_scale: Optional 2D scale argument,
748  * Use when displaying a sub-region, eg: when #view3d_winmatrix_set takes a 'rect' argument.
749  *
750  * \note don't set windows active in here, is used by renderwin too.
751  */
752 void view3d_viewmatrix_set(
753         Depsgraph *depsgraph, Scene *scene,
754         const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2])
755 {
756         if (rv3d->persp == RV3D_CAMOB) {      /* obs/camera */
757                 if (v3d->camera) {
758                         Object *camera_object = DEG_get_evaluated_object(depsgraph, v3d->camera);
759                         BKE_object_where_is_calc(depsgraph, scene, camera_object);
760                         obmat_to_viewmat(rv3d, camera_object);
761                 }
762                 else {
763                         quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
764                         rv3d->viewmat[3][2] -= rv3d->dist;
765                 }
766         }
767         else {
768                 bool use_lock_ofs = false;
769
770
771                 /* should be moved to better initialize later on XXX */
772                 if (rv3d->viewlock & RV3D_LOCKED)
773                         ED_view3d_lock(rv3d);
774                 
775                 quat_to_mat4(rv3d->viewmat, rv3d->viewquat);
776                 if (rv3d->persp == RV3D_PERSP) rv3d->viewmat[3][2] -= rv3d->dist;
777                 if (v3d->ob_centre) {
778                         Object *ob = v3d->ob_centre;
779                         float vec[3];
780                         
781                         copy_v3_v3(vec, ob->obmat[3]);
782                         if (ob->type == OB_ARMATURE && v3d->ob_centre_bone[0]) {
783                                 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, v3d->ob_centre_bone);
784                                 if (pchan) {
785                                         copy_v3_v3(vec, pchan->pose_mat[3]);
786                                         mul_m4_v3(ob->obmat, vec);
787                                 }
788                         }
789                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
790                         use_lock_ofs = true;
791                 }
792                 else if (v3d->ob_centre_cursor) {
793                         float vec[3];
794                         copy_v3_v3(vec, ED_view3d_cursor3d_get(scene, (View3D *)v3d)->location);
795                         translate_m4(rv3d->viewmat, -vec[0], -vec[1], -vec[2]);
796                         use_lock_ofs = true;
797                 }
798                 else {
799                         translate_m4(rv3d->viewmat, rv3d->ofs[0], rv3d->ofs[1], rv3d->ofs[2]);
800                 }
801
802                 /* lock offset */
803                 if (use_lock_ofs) {
804                         float persmat[4][4], persinv[4][4];
805                         float vec[3];
806
807                         /* we could calculate the real persmat/persinv here
808                          * but it would be unreliable so better to later */
809                         mul_m4_m4m4(persmat, rv3d->winmat, rv3d->viewmat);
810                         invert_m4_m4(persinv, persmat);
811
812                         mul_v2_v2fl(vec, rv3d->ofs_lock, rv3d->is_persp ? rv3d->dist : 1.0f);
813                         vec[2] = 0.0f;
814
815                         if (rect_scale) {
816                                 /* Since 'RegionView3D.winmat' has been calculated and this function doesn't take the 'ARegion'
817                                  * we don't know about the region size.
818                                  * Use 'rect_scale' when drawing a sub-region to apply 2D offset,
819                                  * scaled by the difference between the sub-region and the region size.
820                                  */
821                                 vec[0] /= rect_scale[0];
822                                 vec[1] /= rect_scale[1];
823                         }
824
825                         mul_mat3_m4_v3(persinv, vec);
826                         translate_m4(rv3d->viewmat, vec[0], vec[1], vec[2]);
827                 }
828                 /* end lock offset */
829         }
830 }
831
832 /** \} */
833
834 /* -------------------------------------------------------------------- */
835 /** \name OpenGL Select Utilities
836  * \{ */
837
838 /**
839  * Optionally cache data for multiple calls to #view3d_opengl_select
840  *
841  * just avoid GPU_select headers outside this file
842  */
843 void view3d_opengl_select_cache_begin(void)
844 {
845         GPU_select_cache_begin();
846 }
847
848 void view3d_opengl_select_cache_end(void)
849 {
850         GPU_select_cache_end();
851 }
852
853 #ifndef WITH_OPENGL_LEGACY
854 struct DrawSelectLoopUserData {
855         uint  pass;
856         uint  hits;
857         uint *buffer;
858         uint  buffer_len;
859         const rcti *rect;
860         char gpu_select_mode;
861 };
862
863 static bool drw_select_loop_pass(eDRWSelectStage stage, void *user_data)
864 {
865         bool continue_pass = false;
866         struct DrawSelectLoopUserData *data = user_data;
867         if (stage == DRW_SELECT_PASS_PRE) {
868                 GPU_select_begin(data->buffer, data->buffer_len, data->rect, data->gpu_select_mode, data->hits);
869                 /* always run POST after PRE. */
870                 continue_pass = true;
871         }
872         else if (stage == DRW_SELECT_PASS_POST) {
873                 int hits = GPU_select_end();
874                 if (data->pass == 0) {
875                         /* quirk of GPU_select_end, only take hits value from first call. */
876                         data->hits = hits;
877                 }
878                 if (data->gpu_select_mode == GPU_SELECT_NEAREST_FIRST_PASS) {
879                         data->gpu_select_mode = GPU_SELECT_NEAREST_SECOND_PASS;
880                         continue_pass = (hits > 0);
881                 }
882                 data->pass += 1;
883         }
884         else {
885                 BLI_assert(0);
886         }
887         return continue_pass;
888
889 }
890 #endif /* WITH_OPENGL_LEGACY */
891
892 /**
893  * \warning be sure to account for a negative return value
894  * This is an error, "Too many objects in select buffer"
895  * and no action should be taken (can crash blender) if this happens
896  *
897  * \note (vc->obedit == NULL) can be set to explicitly skip edit-object selection.
898  */
899 int view3d_opengl_select(
900         ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input,
901         eV3DSelectMode select_mode)
902 {
903         struct bThemeState theme_state;
904         Depsgraph *graph = vc->depsgraph;
905         Scene *scene = vc->scene;
906         View3D *v3d = vc->v3d;
907         ARegion *ar = vc->ar;
908         rcti rect;
909         int hits;
910         const bool use_obedit_skip = (OBEDIT_FROM_VIEW_LAYER(vc->view_layer) != NULL) && (vc->obedit == NULL);
911         const bool is_pick_select = (U.gpu_select_pick_deph != 0);
912         const bool do_passes = (
913                 (is_pick_select == false) &&
914                 (select_mode == VIEW3D_SELECT_PICK_NEAREST) &&
915                 GPU_select_query_check_active());
916         const bool use_nearest = (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST);
917
918         char gpu_select_mode;
919
920         /* case not a border select */
921         if (input->xmin == input->xmax) {
922                 /* seems to be default value for bones only now */
923                 BLI_rcti_init_pt_radius(&rect, (const int[2]){input->xmin, input->ymin}, 12);
924         }
925         else {
926                 rect = *input;
927         }
928
929         if (is_pick_select) {
930                 if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST) {
931                         gpu_select_mode = GPU_SELECT_PICK_NEAREST;
932                 }
933                 else if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_ALL) {
934                         gpu_select_mode = GPU_SELECT_PICK_ALL;
935                 }
936                 else {
937                         gpu_select_mode = GPU_SELECT_ALL;
938                 }
939         }
940         else {
941                 if (do_passes) {
942                         gpu_select_mode = GPU_SELECT_NEAREST_FIRST_PASS;
943                 }
944                 else {
945                         gpu_select_mode = GPU_SELECT_ALL;
946                 }
947         }
948
949         /* Tools may request depth outside of regular drawing code. */
950         UI_Theme_Store(&theme_state);
951         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
952
953         /* Re-use cache (rect must be smaller then the cached)
954          * other context is assumed to be unchanged */
955         if (GPU_select_is_cached()) {
956                 GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
957                 GPU_select_cache_load_id();
958                 hits = GPU_select_end();
959                 goto finally;
960         }
961
962 #ifndef WITH_OPENGL_LEGACY
963         /* All of the queries need to be perform on the drawing context. */
964         DRW_opengl_context_enable();
965 #endif
966
967         G.f |= G_PICKSEL;
968
969         /* Important we use the 'viewmat' and don't re-calculate since
970          * the object & bone view locking takes 'rect' into account, see: T51629. */
971         ED_view3d_draw_setup_view(vc->win, graph, scene, ar, v3d, vc->rv3d->viewmat, NULL, &rect);
972
973         if (v3d->drawtype > OB_WIRE) {
974                 v3d->zbuf = true;
975                 glEnable(GL_DEPTH_TEST);
976         }
977
978         if (vc->rv3d->rflag & RV3D_CLIPPING)
979                 ED_view3d_clipping_set(vc->rv3d);
980         
981
982 #ifdef WITH_OPENGL_LEGACY
983         if (IS_VIEWPORT_LEGACY(vc->v3d)) {
984                 GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
985                 ED_view3d_draw_select_loop(vc, scene, sl, v3d, ar, use_obedit_skip, use_nearest);
986                 hits = GPU_select_end();
987
988                 if (do_passes && (hits > 0)) {
989                         GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
990                         ED_view3d_draw_select_loop(vc, scene, sl, v3d, ar, use_obedit_skip, use_nearest);
991                         GPU_select_end();
992                 }
993         }
994         else
995 #else
996         {
997                 /* We need to call "GPU_select_*" API's inside DRW_draw_select_loop
998                  * because the OpenGL context created & destroyed inside this function. */
999                 struct DrawSelectLoopUserData drw_select_loop_user_data = {
1000                         .pass = 0,
1001                         .hits = 0,
1002                         .buffer = buffer,
1003                         .buffer_len = bufsize,
1004                         .rect = &rect,
1005                         .gpu_select_mode = gpu_select_mode,
1006                 };
1007                 DRW_draw_select_loop(
1008                         graph, ar, v3d,
1009                         use_obedit_skip, use_nearest, &rect,
1010                         drw_select_loop_pass, &drw_select_loop_user_data);
1011                 hits = drw_select_loop_user_data.hits;
1012         }
1013 #endif /* WITH_OPENGL_LEGACY */
1014
1015         G.f &= ~G_PICKSEL;
1016         ED_view3d_draw_setup_view(vc->win, graph, scene, ar, v3d, vc->rv3d->viewmat, NULL, NULL);
1017         
1018         if (v3d->drawtype > OB_WIRE) {
1019                 v3d->zbuf = 0;
1020                 glDisable(GL_DEPTH_TEST);
1021         }
1022         
1023         if (vc->rv3d->rflag & RV3D_CLIPPING)
1024                 ED_view3d_clipping_disable();
1025
1026 #ifndef WITH_OPENGL_LEGACY
1027         DRW_opengl_context_disable();
1028 #endif
1029
1030 finally:
1031
1032         if (hits < 0) printf("Too many objects in select buffer\n");  /* XXX make error message */
1033
1034         UI_Theme_Restore(&theme_state);
1035
1036         return hits;
1037 }
1038
1039 /** \} */
1040
1041 /* -------------------------------------------------------------------- */
1042 /** \name View Layer Utilities
1043  * \{ */
1044
1045 int ED_view3d_view_layer_set(int lay, const int *values, int *active)
1046 {
1047         int i, tot = 0;
1048         
1049         /* ensure we always have some layer selected */
1050         for (i = 0; i < 20; i++)
1051                 if (values[i])
1052                         tot++;
1053         
1054         if (tot == 0)
1055                 return lay;
1056         
1057         for (i = 0; i < 20; i++) {
1058                 
1059                 if (active) {
1060                         /* if this value has just been switched on, make that layer active */
1061                         if (values[i] && (lay & (1 << i)) == 0) {
1062                                 *active = (1 << i);
1063                         }
1064                 }
1065                         
1066                 if (values[i]) lay |= (1 << i);
1067                 else lay &= ~(1 << i);
1068         }
1069         
1070         /* ensure always an active layer */
1071         if (active && (lay & *active) == 0) {
1072                 for (i = 0; i < 20; i++) {
1073                         if (lay & (1 << i)) {
1074                                 *active = 1 << i;
1075                                 break;
1076                         }
1077                 }
1078         }
1079         
1080         return lay;
1081 }
1082
1083 /** \} */