Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_draw.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_draw.c
28  *  \ingroup spview3d
29  */
30
31 #include <math.h>
32
33 #include "BLI_listbase.h"
34 #include "BLI_math.h"
35 #include "BLI_rect.h"
36 #include "BLI_string.h"
37 #include "BLI_threads.h"
38 #include "BLI_jitter_2d.h"
39
40 #include "BIF_gl.h"
41 #include "BIF_glutil.h"
42
43 #include "BKE_camera.h"
44 #include "BKE_context.h"
45 #include "BKE_global.h"
46 #include "BKE_key.h"
47 #include "BKE_scene.h"
48 #include "BKE_object.h"
49 #include "BKE_paint.h"
50 #include "BKE_unit.h"
51
52 #include "BLF_api.h"
53
54 #include "BLT_translation.h"
55
56 #include "DNA_armature_types.h"
57 #include "DNA_brush_types.h"
58 #include "DNA_camera_types.h"
59 #include "DNA_key_types.h"
60 #include "DNA_mesh_types.h"
61 #include "DNA_object_types.h"
62 #include "DNA_view3d_types.h"
63 #include "DNA_windowmanager_types.h"
64
65 #include "DRW_engine.h"
66
67 #include "ED_armature.h"
68 #include "ED_keyframing.h"
69 #include "ED_gpencil.h"
70 #include "ED_screen.h"
71 #include "ED_transform.h"
72
73 #include "DEG_depsgraph_query.h"
74
75 #include "GPU_batch.h"
76 #include "GPU_draw.h"
77 #include "GPU_matrix.h"
78 #include "GPU_immediate.h"
79 #include "GPU_immediate_util.h"
80 #include "GPU_material.h"
81 #include "GPU_viewport.h"
82
83 #include "MEM_guardedalloc.h"
84
85 #include "UI_interface.h"
86 #include "UI_resources.h"
87
88 #include "RE_engine.h"
89
90 #include "WM_api.h"
91 #include "WM_types.h"
92
93 #include "RNA_access.h"
94
95 #include "IMB_imbuf.h"
96 #include "IMB_imbuf_types.h"
97
98 #include "view3d_intern.h"  /* own include */
99
100 /* ******************** general functions ***************** */
101
102 /**
103  * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
104  */
105 void ED_view3d_update_viewmat(
106         Depsgraph *depsgraph, Scene *scene, View3D *v3d, ARegion *ar,
107         float viewmat[4][4], float winmat[4][4], const rcti *rect)
108 {
109         RegionView3D *rv3d = ar->regiondata;
110
111         /* setup window matrices */
112         if (winmat)
113                 copy_m4_m4(rv3d->winmat, winmat);
114         else
115                 view3d_winmatrix_set(depsgraph, ar, v3d, rect);
116
117         /* setup view matrix */
118         if (viewmat) {
119                 copy_m4_m4(rv3d->viewmat, viewmat);
120         }
121         else {
122                 float rect_scale[2];
123                 if (rect) {
124                         rect_scale[0] = (float)BLI_rcti_size_x(rect) / (float)ar->winx;
125                         rect_scale[1] = (float)BLI_rcti_size_y(rect) / (float)ar->winy;
126                 }
127                 /* note: calls BKE_object_where_is_calc for camera... */
128                 view3d_viewmatrix_set(depsgraph, scene, v3d, rv3d, rect ? rect_scale : NULL);
129         }
130         /* update utility matrices */
131         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
132         invert_m4_m4(rv3d->persinv, rv3d->persmat);
133         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
134
135         /* calculate GLSL view dependent values */
136
137         /* store window coordinates scaling/offset */
138         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
139                 rctf cameraborder;
140                 ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &cameraborder, false);
141                 rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
142                 rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
143
144                 rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
145                 rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
146         }
147         else {
148                 rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
149                 rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
150         }
151
152         /* calculate pixelsize factor once, is used for lamps and obcenters */
153         {
154                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
155                  * because of float point precision problems at large values [#23908] */
156                 float v1[3], v2[3];
157                 float len_px, len_sc;
158
159                 v1[0] = rv3d->persmat[0][0];
160                 v1[1] = rv3d->persmat[1][0];
161                 v1[2] = rv3d->persmat[2][0];
162
163                 v2[0] = rv3d->persmat[0][1];
164                 v2[1] = rv3d->persmat[1][1];
165                 v2[2] = rv3d->persmat[2][1];
166
167                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
168                 len_sc = (float)MAX2(ar->winx, ar->winy);
169
170                 rv3d->pixsize = len_px / len_sc;
171         }
172 }
173
174 static void view3d_main_region_setup_view(
175         Depsgraph *depsgraph, Scene *scene,
176         View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
177 {
178         RegionView3D *rv3d = ar->regiondata;
179
180         ED_view3d_update_viewmat(depsgraph, scene, v3d, ar, viewmat, winmat, rect);
181
182         /* set for opengl */
183         gpuLoadProjectionMatrix(rv3d->winmat);
184         gpuLoadMatrix(rv3d->viewmat);
185 }
186
187 static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
188 {
189         if ((scene->r.scemode & R_MULTIVIEW) == 0) {
190                 return false;
191         }
192
193         if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
194                 return false;
195         }
196
197         switch (v3d->stereo3d_camera) {
198                 case STEREO_MONO_ID:
199                         return false;
200                         break;
201                 case STEREO_3D_ID:
202                         /* win will be NULL when calling this from the selection or draw loop. */
203                         if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
204                                 return false;
205                         }
206                         if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
207                             !BKE_scene_multiview_is_stereo3d(&scene->r))
208                         {
209                                 return false;
210                         }
211                         break;
212                 /* We always need the stereo calculation for left and right cameras. */
213                 case STEREO_LEFT_ID:
214                 case STEREO_RIGHT_ID:
215                 default:
216                         break;
217         }
218         return true;
219 }
220
221
222 /* setup the view and win matrices for the multiview cameras
223  *
224  * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
225  * we have no winmatrix (i.e., projection matrix) defined at that time.
226  * Since the camera and the camera shift are needed for the winmat calculation
227  * we do a small hack to replace it temporarily so we don't need to change the
228  * view3d)main_region_setup_view() code to account for that.
229  */
230 static void view3d_stereo3d_setup(
231         Depsgraph *depsgraph, Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect)
232 {
233         bool is_left;
234         const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
235         const char *viewname;
236
237         /* show only left or right camera */
238         if (v3d->stereo3d_camera != STEREO_3D_ID)
239                 v3d->multiview_eye = v3d->stereo3d_camera;
240
241         is_left = v3d->multiview_eye == STEREO_LEFT_ID;
242         viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
243
244         /* update the viewport matrices with the new camera */
245         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
246                 Camera *data;
247                 float viewmat[4][4];
248                 float shiftx;
249
250                 data = (Camera *)v3d->camera->data;
251                 shiftx = data->shiftx;
252
253                 BLI_thread_lock(LOCK_VIEW3D);
254                 data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
255
256                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
257                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, NULL, rect);
258
259                 data->shiftx = shiftx;
260                 BLI_thread_unlock(LOCK_VIEW3D);
261         }
262         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
263                 float viewmat[4][4];
264                 Object *view_ob = v3d->camera;
265                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
266
267                 BLI_thread_lock(LOCK_VIEW3D);
268                 v3d->camera = camera;
269
270                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
271                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, NULL, rect);
272
273                 v3d->camera = view_ob;
274                 BLI_thread_unlock(LOCK_VIEW3D);
275         }
276 }
277
278 /**
279  * Set the correct matrices
280  */
281 void ED_view3d_draw_setup_view(
282         wmWindow *win, Depsgraph *depsgraph, Scene *scene, ARegion *ar, View3D *v3d,
283         float viewmat[4][4], float winmat[4][4], const rcti *rect)
284 {
285         RegionView3D *rv3d = ar->regiondata;
286
287         /* Setup the view matrix. */
288         if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
289                 view3d_stereo3d_setup(depsgraph, scene, v3d, ar, rect);
290         }
291         else {
292                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, rect);
293         }
294 }
295
296 /* ******************** view border ***************** */
297
298 static void view3d_camera_border(
299         const Scene *scene, struct Depsgraph *depsgraph,
300         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
301         rctf *r_viewborder, const bool no_shift, const bool no_zoom)
302 {
303         CameraParams params;
304         rctf rect_view, rect_camera;
305
306         /* get viewport viewplane */
307         BKE_camera_params_init(&params);
308         BKE_camera_params_from_view3d(&params, depsgraph, v3d, rv3d);
309         if (no_zoom)
310                 params.zoom = 1.0f;
311         BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
312         rect_view = params.viewplane;
313
314         /* get camera viewplane */
315         BKE_camera_params_init(&params);
316         /* fallback for non camera objects */
317         params.clipsta = v3d->near;
318         params.clipend = v3d->far;
319         BKE_camera_params_from_object(&params, v3d->camera);
320         if (no_shift) {
321                 params.shiftx = 0.0f;
322                 params.shifty = 0.0f;
323         }
324         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
325         rect_camera = params.viewplane;
326
327         /* get camera border within viewport */
328         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
329         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
330         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
331         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
332 }
333
334 void ED_view3d_calc_camera_border_size(
335         const Scene *scene, Depsgraph *depsgraph,
336         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
337         float r_size[2])
338 {
339         rctf viewborder;
340
341         view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, true, true);
342         r_size[0] = BLI_rctf_size_x(&viewborder);
343         r_size[1] = BLI_rctf_size_y(&viewborder);
344 }
345
346 void ED_view3d_calc_camera_border(
347         const Scene *scene, Depsgraph *depsgraph,
348         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
349         rctf *r_viewborder, const bool no_shift)
350 {
351         view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, r_viewborder, no_shift, false);
352 }
353
354 static void drawviewborder_grid3(uint shdr_pos, float x1, float x2, float y1, float y2, float fac)
355 {
356         float x3, y3, x4, y4;
357
358         x3 = x1 + fac * (x2 - x1);
359         y3 = y1 + fac * (y2 - y1);
360         x4 = x1 + (1.0f - fac) * (x2 - x1);
361         y4 = y1 + (1.0f - fac) * (y2 - y1);
362
363         immBegin(GWN_PRIM_LINES, 8);
364
365         immVertex2f(shdr_pos, x1, y3);
366         immVertex2f(shdr_pos, x2, y3);
367
368         immVertex2f(shdr_pos, x1, y4);
369         immVertex2f(shdr_pos, x2, y4);
370
371         immVertex2f(shdr_pos, x3, y1);
372         immVertex2f(shdr_pos, x3, y2);
373
374         immVertex2f(shdr_pos, x4, y1);
375         immVertex2f(shdr_pos, x4, y2);
376
377         immEnd();
378 }
379
380 /* harmonious triangle */
381 static void drawviewborder_triangle(
382         uint shdr_pos, float x1, float x2, float y1, float y2, const char golden, const char dir)
383 {
384         float ofs;
385         float w = x2 - x1;
386         float h = y2 - y1;
387
388         immBegin(GWN_PRIM_LINES, 6);
389
390         if (w > h) {
391                 if (golden) {
392                         ofs = w * (1.0f - (1.0f / 1.61803399f));
393                 }
394                 else {
395                         ofs = h * (h / w);
396                 }
397                 if (dir == 'B') SWAP(float, y1, y2);
398
399                 immVertex2f(shdr_pos, x1, y1);
400                 immVertex2f(shdr_pos, x2, y2);
401
402                 immVertex2f(shdr_pos, x2, y1);
403                 immVertex2f(shdr_pos, x1 + (w - ofs), y2);
404
405                 immVertex2f(shdr_pos, x1, y2);
406                 immVertex2f(shdr_pos, x1 + ofs, y1);
407         }
408         else {
409                 if (golden) {
410                         ofs = h * (1.0f - (1.0f / 1.61803399f));
411                 }
412                 else {
413                         ofs = w * (w / h);
414                 }
415                 if (dir == 'B') SWAP(float, x1, x2);
416
417                 immVertex2f(shdr_pos, x1, y1);
418                 immVertex2f(shdr_pos, x2, y2);
419
420                 immVertex2f(shdr_pos, x2, y1);
421                 immVertex2f(shdr_pos, x1, y1 + ofs);
422
423                 immVertex2f(shdr_pos, x1, y2);
424                 immVertex2f(shdr_pos, x2, y1 + (h - ofs));
425         }
426
427         immEnd();
428 }
429
430 static void drawviewborder(Scene *scene, Depsgraph *depsgraph, ARegion *ar, View3D *v3d)
431 {
432         float x1, x2, y1, y2;
433         float x1i, x2i, y1i, y2i;
434
435         rctf viewborder;
436         Camera *ca = NULL;
437         RegionView3D *rv3d = ar->regiondata;
438
439         if (v3d->camera == NULL)
440                 return;
441         if (v3d->camera->type == OB_CAMERA)
442                 ca = v3d->camera->data;
443         
444         ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, false);
445         /* the offsets */
446         x1 = viewborder.xmin;
447         y1 = viewborder.ymin;
448         x2 = viewborder.xmax;
449         y2 = viewborder.ymax;
450         
451         glLineWidth(1.0f);
452
453         /* apply offsets so the real 3D camera shows through */
454
455         /* note: quite un-scientific but without this bit extra
456          * 0.0001 on the lower left the 2D border sometimes
457          * obscures the 3D camera border */
458         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
459          * but keep it here in case we need to remove the workaround */
460         x1i = (int)(x1 - 1.0001f);
461         y1i = (int)(y1 - 1.0001f);
462         x2i = (int)(x2 + (1.0f - 0.0001f));
463         y2i = (int)(y2 + (1.0f - 0.0001f));
464
465         uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
466
467         /* First, solid lines. */
468         {
469                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
470
471                 /* passepartout, specified in camera edit buttons */
472                 if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
473                         const float winx = (ar->winx + 1);
474                         const float winy = (ar->winy + 1);
475
476                         float alpha = 1.0f;
477
478                         if (ca->passepartalpha != 1.0f) {
479                                 glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
480                                 glEnable(GL_BLEND);
481                                 alpha = ca->passepartalpha;
482                         }
483
484                         immUniformColor4f(0.0f, 0.0f, 0.0f, alpha);
485
486                         if (x1i > 0.0f)
487                                 immRectf(shdr_pos, 0.0f, winy, x1i, 0.0f);
488                         if (x2i < winx)
489                                 immRectf(shdr_pos, x2i, winy, winx, 0.0f);
490                         if (y2i < winy)
491                                 immRectf(shdr_pos, x1i, winy, x2i, y2i);
492                         if (y2i > 0.0f)
493                                 immRectf(shdr_pos, x1i, y1i, x2i, 0.0f);
494
495                         glDisable(GL_BLEND);
496                 }
497
498                 immUniformThemeColor(TH_BACK);
499                 imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
500
501 #ifdef VIEW3D_CAMERA_BORDER_HACK
502                 if (view3d_camera_border_hack_test == true) {
503                         immUniformColor3ubv(view3d_camera_border_hack_col);
504                         imm_draw_box_wire_2d(shdr_pos, x1i + 1, y1i + 1, x2i - 1, y2i - 1);
505                         view3d_camera_border_hack_test = false;
506                 }
507 #endif
508
509                 immUnbindProgram();
510         }
511
512         /* And now, the dashed lines! */
513         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
514
515         {
516                 float viewport_size[4];
517                 glGetFloatv(GL_VIEWPORT, viewport_size);
518                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
519
520                 immUniform1i("num_colors", 0);  /* "simple" mode */
521                 immUniform1f("dash_width", 6.0f);
522                 immUniform1f("dash_factor", 0.5f);
523
524                 /* outer line not to confuse with object selection */
525                 if (v3d->flag2 & V3D_LOCK_CAMERA) {
526                         immUniformThemeColor(TH_REDALERT);
527                         imm_draw_box_wire_2d(shdr_pos, x1i - 1, y1i - 1, x2i + 1, y2i + 1);
528                 }
529
530                 immUniformThemeColor(TH_VIEW_OVERLAY);
531                 imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
532         }
533
534         /* border */
535         if (scene->r.mode & R_BORDER) {
536                 float x3, y3, x4, y4;
537
538                 x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
539                 y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
540                 x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
541                 y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
542
543                 immUniformColor3f(1.0f, 0.25f, 0.25f);
544                 imm_draw_box_wire_2d(shdr_pos, x3, y3, x4, y4);
545         }
546
547         /* safety border */
548         if (ca) {
549                 immUniformThemeColorBlend(TH_VIEW_OVERLAY, TH_BACK, 0.25f);
550
551                 if (ca->dtx & CAM_DTX_CENTER) {
552                         float x3, y3;
553
554                         x3 = x1 + 0.5f * (x2 - x1);
555                         y3 = y1 + 0.5f * (y2 - y1);
556
557                         immBegin(GWN_PRIM_LINES, 4);
558
559                         immVertex2f(shdr_pos, x1, y3);
560                         immVertex2f(shdr_pos, x2, y3);
561
562                         immVertex2f(shdr_pos, x3, y1);
563                         immVertex2f(shdr_pos, x3, y2);
564
565                         immEnd();
566                 }
567
568                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
569                         immBegin(GWN_PRIM_LINES, 4);
570
571                         immVertex2f(shdr_pos, x1, y1);
572                         immVertex2f(shdr_pos, x2, y2);
573
574                         immVertex2f(shdr_pos, x1, y2);
575                         immVertex2f(shdr_pos, x2, y1);
576
577                         immEnd();
578                 }
579
580                 if (ca->dtx & CAM_DTX_THIRDS) {
581                         drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f / 3.0f);
582                 }
583
584                 if (ca->dtx & CAM_DTX_GOLDEN) {
585                         drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
586                 }
587
588                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
589                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'A');
590                 }
591
592                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
593                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'B');
594                 }
595
596                 if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
597                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'A');
598                 }
599
600                 if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
601                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'B');
602                 }
603
604                 if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
605                         UI_draw_safe_areas(
606                                 shdr_pos, x1, x2, y1, y2,
607                                 scene->safe_areas.title, scene->safe_areas.action);
608
609                         if (ca->flag & CAM_SHOW_SAFE_CENTER) {
610                                 UI_draw_safe_areas(
611                                         shdr_pos, x1, x2, y1, y2,
612                                         scene->safe_areas.title_center, scene->safe_areas.action_center);
613                         }
614                 }
615
616                 if (ca->flag & CAM_SHOWSENSOR) {
617                         /* determine sensor fit, and get sensor x/y, for auto fit we
618                          * assume and square sensor and only use sensor_x */
619                         float sizex = scene->r.xsch * scene->r.xasp;
620                         float sizey = scene->r.ysch * scene->r.yasp;
621                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
622                         float sensor_x = ca->sensor_x;
623                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
624
625                         /* determine sensor plane */
626                         rctf rect;
627
628                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
629                                 float sensor_scale = (x2i - x1i) / sensor_x;
630                                 float sensor_height = sensor_scale * sensor_y;
631
632                                 rect.xmin = x1i;
633                                 rect.xmax = x2i;
634                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
635                                 rect.ymax = rect.ymin + sensor_height;
636                         }
637                         else {
638                                 float sensor_scale = (y2i - y1i) / sensor_y;
639                                 float sensor_width = sensor_scale * sensor_x;
640
641                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
642                                 rect.xmax = rect.xmin + sensor_width;
643                                 rect.ymin = y1i;
644                                 rect.ymax = y2i;
645                         }
646
647                         /* draw */
648                         immUniformThemeColorShade(TH_VIEW_OVERLAY, 100);
649                         
650                         /* TODO Was using UI_draw_roundbox_4fv(false, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color).
651                          * We'll probably need a new imm_draw_line_roundbox_dashed dor that - though in practice the
652                          * 2.0f round corner effect was nearly not visible anyway... */
653                         imm_draw_box_wire_2d(shdr_pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
654                 }
655         }
656
657         immUnbindProgram();
658         /* end dashed lines */
659
660         /* camera name - draw in highlighted text color */
661         if (ca && (ca->flag & CAM_SHOWNAME)) {
662                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
663                 BLF_draw_default(
664                         x1i, y1i - (0.7f * U.widget_unit), 0.0f,
665                         v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
666         }
667 }
668
669 static void drawrenderborder(ARegion *ar, View3D *v3d)
670 {
671         /* use the same program for everything */
672         uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
673
674         glLineWidth(1.0f);
675
676         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
677
678         float viewport_size[4];
679         glGetFloatv(GL_VIEWPORT, viewport_size);
680         immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
681
682         immUniform1i("num_colors", 0);  /* "simple" mode */
683         immUniform4f("color", 1.0f, 0.25f, 0.25f, 1.0f);
684         immUniform1f("dash_width", 6.0f);
685         immUniform1f("dash_factor", 0.5f);
686
687         imm_draw_box_wire_2d(shdr_pos,
688                           v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
689                           v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
690
691         immUnbindProgram();
692 }
693
694 void ED_view3d_draw_depth(
695         Depsgraph *depsgraph,
696         ARegion *ar, View3D *v3d, bool alphaoverride)
697 {
698         struct bThemeState theme_state;
699         Scene *scene = DEG_get_evaluated_scene(depsgraph);
700         RegionView3D *rv3d = ar->regiondata;
701
702         short zbuf = v3d->zbuf;
703         short flag = v3d->flag;
704         float glalphaclip = U.glalphaclip;
705         int obcenter_dia = U.obcenter_dia;
706         /* temp set drawtype to solid */
707         /* Setting these temporarily is not nice */
708         v3d->flag &= ~V3D_SELECT_OUTLINE;
709         U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
710         U.obcenter_dia = 0;
711
712         /* Tools may request depth outside of regular drawing code. */
713         UI_Theme_Store(&theme_state);
714         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
715
716         ED_view3d_draw_setup_view(NULL, depsgraph, scene, ar, v3d, NULL, NULL, NULL);
717
718         glClear(GL_DEPTH_BUFFER_BIT);
719
720         if (rv3d->rflag & RV3D_CLIPPING) {
721                 ED_view3d_clipping_set(rv3d);
722         }
723         /* get surface depth without bias */
724         rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
725
726         v3d->zbuf = true;
727         glEnable(GL_DEPTH_TEST);
728
729         DRW_draw_depth_loop(depsgraph, ar, v3d);
730
731         if (rv3d->rflag & RV3D_CLIPPING) {
732                 ED_view3d_clipping_disable();
733         }
734         rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
735
736         v3d->zbuf = zbuf;
737         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
738
739         U.glalphaclip = glalphaclip;
740         v3d->flag = flag;
741         U.obcenter_dia = obcenter_dia;
742
743         UI_Theme_Restore(&theme_state);
744 }
745
746 /* ******************** other elements ***************** */
747
748 /** could move this elsewhere, but tied into #ED_view3d_grid_scale */
749 float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
750 {
751         /* apply units */
752         if (scene->unit.system) {
753                 const void *usys;
754                 int len;
755
756                 bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
757
758                 if (usys) {
759                         int i = bUnit_GetBaseUnit(usys);
760                         if (grid_unit)
761                                 *grid_unit = bUnit_GetNameDisplay(usys, i);
762                         return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
763                 }
764         }
765
766         return 1.0f;
767 }
768
769 float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
770 {
771         return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
772 }
773
774 static void draw_view_axis(RegionView3D *rv3d, const rcti *rect)
775 {
776         const float k = U.rvisize * U.pixelsize;  /* axis size */
777         const int bright = - 20 * (10 - U.rvibright);  /* axis alpha offset (rvibright has range 0-10) */
778
779         const float startx = rect->xmin + k + 1.0f;  /* axis center in screen coordinates, x=y */
780         const float starty = rect->ymin + k + 1.0f;
781
782         float axis_pos[3][2];
783         unsigned char axis_col[3][4];
784
785         int axis_order[3] = {0, 1, 2};
786         axis_sort_v3(rv3d->viewinv[2], axis_order);
787
788         for (int axis_i = 0; axis_i < 3; axis_i++) {
789                 int i = axis_order[axis_i];
790
791                 /* get position of each axis tip on screen */
792                 float vec[3] = { 0.0f };
793                 vec[i] = 1.0f;
794                 mul_qt_v3(rv3d->viewquat, vec);
795                 axis_pos[i][0] = startx + vec[0] * k;
796                 axis_pos[i][1] = starty + vec[1] * k;
797
798                 /* get color of each axis */
799                 UI_GetThemeColorShade3ubv(TH_AXIS_X + i, bright, axis_col[i]); /* rgb */
800                 axis_col[i][3] = 255 * hypotf(vec[0], vec[1]); /* alpha */
801         }
802
803         /* draw axis lines */
804         glLineWidth(2.0f);
805         glEnable(GL_LINE_SMOOTH);
806         glEnable(GL_BLEND);
807         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
808
809         Gwn_VertFormat *format = immVertexFormat();
810         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
811         unsigned int col = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 4, GWN_FETCH_INT_TO_FLOAT_UNIT);
812
813         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
814         immBegin(GWN_PRIM_LINES, 6);
815
816         for (int axis_i = 0; axis_i < 3; axis_i++) {
817                 int i = axis_order[axis_i];
818
819                 immAttrib4ubv(col, axis_col[i]);
820                 immVertex2f(pos, startx, starty);
821                 immAttrib4ubv(col, axis_col[i]);
822                 immVertex2fv(pos, axis_pos[i]);
823         }
824
825         immEnd();
826         immUnbindProgram();
827         glDisable(GL_LINE_SMOOTH);
828
829         /* draw axis names */
830         for (int axis_i = 0; axis_i < 3; axis_i++) {
831                 int i = axis_order[axis_i];
832
833                 const char axis_text[2] = {'x' + i, '\0'};
834                 BLF_color4ubv(BLF_default(), axis_col[i]);
835                 BLF_draw_default_ascii(axis_pos[i][0] + 2, axis_pos[i][1] + 2, 0.0f, axis_text, 1);
836         }
837 }
838
839 #ifdef WITH_INPUT_NDOF
840 /* draw center and axis of rotation for ongoing 3D mouse navigation */
841 static void UNUSED_FUNCTION(draw_rotation_guide)(RegionView3D *rv3d)
842 {
843         float o[3];    /* center of rotation */
844         float end[3];  /* endpoints for drawing */
845
846         GLubyte color[4] = {0, 108, 255, 255};  /* bright blue so it matches device LEDs */
847
848         negate_v3_v3(o, rv3d->ofs);
849
850         glEnable(GL_BLEND);
851         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
852         glDepthMask(GL_FALSE);  /* don't overwrite zbuf */
853
854         Gwn_VertFormat *format = immVertexFormat();
855         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
856         unsigned int col = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 4, GWN_FETCH_INT_TO_FLOAT_UNIT);
857
858         immBindBuiltinProgram(GPU_SHADER_3D_SMOOTH_COLOR);
859
860         if (rv3d->rot_angle != 0.0f) {
861                 /* -- draw rotation axis -- */
862                 float scaled_axis[3];
863                 const float scale = rv3d->dist;
864                 mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
865
866
867                 immBegin(GWN_PRIM_LINE_STRIP, 3);
868                 color[3] = 0; /* more transparent toward the ends */
869                 immAttrib4ubv(col, color);
870                 add_v3_v3v3(end, o, scaled_axis);
871                 immVertex3fv(pos, end);
872
873 #if 0
874                 color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
875                 /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
876 #endif
877
878                 color[3] = 127; /* more opaque toward the center */
879                 immAttrib4ubv(col, color);
880                 immVertex3fv(pos, o);
881
882                 color[3] = 0;
883                 immAttrib4ubv(col, color);
884                 sub_v3_v3v3(end, o, scaled_axis);
885                 immVertex3fv(pos, end);
886                 immEnd();
887                 
888                 /* -- draw ring around rotation center -- */
889                 {
890 #define     ROT_AXIS_DETAIL 13
891
892                         const float s = 0.05f * scale;
893                         const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
894
895                         float q[4];  /* rotate ring so it's perpendicular to axis */
896                         const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
897                         if (!upright) {
898                                 const float up[3] = {0.0f, 0.0f, 1.0f};
899                                 float vis_angle, vis_axis[3];
900
901                                 cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
902                                 vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
903                                 axis_angle_to_quat(q, vis_axis, vis_angle);
904                         }
905
906                         immBegin(GWN_PRIM_LINE_LOOP, ROT_AXIS_DETAIL);
907                         color[3] = 63; /* somewhat faint */
908                         immAttrib4ubv(col, color);
909                         float angle = 0.0f;
910                         for (int i = 0; i < ROT_AXIS_DETAIL; ++i, angle += step) {
911                                 float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
912
913                                 if (!upright) {
914                                         mul_qt_v3(q, p);
915                                 }
916
917                                 add_v3_v3(p, o);
918                                 immVertex3fv(pos, p);
919                         }
920                         immEnd();
921
922 #undef      ROT_AXIS_DETAIL
923                 }
924
925                 color[3] = 255;  /* solid dot */
926         }
927         else
928                 color[3] = 127;  /* see-through dot */
929
930         immUnbindProgram();
931
932         /* -- draw rotation center -- */
933         immBindBuiltinProgram(GPU_SHADER_3D_POINT_FIXED_SIZE_VARYING_COLOR);
934         glPointSize(5.0f);
935         immBegin(GWN_PRIM_POINTS, 1);
936         immAttrib4ubv(col, color);
937         immVertex3fv(pos, o);
938         immEnd();
939         immUnbindProgram();
940
941 #if 0
942         /* find screen coordinates for rotation center, then draw pretty icon */
943         mul_m4_v3(rv3d->persinv, rot_center);
944         UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
945         /* ^^ just playing around, does not work */
946 #endif
947
948         glDisable(GL_BLEND);
949         glDepthMask(GL_TRUE);
950 }
951 #endif /* WITH_INPUT_NDOF */
952
953 /* ******************** info ***************** */
954
955 /**
956 * Render and camera border
957 */
958 static void view3d_draw_border(const bContext *C, ARegion *ar)
959 {
960         Scene *scene = CTX_data_scene(C);
961         Depsgraph *depsgraph = CTX_data_depsgraph(C);
962         RegionView3D *rv3d = ar->regiondata;
963         View3D *v3d = CTX_wm_view3d(C);
964
965         if (rv3d->persp == RV3D_CAMOB) {
966                 drawviewborder(scene, depsgraph, ar, v3d);
967         }
968         else if (v3d->flag2 & V3D_RENDER_BORDER) {
969                 drawrenderborder(ar, v3d);
970         }
971 }
972
973 /**
974 * Grease Pencil
975 */
976 static void view3d_draw_grease_pencil(const bContext *UNUSED(C))
977 {
978         /* TODO viewport */
979 }
980
981 /**
982 * Viewport Name
983 */
984 static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
985 {
986         const char *name = NULL;
987
988         switch (rv3d->view) {
989                 case RV3D_VIEW_FRONT:
990                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Front Ortho");
991                         else name = IFACE_("Front Persp");
992                         break;
993                 case RV3D_VIEW_BACK:
994                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Back Ortho");
995                         else name = IFACE_("Back Persp");
996                         break;
997                 case RV3D_VIEW_TOP:
998                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Top Ortho");
999                         else name = IFACE_("Top Persp");
1000                         break;
1001                 case RV3D_VIEW_BOTTOM:
1002                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Bottom Ortho");
1003                         else name = IFACE_("Bottom Persp");
1004                         break;
1005                 case RV3D_VIEW_RIGHT:
1006                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Right Ortho");
1007                         else name = IFACE_("Right Persp");
1008                         break;
1009                 case RV3D_VIEW_LEFT:
1010                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Left Ortho");
1011                         else name = IFACE_("Left Persp");
1012                         break;
1013
1014                 default:
1015                         if (rv3d->persp == RV3D_CAMOB) {
1016                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
1017                                         Camera *cam;
1018                                         cam = v3d->camera->data;
1019                                         if (cam->type == CAM_PERSP) {
1020                                                 name = IFACE_("Camera Persp");
1021                                         }
1022                                         else if (cam->type == CAM_ORTHO) {
1023                                                 name = IFACE_("Camera Ortho");
1024                                         }
1025                                         else {
1026                                                 BLI_assert(cam->type == CAM_PANO);
1027                                                 name = IFACE_("Camera Pano");
1028                                         }
1029                                 }
1030                                 else {
1031                                         name = IFACE_("Object as Camera");
1032                                 }
1033                         }
1034                         else {
1035                                 name = (rv3d->persp == RV3D_ORTHO) ? IFACE_("User Ortho") : IFACE_("User Persp");
1036                         }
1037         }
1038
1039         return name;
1040 }
1041
1042 static void draw_viewport_name(ARegion *ar, View3D *v3d, const rcti *rect)
1043 {
1044         RegionView3D *rv3d = ar->regiondata;
1045         const char *name = view3d_get_name(v3d, rv3d);
1046         /* increase size for unicode languages (Chinese in utf-8...) */
1047 #ifdef WITH_INTERNATIONAL
1048         char tmpstr[96];
1049 #else
1050         char tmpstr[32];
1051 #endif
1052
1053         if (v3d->localvd) {
1054                 BLI_snprintf(tmpstr, sizeof(tmpstr), IFACE_("%s (Local)"), name);
1055                 name = tmpstr;
1056         }
1057
1058         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1059 #ifdef WITH_INTERNATIONAL
1060         BLF_draw_default(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
1061 #else
1062         BLF_draw_default_ascii(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
1063 #endif
1064 }
1065
1066 /**
1067  * draw info beside axes in bottom left-corner:
1068  * framenum, object name, bone name (if available), marker name (if available)
1069  */
1070
1071 static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
1072 {
1073         const int cfra = CFRA;
1074         const char *msg_pin = " (Pinned)";
1075         const char *msg_sep = " : ";
1076
1077         const int font_id = BLF_default();
1078
1079         char info[300];
1080         char *s = info;
1081         short offset = 1.5f * UI_UNIT_X + rect->xmin;
1082
1083         s += sprintf(s, "(%d)", cfra);
1084
1085         /*
1086          * info can contain:
1087          * - a frame (7 + 2)
1088          * - 3 object names (MAX_NAME)
1089          * - 2 BREAD_CRUMB_SEPARATORs (6)
1090          * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
1091          * - a marker name (MAX_NAME + 3)
1092          */
1093
1094         /* get name of marker on current frame (if available) */
1095         const char *markern = BKE_scene_find_marker_name(scene, cfra);
1096
1097         /* check if there is an object */
1098         if (ob) {
1099                 *s++ = ' ';
1100                 s += BLI_strcpy_rlen(s, ob->id.name + 2);
1101
1102                 /* name(s) to display depends on type of object */
1103                 if (ob->type == OB_ARMATURE) {
1104                         bArmature *arm = ob->data;
1105
1106                         /* show name of active bone too (if possible) */
1107                         if (arm->edbo) {
1108                                 if (arm->act_edbone) {
1109                                         s += BLI_strcpy_rlen(s, msg_sep);
1110                                         s += BLI_strcpy_rlen(s, arm->act_edbone->name);
1111                                 }
1112                         }
1113                         else if (ob->mode & OB_MODE_POSE) {
1114                                 if (arm->act_bone) {
1115
1116                                         if (arm->act_bone->layer & arm->layer) {
1117                                                 s += BLI_strcpy_rlen(s, msg_sep);
1118                                                 s += BLI_strcpy_rlen(s, arm->act_bone->name);
1119                                         }
1120                                 }
1121                         }
1122                 }
1123                 else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
1124                         /* try to display active bone and active shapekey too (if they exist) */
1125
1126                         if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
1127                                 Object *armobj = BKE_object_pose_armature_get(ob);
1128                                 if (armobj  && armobj->mode & OB_MODE_POSE) {
1129                                         bArmature *arm = armobj->data;
1130                                         if (arm->act_bone) {
1131                                                 if (arm->act_bone->layer & arm->layer) {
1132                                                         s += BLI_strcpy_rlen(s, msg_sep);
1133                                                         s += BLI_strcpy_rlen(s, arm->act_bone->name);
1134                                                 }
1135                                         }
1136                                 }
1137                         }
1138
1139                         Key *key = BKE_key_from_object(ob);
1140                         if (key) {
1141                                 KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
1142                                 if (kb) {
1143                                         s += BLI_strcpy_rlen(s, msg_sep);
1144                                         s += BLI_strcpy_rlen(s, kb->name);
1145                                         if (ob->shapeflag & OB_SHAPE_LOCK) {
1146                                                 s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
1147                                         }
1148                                 }
1149                         }
1150                 }
1151
1152                 /* color depends on whether there is a keyframe */
1153                 if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
1154                         UI_FontThemeColor(font_id, TH_TIME_KEYFRAME);
1155                 else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
1156                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
1157                 else
1158                         UI_FontThemeColor(font_id, TH_TEXT_HI);
1159         }
1160         else {
1161                 /* no object */
1162                 if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
1163                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
1164                 else
1165                         UI_FontThemeColor(font_id, TH_TEXT_HI);
1166         }
1167
1168         if (markern) {
1169                 s += sprintf(s, " <%s>", markern);
1170         }
1171
1172         if (U.uiflag & USER_SHOW_ROTVIEWICON)
1173                 offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
1174
1175         BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
1176 }
1177
1178 /* ******************** view loop ***************** */
1179
1180 /**
1181 * Information drawn on top of the solid plates and composed data
1182 */
1183 void view3d_draw_region_info(const bContext *C, ARegion *ar, const int offset)
1184 {
1185         RegionView3D *rv3d = ar->regiondata;
1186         View3D *v3d = CTX_wm_view3d(C);
1187         Scene *scene = CTX_data_scene(C);
1188         wmWindowManager *wm = CTX_wm_manager(C);
1189
1190         /* correct projection matrix */
1191         ED_region_pixelspace(ar);
1192
1193         /* local coordinate visible rect inside region, to accomodate overlapping ui */
1194         rcti rect;
1195         ED_region_visible_rect(ar, &rect);
1196
1197         /* Leave room for previously drawn info. */
1198         rect.ymax -= offset;
1199
1200         view3d_draw_border(C, ar);
1201         view3d_draw_grease_pencil(C);
1202
1203         BLF_batch_draw_begin();
1204
1205         if (U.uiflag & USER_SHOW_ROTVIEWICON) {
1206                 draw_view_axis(rv3d, &rect);
1207         }
1208
1209         if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
1210                 ED_scene_draw_fps(scene, &rect);
1211         }
1212         else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
1213                 draw_viewport_name(ar, v3d, &rect);
1214         }
1215
1216         if (U.uiflag & USER_DRAWVIEWINFO) {
1217                 ViewLayer *view_layer = CTX_data_view_layer(C);
1218                 Object *ob = OBACT(view_layer);
1219                 draw_selected_name(scene, ob, &rect);
1220         }
1221
1222 #if 0 /* TODO */
1223         if (grid_unit) { /* draw below the viewport name */
1224                 char numstr[32] = "";
1225
1226                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1227                 if (v3d->grid != 1.0f) {
1228                         BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
1229                 }
1230
1231                 BLF_draw_default_ascii(rect.xmin + U.widget_unit,
1232                                        rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
1233                                        numstr[0] ? numstr : grid_unit, sizeof(numstr));
1234         }
1235 #endif
1236         BLF_batch_draw_end();
1237 }
1238
1239 static void view3d_draw_view(const bContext *C, ARegion *ar)
1240 {
1241         ED_view3d_draw_setup_view(CTX_wm_window(C), CTX_data_depsgraph(C), CTX_data_scene(C), ar, CTX_wm_view3d(C), NULL, NULL, NULL);
1242
1243         /* Only 100% compliant on new spec goes bellow */
1244         DRW_draw_view(C);
1245 }
1246
1247 RenderEngineType *ED_view3d_engine_type(Scene *scene, int drawtype)
1248 {
1249         /*
1250          * Tempory viewport draw modes until we have a proper system. 
1251          * all modes are done in the draw manager, except
1252          * cycles material as it is an external render engine.
1253          */
1254         if (strcmp(scene->r.engine, RE_engine_id_CYCLES) == 0 && drawtype == OB_MATERIAL) {
1255                 return RE_engines_find(RE_engine_id_BLENDER_EEVEE);
1256         }
1257         return RE_engines_find(scene->r.engine);
1258 }
1259
1260 void view3d_main_region_draw(const bContext *C, ARegion *ar)
1261 {
1262         View3D *v3d = CTX_wm_view3d(C);
1263
1264         view3d_draw_view(C, ar);
1265
1266         GPU_free_images_old();
1267         GPU_pass_cache_garbage_collect();
1268
1269         /* XXX This is in order to draw UI batches with the DRW
1270          * olg context since we now use it for drawing the entire area */
1271         gpu_batch_presets_reset();
1272
1273         /* No depth test for drawing action zones afterwards. */
1274         glDisable(GL_DEPTH_TEST);
1275
1276         v3d->flag |= V3D_INVALID_BACKBUF;
1277 }
1278
1279 /* -------------------------------------------------------------------- */
1280
1281 /** \name Offscreen Drawing
1282  * \{ */
1283
1284 static void view3d_stereo3d_setup_offscreen(
1285         Depsgraph *depsgraph, Scene *scene, View3D *v3d, ARegion *ar,
1286         float winmat[4][4], const char *viewname)
1287 {
1288         /* update the viewport matrices with the new camera */
1289         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1290                 float viewmat[4][4];
1291                 const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
1292
1293                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
1294                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
1295         }
1296         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
1297                 float viewmat[4][4];
1298                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
1299
1300                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
1301                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
1302         }
1303 }
1304
1305 void ED_view3d_draw_offscreen(
1306         Depsgraph *depsgraph, Scene *scene,
1307         int drawtype,
1308         View3D *v3d, ARegion *ar, int winx, int winy,
1309         float viewmat[4][4], float winmat[4][4],
1310         bool do_sky, bool UNUSED(is_persp), const char *viewname,
1311         GPUFXSettings *UNUSED(fx_settings),
1312         GPUOffScreen *ofs, GPUViewport *viewport)
1313 {
1314         RegionView3D *rv3d = ar->regiondata;
1315         RenderEngineType *engine_type = ED_view3d_engine_type(scene, drawtype);
1316
1317         /* set temporary new size */
1318         int bwinx = ar->winx;
1319         int bwiny = ar->winy;
1320         rcti brect = ar->winrct;
1321
1322         ar->winx = winx;
1323         ar->winy = winy;
1324         ar->winrct.xmin = 0;
1325         ar->winrct.ymin = 0;
1326         ar->winrct.xmax = winx;
1327         ar->winrct.ymax = winy;
1328
1329         struct bThemeState theme_state;
1330         UI_Theme_Store(&theme_state);
1331         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
1332
1333         /* set flags */
1334         G.f |= G_RENDER_OGL;
1335
1336         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
1337                 /* free images which can have changed on frame-change
1338                  * warning! can be slow so only free animated images - campbell */
1339                 GPU_free_images_anim();
1340         }
1341
1342         gpuPushProjectionMatrix();
1343         gpuLoadIdentity();
1344         gpuPushMatrix();
1345         gpuLoadIdentity();
1346
1347         if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
1348                 view3d_stereo3d_setup_offscreen(depsgraph, scene, v3d, ar, winmat, viewname);
1349         else
1350                 view3d_main_region_setup_view(depsgraph, scene, v3d, ar, viewmat, winmat, NULL);
1351
1352         /* main drawing call */
1353         DRW_draw_render_loop_offscreen(
1354                 depsgraph, engine_type, ar, v3d,
1355                 do_sky, ofs, viewport);
1356
1357         /* restore size */
1358         ar->winx = bwinx;
1359         ar->winy = bwiny;
1360         ar->winrct = brect;
1361
1362         gpuPopProjectionMatrix();
1363         gpuPopMatrix();
1364
1365         UI_Theme_Restore(&theme_state);
1366
1367         G.f &= ~G_RENDER_OGL;
1368 }
1369
1370 /**
1371  * Utility func for ED_view3d_draw_offscreen
1372  *
1373  * \param ofs: Optional off-screen buffer, can be NULL.
1374  * (avoids re-creating when doing multiple GL renders).
1375  */
1376 ImBuf *ED_view3d_draw_offscreen_imbuf(
1377         Depsgraph *depsgraph, Scene *scene,
1378         int drawtype,
1379         View3D *v3d, ARegion *ar, int sizex, int sizey,
1380         unsigned int flag, unsigned int draw_flags,
1381         int alpha_mode, int samples, const char *viewname,
1382         /* output vars */
1383         GPUOffScreen *ofs, char err_out[256])
1384 {
1385         RegionView3D *rv3d = ar->regiondata;
1386         const bool draw_sky = (alpha_mode == R_ADDSKY);
1387         const bool use_full_sample = (draw_flags & V3D_OFSDRAW_USE_FULL_SAMPLE);
1388
1389         /* view state */
1390         GPUFXSettings fx_settings = v3d->fx_settings;
1391         bool is_ortho = false;
1392         float winmat[4][4];
1393
1394         if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
1395                 /* sizes differ, can't reuse */
1396                 ofs = NULL;
1397         }
1398
1399         const bool own_ofs = (ofs == NULL);
1400         DRW_opengl_context_enable();
1401
1402         if (own_ofs) {
1403                 /* bind */
1404                 ofs = GPU_offscreen_create(sizex, sizey, use_full_sample ? 0 : samples, true, false, err_out);
1405                 if (ofs == NULL) {
1406                         DRW_opengl_context_disable();
1407                         return NULL;
1408                 }
1409         }
1410
1411         GPU_offscreen_bind(ofs, true);
1412
1413         /* read in pixels & stamp */
1414         ImBuf *ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
1415
1416         /* render 3d view */
1417         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
1418                 CameraParams params;
1419                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
1420
1421                 BKE_camera_params_init(&params);
1422                 /* fallback for non camera objects */
1423                 params.clipsta = v3d->near;
1424                 params.clipend = v3d->far;
1425                 BKE_camera_params_from_object(&params, camera);
1426                 BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
1427                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
1428                 BKE_camera_params_compute_matrix(&params);
1429
1430                 BKE_camera_to_gpu_dof(camera, &fx_settings);
1431
1432                 is_ortho = params.is_ortho;
1433                 copy_m4_m4(winmat, params.winmat);
1434         }
1435         else {
1436                 rctf viewplane;
1437                 float clipsta, clipend;
1438
1439                 is_ortho = ED_view3d_viewplane_get(depsgraph, v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
1440                 if (is_ortho) {
1441                         orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
1442                 }
1443                 else {
1444                         perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
1445                 }
1446         }
1447
1448         if ((samples && use_full_sample) == 0) {
1449                 /* Single-pass render, common case */
1450                 ED_view3d_draw_offscreen(
1451                         depsgraph, scene, drawtype,
1452                         v3d, ar, sizex, sizey, NULL, winmat,
1453                         draw_sky, !is_ortho, viewname,
1454                         &fx_settings, ofs, NULL);
1455
1456                 if (ibuf->rect_float) {
1457                         GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
1458                 }
1459                 else if (ibuf->rect) {
1460                         GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
1461                 }
1462         }
1463         else {
1464                 /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
1465                  * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
1466                 static float jit_ofs[32][2];
1467                 float winmat_jitter[4][4];
1468                 float *rect_temp = (ibuf->rect_float) ? ibuf->rect_float : MEM_mallocN(sizex * sizey * sizeof(float[4]), "rect_temp");
1469                 float *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(float[4]), "accum_buffer");
1470                 GPUViewport *viewport = GPU_viewport_create_from_offscreen(ofs);
1471
1472                 BLI_jitter_init(jit_ofs, samples);
1473
1474                 /* first sample buffer, also initializes 'rv3d->persmat' */
1475                 ED_view3d_draw_offscreen(
1476                         depsgraph, scene, drawtype,
1477                         v3d, ar, sizex, sizey, NULL, winmat,
1478                         draw_sky, !is_ortho, viewname,
1479                         &fx_settings, ofs, viewport);
1480                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, accum_buffer);
1481
1482                 /* skip the first sample */
1483                 for (int j = 1; j < samples; j++) {
1484                         copy_m4_m4(winmat_jitter, winmat);
1485                         window_translate_m4(
1486                                 winmat_jitter, rv3d->persmat,
1487                                 (jit_ofs[j][0] * 2.0f) / sizex,
1488                                 (jit_ofs[j][1] * 2.0f) / sizey);
1489
1490                         ED_view3d_draw_offscreen(
1491                                 depsgraph, scene, drawtype,
1492                                 v3d, ar, sizex, sizey, NULL, winmat_jitter,
1493                                 draw_sky, !is_ortho, viewname,
1494                                 &fx_settings, ofs, viewport);
1495                         GPU_offscreen_read_pixels(ofs, GL_FLOAT, rect_temp);
1496
1497                         unsigned int i = sizex * sizey * 4;
1498                         while (i--) {
1499                                 accum_buffer[i] += rect_temp[i];
1500                         }
1501                 }
1502
1503                 {
1504                         /* don't free data owned by 'ofs' */
1505                         GPU_viewport_clear_from_offscreen(viewport);
1506                         GPU_viewport_free(viewport);
1507                 }
1508
1509                 if (ibuf->rect_float == NULL) {
1510                         MEM_freeN(rect_temp);
1511                 }
1512
1513                 if (ibuf->rect_float) {
1514                         float *rect_float = ibuf->rect_float;
1515                         unsigned int i = sizex * sizey * 4;
1516                         while (i--) {
1517                                 rect_float[i] = accum_buffer[i] / samples;
1518                         }
1519                 }
1520                 else {
1521                         unsigned char *rect_ub = (unsigned char *)ibuf->rect;
1522                         unsigned int i = sizex * sizey * 4;
1523                         while (i--) {
1524                                 rect_ub[i] = (unsigned char)(255.0f * accum_buffer[i] / samples);
1525                         }
1526                 }
1527
1528                 MEM_freeN(accum_buffer);
1529         }
1530
1531         /* unbind */
1532         GPU_offscreen_unbind(ofs, true);
1533
1534         if (own_ofs) {
1535                 GPU_offscreen_free(ofs);
1536         }
1537
1538         DRW_opengl_context_disable();
1539
1540         if (ibuf->rect_float && ibuf->rect)
1541                 IMB_rect_from_float(ibuf);
1542
1543         return ibuf;
1544 }
1545
1546 /**
1547  * Creates own fake 3d views (wrapping #ED_view3d_draw_offscreen_imbuf)
1548  *
1549  * \param ofs: Optional off-screen buffer can be NULL.
1550  * (avoids re-creating when doing multiple GL renders).
1551  *
1552  * \note used by the sequencer
1553  */
1554 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
1555         Depsgraph *depsgraph, Scene *scene,
1556         int drawtype,
1557         Object *camera, int width, int height,
1558         unsigned int flag, unsigned int draw_flags,
1559         int alpha_mode, int samples, const char *viewname,
1560         GPUOffScreen *ofs, char err_out[256])
1561 {
1562         View3D v3d = {NULL};
1563         ARegion ar = {NULL};
1564         RegionView3D rv3d = {{{0}}};
1565
1566         /* connect data */
1567         v3d.regionbase.first = v3d.regionbase.last = &ar;
1568         ar.regiondata = &rv3d;
1569         ar.regiontype = RGN_TYPE_WINDOW;
1570
1571         v3d.camera = camera;
1572         v3d.lay = scene->lay;
1573         v3d.drawtype = drawtype;
1574         v3d.flag2 = V3D_RENDER_OVERRIDE;
1575
1576         if (draw_flags & V3D_OFSDRAW_USE_GPENCIL) {
1577                 v3d.flag2 |= V3D_SHOW_GPENCIL;
1578         }
1579         if (draw_flags & V3D_OFSDRAW_USE_SOLID_TEX) {
1580                 v3d.flag2 |= V3D_SOLID_TEX;
1581         }
1582
1583         v3d.flag3 |= V3D_SHOW_WORLD;
1584
1585         if (draw_flags & V3D_OFSDRAW_USE_CAMERA_DOF) {
1586                 if (camera->type == OB_CAMERA) {
1587                         v3d.fx_settings.dof = &((Camera *)camera->data)->gpu_dof;
1588                         v3d.fx_settings.fx_flag |= GPU_FX_FLAG_DOF;
1589                 }
1590         }
1591
1592         rv3d.persp = RV3D_CAMOB;
1593
1594         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
1595         normalize_m4(rv3d.viewinv);
1596         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
1597
1598         {
1599                 CameraParams params;
1600                 Object *view_camera = BKE_camera_multiview_render(scene, v3d.camera, viewname);
1601
1602                 BKE_camera_params_init(&params);
1603                 BKE_camera_params_from_object(&params, view_camera);
1604                 BKE_camera_multiview_params(&scene->r, &params, view_camera, viewname);
1605                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
1606                 BKE_camera_params_compute_matrix(&params);
1607
1608                 copy_m4_m4(rv3d.winmat, params.winmat);
1609                 v3d.near = params.clipsta;
1610                 v3d.far = params.clipend;
1611                 v3d.lens = params.lens;
1612         }
1613
1614         mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
1615         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
1616
1617         return ED_view3d_draw_offscreen_imbuf(
1618                 depsgraph, scene, drawtype,
1619                 &v3d, &ar, width, height, flag,
1620                 draw_flags, alpha_mode, samples, viewname, ofs, err_out);
1621 }
1622
1623 /** \} */