Grease Pencil dat files fix
[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.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_draw.h"
76 #include "GPU_matrix.h"
77 #include "GPU_immediate.h"
78 #include "GPU_immediate_util.h"
79 #include "GPU_material.h"
80 #include "GPU_viewport.h"
81 #include "GPU_compositing.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 static bool use_depth_doit(Scene *scene, View3D *v3d)
103 {
104         if (v3d->drawtype > OB_WIRE)
105                 return true;
106
107         /* special case (depth for wire color) */
108         if (v3d->drawtype <= OB_WIRE) {
109                 if (scene->obedit && scene->obedit->type == OB_MESH) {
110                         Mesh *me = scene->obedit->data;
111                         if (me->drawflag & ME_DRAWEIGHT) {
112                                 return true;
113                         }
114                 }
115         }
116         return false;
117 }
118
119 /**
120  * \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
121  */
122 void ED_view3d_update_viewmat(
123         const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar,
124         float viewmat[4][4], float winmat[4][4], const rcti *rect)
125 {
126         const Depsgraph *depsgraph = eval_ctx->depsgraph;
127         RegionView3D *rv3d = ar->regiondata;
128
129         /* setup window matrices */
130         if (winmat)
131                 copy_m4_m4(rv3d->winmat, winmat);
132         else
133                 view3d_winmatrix_set(depsgraph, ar, v3d, rect);
134
135         /* setup view matrix */
136         if (viewmat)
137                 copy_m4_m4(rv3d->viewmat, viewmat);
138         else
139                 view3d_viewmatrix_set(eval_ctx, scene, v3d, rv3d);  /* note: calls BKE_object_where_is_calc for camera... */
140
141         /* update utility matrices */
142         mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
143         invert_m4_m4(rv3d->persinv, rv3d->persmat);
144         invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
145
146         /* calculate GLSL view dependent values */
147
148         /* store window coordinates scaling/offset */
149         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
150                 rctf cameraborder;
151                 ED_view3d_calc_camera_border(scene, eval_ctx->depsgraph, ar, v3d, rv3d, &cameraborder, false);
152                 rv3d->viewcamtexcofac[0] = (float)ar->winx / BLI_rctf_size_x(&cameraborder);
153                 rv3d->viewcamtexcofac[1] = (float)ar->winy / BLI_rctf_size_y(&cameraborder);
154
155                 rv3d->viewcamtexcofac[2] = -rv3d->viewcamtexcofac[0] * cameraborder.xmin / (float)ar->winx;
156                 rv3d->viewcamtexcofac[3] = -rv3d->viewcamtexcofac[1] * cameraborder.ymin / (float)ar->winy;
157         }
158         else {
159                 rv3d->viewcamtexcofac[0] = rv3d->viewcamtexcofac[1] = 1.0f;
160                 rv3d->viewcamtexcofac[2] = rv3d->viewcamtexcofac[3] = 0.0f;
161         }
162
163         /* calculate pixelsize factor once, is used for lamps and obcenters */
164         {
165                 /* note:  '1.0f / len_v3(v1)'  replaced  'len_v3(rv3d->viewmat[0])'
166                  * because of float point precision problems at large values [#23908] */
167                 float v1[3], v2[3];
168                 float len_px, len_sc;
169
170                 v1[0] = rv3d->persmat[0][0];
171                 v1[1] = rv3d->persmat[1][0];
172                 v1[2] = rv3d->persmat[2][0];
173
174                 v2[0] = rv3d->persmat[0][1];
175                 v2[1] = rv3d->persmat[1][1];
176                 v2[2] = rv3d->persmat[2][1];
177
178                 len_px = 2.0f / sqrtf(min_ff(len_squared_v3(v1), len_squared_v3(v2)));
179                 len_sc = (float)MAX2(ar->winx, ar->winy);
180
181                 rv3d->pixsize = len_px / len_sc;
182         }
183 }
184
185 static void view3d_main_region_setup_view(
186         const EvaluationContext *eval_ctx, Scene *scene,
187         View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
188 {
189         RegionView3D *rv3d = ar->regiondata;
190
191         ED_view3d_update_viewmat(eval_ctx, scene, v3d, ar, viewmat, winmat, rect);
192
193         /* set for opengl */
194         gpuLoadProjectionMatrix(rv3d->winmat);
195         gpuLoadMatrix(rv3d->viewmat);
196 }
197
198 static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
199 {
200         if ((scene->r.scemode & R_MULTIVIEW) == 0) {
201                 return false;
202         }
203
204         if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
205                 return false;
206         }
207
208         switch (v3d->stereo3d_camera) {
209                 case STEREO_MONO_ID:
210                         return false;
211                         break;
212                 case STEREO_3D_ID:
213                         /* win will be NULL when calling this from the selection or draw loop. */
214                         if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
215                                 return false;
216                         }
217                         if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
218                             !BKE_scene_multiview_is_stereo3d(&scene->r))
219                         {
220                                 return false;
221                         }
222                         break;
223                 /* We always need the stereo calculation for left and right cameras. */
224                 case STEREO_LEFT_ID:
225                 case STEREO_RIGHT_ID:
226                 default:
227                         break;
228         }
229         return true;
230 }
231
232
233 /* setup the view and win matrices for the multiview cameras
234  *
235  * unlike view3d_stereo3d_setup_offscreen, when view3d_stereo3d_setup is called
236  * we have no winmatrix (i.e., projection matrix) defined at that time.
237  * Since the camera and the camera shift are needed for the winmat calculation
238  * we do a small hack to replace it temporarily so we don't need to change the
239  * view3d)main_region_setup_view() code to account for that.
240  */
241 static void view3d_stereo3d_setup(
242         const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect)
243 {
244         bool is_left;
245         const char *names[2] = { STEREO_LEFT_NAME, STEREO_RIGHT_NAME };
246         const char *viewname;
247
248         /* show only left or right camera */
249         if (v3d->stereo3d_camera != STEREO_3D_ID)
250                 v3d->multiview_eye = v3d->stereo3d_camera;
251
252         is_left = v3d->multiview_eye == STEREO_LEFT_ID;
253         viewname = names[is_left ? STEREO_LEFT_ID : STEREO_RIGHT_ID];
254
255         /* update the viewport matrices with the new camera */
256         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
257                 Camera *data;
258                 float viewmat[4][4];
259                 float shiftx;
260
261                 data = (Camera *)v3d->camera->data;
262                 shiftx = data->shiftx;
263
264                 BLI_lock_thread(LOCK_VIEW3D);
265                 data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
266
267                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
268                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, NULL, rect);
269
270                 data->shiftx = shiftx;
271                 BLI_unlock_thread(LOCK_VIEW3D);
272         }
273         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
274                 float viewmat[4][4];
275                 Object *view_ob = v3d->camera;
276                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
277
278                 BLI_lock_thread(LOCK_VIEW3D);
279                 v3d->camera = camera;
280
281                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
282                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, NULL, rect);
283
284                 v3d->camera = view_ob;
285                 BLI_unlock_thread(LOCK_VIEW3D);
286         }
287 }
288
289 /**
290  * Set the correct matrices
291  */
292 void ED_view3d_draw_setup_view(
293         wmWindow *win, const EvaluationContext *eval_ctx, Scene *scene, ARegion *ar, View3D *v3d,
294         float viewmat[4][4], float winmat[4][4], const rcti *rect)
295 {
296         RegionView3D *rv3d = ar->regiondata;
297
298         /* Setup the view matrix. */
299         if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
300                 view3d_stereo3d_setup(eval_ctx, scene, v3d, ar, rect);
301         }
302         else {
303                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, rect);
304         }
305 }
306
307 /* ******************** view border ***************** */
308
309 static void view3d_camera_border(
310         const Scene *scene, const struct Depsgraph *depsgraph,
311         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
312         rctf *r_viewborder, const bool no_shift, const bool no_zoom)
313 {
314         CameraParams params;
315         rctf rect_view, rect_camera;
316
317         /* get viewport viewplane */
318         BKE_camera_params_init(&params);
319         BKE_camera_params_from_view3d(&params, depsgraph, v3d, rv3d);
320         if (no_zoom)
321                 params.zoom = 1.0f;
322         BKE_camera_params_compute_viewplane(&params, ar->winx, ar->winy, 1.0f, 1.0f);
323         rect_view = params.viewplane;
324
325         /* get camera viewplane */
326         BKE_camera_params_init(&params);
327         /* fallback for non camera objects */
328         params.clipsta = v3d->near;
329         params.clipend = v3d->far;
330         BKE_camera_params_from_object(&params, v3d->camera);
331         if (no_shift) {
332                 params.shiftx = 0.0f;
333                 params.shifty = 0.0f;
334         }
335         BKE_camera_params_compute_viewplane(&params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
336         rect_camera = params.viewplane;
337
338         /* get camera border within viewport */
339         r_viewborder->xmin = ((rect_camera.xmin - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
340         r_viewborder->xmax = ((rect_camera.xmax - rect_view.xmin) / BLI_rctf_size_x(&rect_view)) * ar->winx;
341         r_viewborder->ymin = ((rect_camera.ymin - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
342         r_viewborder->ymax = ((rect_camera.ymax - rect_view.ymin) / BLI_rctf_size_y(&rect_view)) * ar->winy;
343 }
344
345 void ED_view3d_calc_camera_border_size(
346         const Scene *scene, const Depsgraph *depsgraph,
347         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
348         float r_size[2])
349 {
350         rctf viewborder;
351
352         view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, true, true);
353         r_size[0] = BLI_rctf_size_x(&viewborder);
354         r_size[1] = BLI_rctf_size_y(&viewborder);
355 }
356
357 void ED_view3d_calc_camera_border(
358         const Scene *scene, const Depsgraph *depsgraph,
359         const ARegion *ar, const View3D *v3d, const RegionView3D *rv3d,
360         rctf *r_viewborder, const bool no_shift)
361 {
362         view3d_camera_border(scene, depsgraph, ar, v3d, rv3d, r_viewborder, no_shift, false);
363 }
364
365 static void drawviewborder_grid3(uint shdr_pos, float x1, float x2, float y1, float y2, float fac)
366 {
367         float x3, y3, x4, y4;
368
369         x3 = x1 + fac * (x2 - x1);
370         y3 = y1 + fac * (y2 - y1);
371         x4 = x1 + (1.0f - fac) * (x2 - x1);
372         y4 = y1 + (1.0f - fac) * (y2 - y1);
373
374         immBegin(GWN_PRIM_LINES, 8);
375
376         immVertex2f(shdr_pos, x1, y3);
377         immVertex2f(shdr_pos, x2, y3);
378
379         immVertex2f(shdr_pos, x1, y4);
380         immVertex2f(shdr_pos, x2, y4);
381
382         immVertex2f(shdr_pos, x3, y1);
383         immVertex2f(shdr_pos, x3, y2);
384
385         immVertex2f(shdr_pos, x4, y1);
386         immVertex2f(shdr_pos, x4, y2);
387
388         immEnd();
389 }
390
391 /* harmonious triangle */
392 static void drawviewborder_triangle(
393         uint shdr_pos, float x1, float x2, float y1, float y2, const char golden, const char dir)
394 {
395         float ofs;
396         float w = x2 - x1;
397         float h = y2 - y1;
398
399         immBegin(GWN_PRIM_LINES, 6);
400
401         if (w > h) {
402                 if (golden) {
403                         ofs = w * (1.0f - (1.0f / 1.61803399f));
404                 }
405                 else {
406                         ofs = h * (h / w);
407                 }
408                 if (dir == 'B') SWAP(float, y1, y2);
409
410                 immVertex2f(shdr_pos, x1, y1);
411                 immVertex2f(shdr_pos, x2, y2);
412
413                 immVertex2f(shdr_pos, x2, y1);
414                 immVertex2f(shdr_pos, x1 + (w - ofs), y2);
415
416                 immVertex2f(shdr_pos, x1, y2);
417                 immVertex2f(shdr_pos, x1 + ofs, y1);
418         }
419         else {
420                 if (golden) {
421                         ofs = h * (1.0f - (1.0f / 1.61803399f));
422                 }
423                 else {
424                         ofs = w * (w / h);
425                 }
426                 if (dir == 'B') SWAP(float, x1, x2);
427
428                 immVertex2f(shdr_pos, x1, y1);
429                 immVertex2f(shdr_pos, x2, y2);
430
431                 immVertex2f(shdr_pos, x2, y1);
432                 immVertex2f(shdr_pos, x1, y1 + ofs);
433
434                 immVertex2f(shdr_pos, x1, y2);
435                 immVertex2f(shdr_pos, x2, y1 + (h - ofs));
436         }
437
438         immEnd();
439 }
440
441 static void drawviewborder(Scene *scene, const Depsgraph *depsgraph, ARegion *ar, View3D *v3d)
442 {
443         float x1, x2, y1, y2;
444         float x1i, x2i, y1i, y2i;
445
446         rctf viewborder;
447         Camera *ca = NULL;
448         RegionView3D *rv3d = ar->regiondata;
449
450         if (v3d->camera == NULL)
451                 return;
452         if (v3d->camera->type == OB_CAMERA)
453                 ca = v3d->camera->data;
454         
455         ED_view3d_calc_camera_border(scene, depsgraph, ar, v3d, rv3d, &viewborder, false);
456         /* the offsets */
457         x1 = viewborder.xmin;
458         y1 = viewborder.ymin;
459         x2 = viewborder.xmax;
460         y2 = viewborder.ymax;
461         
462         glLineWidth(1.0f);
463
464         /* apply offsets so the real 3D camera shows through */
465
466         /* note: quite un-scientific but without this bit extra
467          * 0.0001 on the lower left the 2D border sometimes
468          * obscures the 3D camera border */
469         /* note: with VIEW3D_CAMERA_BORDER_HACK defined this error isn't noticeable
470          * but keep it here in case we need to remove the workaround */
471         x1i = (int)(x1 - 1.0001f);
472         y1i = (int)(y1 - 1.0001f);
473         x2i = (int)(x2 + (1.0f - 0.0001f));
474         y2i = (int)(y2 + (1.0f - 0.0001f));
475
476         uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
477
478         /* First, solid lines. */
479         {
480                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
481
482                 /* passepartout, specified in camera edit buttons */
483                 if (ca && (ca->flag & CAM_SHOWPASSEPARTOUT) && ca->passepartalpha > 0.000001f) {
484                         const float winx = (ar->winx + 1);
485                         const float winy = (ar->winy + 1);
486
487                         float alpha = 1.0f;
488
489                         if (ca->passepartalpha != 1.0f) {
490                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
491                                 glEnable(GL_BLEND);
492                                 alpha = ca->passepartalpha;
493                         }
494
495                         immUniformColor4f(0.0f, 0.0f, 0.0f, alpha);
496
497                         if (x1i > 0.0f)
498                                 immRectf(shdr_pos, 0.0f, winy, x1i, 0.0f);
499                         if (x2i < winx)
500                                 immRectf(shdr_pos, x2i, winy, winx, 0.0f);
501                         if (y2i < winy)
502                                 immRectf(shdr_pos, x1i, winy, x2i, y2i);
503                         if (y2i > 0.0f)
504                                 immRectf(shdr_pos, x1i, y1i, x2i, 0.0f);
505
506                         glDisable(GL_BLEND);
507                 }
508
509                 immUniformThemeColor(TH_BACK);
510                 imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
511
512 #ifdef VIEW3D_CAMERA_BORDER_HACK
513                 if (view3d_camera_border_hack_test == true) {
514                         immUniformColor3ubv(view3d_camera_border_hack_col);
515                         imm_draw_box_wire_2d(shdr_pos, x1i + 1, y1i + 1, x2i - 1, y2i - 1);
516                         view3d_camera_border_hack_test = false;
517                 }
518 #endif
519
520                 immUnbindProgram();
521         }
522
523         /* And now, the dashed lines! */
524         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
525
526         {
527                 float viewport_size[4];
528                 glGetFloatv(GL_VIEWPORT, viewport_size);
529                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
530
531                 immUniform1i("num_colors", 0);  /* "simple" mode */
532                 immUniform1f("dash_width", 6.0f);
533                 immUniform1f("dash_factor", 0.5f);
534
535                 /* outer line not to confuse with object selection */
536                 if (v3d->flag2 & V3D_LOCK_CAMERA) {
537                         immUniformThemeColor(TH_REDALERT);
538                         imm_draw_box_wire_2d(shdr_pos, x1i - 1, y1i - 1, x2i + 1, y2i + 1);
539                 }
540
541                 immUniformThemeColor(TH_VIEW_OVERLAY);
542                 imm_draw_box_wire_2d(shdr_pos, x1i, y1i, x2i, y2i);
543         }
544
545         /* border */
546         if (scene->r.mode & R_BORDER) {
547                 float x3, y3, x4, y4;
548
549                 x3 = floorf(x1 + (scene->r.border.xmin * (x2 - x1))) - 1;
550                 y3 = floorf(y1 + (scene->r.border.ymin * (y2 - y1))) - 1;
551                 x4 = floorf(x1 + (scene->r.border.xmax * (x2 - x1))) + (U.pixelsize - 1);
552                 y4 = floorf(y1 + (scene->r.border.ymax * (y2 - y1))) + (U.pixelsize - 1);
553
554                 immUniformColor3f(1.0f, 0.25f, 0.25f);
555                 imm_draw_box_wire_2d(shdr_pos, x3, y3, x4, y4);
556         }
557
558         /* safety border */
559         if (ca) {
560                 immUniformThemeColorBlend(TH_VIEW_OVERLAY, TH_BACK, 0.25f);
561
562                 if (ca->dtx & CAM_DTX_CENTER) {
563                         float x3, y3;
564
565                         x3 = x1 + 0.5f * (x2 - x1);
566                         y3 = y1 + 0.5f * (y2 - y1);
567
568                         immBegin(GWN_PRIM_LINES, 4);
569
570                         immVertex2f(shdr_pos, x1, y3);
571                         immVertex2f(shdr_pos, x2, y3);
572
573                         immVertex2f(shdr_pos, x3, y1);
574                         immVertex2f(shdr_pos, x3, y2);
575
576                         immEnd();
577                 }
578
579                 if (ca->dtx & CAM_DTX_CENTER_DIAG) {
580                         immBegin(GWN_PRIM_LINES, 4);
581
582                         immVertex2f(shdr_pos, x1, y1);
583                         immVertex2f(shdr_pos, x2, y2);
584
585                         immVertex2f(shdr_pos, x1, y2);
586                         immVertex2f(shdr_pos, x2, y1);
587
588                         immEnd();
589                 }
590
591                 if (ca->dtx & CAM_DTX_THIRDS) {
592                         drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f / 3.0f);
593                 }
594
595                 if (ca->dtx & CAM_DTX_GOLDEN) {
596                         drawviewborder_grid3(shdr_pos, x1, x2, y1, y2, 1.0f - (1.0f / 1.61803399f));
597                 }
598
599                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_A) {
600                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'A');
601                 }
602
603                 if (ca->dtx & CAM_DTX_GOLDEN_TRI_B) {
604                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 0, 'B');
605                 }
606
607                 if (ca->dtx & CAM_DTX_HARMONY_TRI_A) {
608                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'A');
609                 }
610
611                 if (ca->dtx & CAM_DTX_HARMONY_TRI_B) {
612                         drawviewborder_triangle(shdr_pos, x1, x2, y1, y2, 1, 'B');
613                 }
614
615                 if (ca->flag & CAM_SHOW_SAFE_MARGINS) {
616                         UI_draw_safe_areas(
617                                 shdr_pos, x1, x2, y1, y2,
618                                 scene->safe_areas.title, scene->safe_areas.action);
619
620                         if (ca->flag & CAM_SHOW_SAFE_CENTER) {
621                                 UI_draw_safe_areas(
622                                         shdr_pos, x1, x2, y1, y2,
623                                         scene->safe_areas.title_center, scene->safe_areas.action_center);
624                         }
625                 }
626
627                 if (ca->flag & CAM_SHOWSENSOR) {
628                         /* determine sensor fit, and get sensor x/y, for auto fit we
629                          * assume and square sensor and only use sensor_x */
630                         float sizex = scene->r.xsch * scene->r.xasp;
631                         float sizey = scene->r.ysch * scene->r.yasp;
632                         int sensor_fit = BKE_camera_sensor_fit(ca->sensor_fit, sizex, sizey);
633                         float sensor_x = ca->sensor_x;
634                         float sensor_y = (ca->sensor_fit == CAMERA_SENSOR_FIT_AUTO) ? ca->sensor_x : ca->sensor_y;
635
636                         /* determine sensor plane */
637                         rctf rect;
638
639                         if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
640                                 float sensor_scale = (x2i - x1i) / sensor_x;
641                                 float sensor_height = sensor_scale * sensor_y;
642
643                                 rect.xmin = x1i;
644                                 rect.xmax = x2i;
645                                 rect.ymin = (y1i + y2i) * 0.5f - sensor_height * 0.5f;
646                                 rect.ymax = rect.ymin + sensor_height;
647                         }
648                         else {
649                                 float sensor_scale = (y2i - y1i) / sensor_y;
650                                 float sensor_width = sensor_scale * sensor_x;
651
652                                 rect.xmin = (x1i + x2i) * 0.5f - sensor_width * 0.5f;
653                                 rect.xmax = rect.xmin + sensor_width;
654                                 rect.ymin = y1i;
655                                 rect.ymax = y2i;
656                         }
657
658                         /* draw */
659                         immUniformThemeColorShade(TH_VIEW_OVERLAY, 100);
660                         
661                         /* TODO Was using UI_draw_roundbox_4fv(false, rect.xmin, rect.ymin, rect.xmax, rect.ymax, 2.0f, color).
662                          * We'll probably need a new imm_draw_line_roundbox_dashed dor that - though in practice the
663                          * 2.0f round corner effect was nearly not visible anyway... */
664                         imm_draw_box_wire_2d(shdr_pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
665                 }
666         }
667
668         immUnbindProgram();
669         /* end dashed lines */
670
671         /* camera name - draw in highlighted text color */
672         if (ca && (ca->flag & CAM_SHOWNAME)) {
673                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
674                 BLF_draw_default(
675                         x1i, y1i - (0.7f * U.widget_unit), 0.0f,
676                         v3d->camera->id.name + 2, sizeof(v3d->camera->id.name) - 2);
677         }
678 }
679
680 static void drawrenderborder(ARegion *ar, View3D *v3d)
681 {
682         /* use the same program for everything */
683         uint shdr_pos = GWN_vertformat_attr_add(immVertexFormat(), "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
684
685         glLineWidth(1.0f);
686
687         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
688
689         float viewport_size[4];
690         glGetFloatv(GL_VIEWPORT, viewport_size);
691         immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
692
693         immUniform1i("num_colors", 0);  /* "simple" mode */
694         immUniform4f("color", 1.0f, 0.25f, 0.25f, 1.0f);
695         immUniform1f("dash_width", 6.0f);
696         immUniform1f("dash_factor", 0.5f);
697
698         imm_draw_box_wire_2d(shdr_pos,
699                           v3d->render_border.xmin * ar->winx, v3d->render_border.ymin * ar->winy,
700                           v3d->render_border.xmax * ar->winx, v3d->render_border.ymax * ar->winy);
701
702         immUnbindProgram();
703 }
704
705 void ED_view3d_draw_depth(
706         const EvaluationContext *eval_ctx, struct Depsgraph *graph,
707         ARegion *ar, View3D *v3d, bool alphaoverride)
708 {
709         struct bThemeState theme_state;
710         Scene *scene = DEG_get_evaluated_scene(graph);
711         RegionView3D *rv3d = ar->regiondata;
712
713         short zbuf = v3d->zbuf;
714         short flag = v3d->flag;
715         float glalphaclip = U.glalphaclip;
716         int obcenter_dia = U.obcenter_dia;
717         /* temp set drawtype to solid */
718         /* Setting these temporarily is not nice */
719         v3d->flag &= ~V3D_SELECT_OUTLINE;
720         U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
721         U.obcenter_dia = 0;
722
723         /* Tools may request depth outside of regular drawing code. */
724         UI_Theme_Store(&theme_state);
725         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
726
727         ED_view3d_draw_setup_view(NULL, eval_ctx, scene, ar, v3d, NULL, NULL, NULL);
728
729         glClear(GL_DEPTH_BUFFER_BIT);
730
731         if (rv3d->rflag & RV3D_CLIPPING) {
732                 ED_view3d_clipping_set(rv3d);
733         }
734         /* get surface depth without bias */
735         rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
736
737         v3d->zbuf = true;
738         glEnable(GL_DEPTH_TEST);
739
740 #ifdef WITH_OPENGL_LEGACY
741         if (IS_VIEWPORT_LEGACY(vc->v3d)) {
742                 /* temp, calls into view3d_draw_legacy.c */
743                 ED_view3d_draw_depth_loop(scene, ar, v3d);
744         }
745         else
746 #endif /* WITH_OPENGL_LEGACY */
747         {
748                 DRW_draw_depth_loop(graph, ar, v3d);
749         }
750
751         if (rv3d->rflag & RV3D_CLIPPING) {
752                 ED_view3d_clipping_disable();
753         }
754         rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
755
756         v3d->zbuf = zbuf;
757         if (!v3d->zbuf) glDisable(GL_DEPTH_TEST);
758
759         U.glalphaclip = glalphaclip;
760         v3d->flag = flag;
761         U.obcenter_dia = obcenter_dia;
762
763         UI_Theme_Restore(&theme_state);
764 }
765
766 /* ******************** background plates ***************** */
767
768 static void view3d_draw_background_gradient(void)
769 {
770         /* TODO: finish 2D API & draw background with that */
771
772         Gwn_VertFormat *format = immVertexFormat();
773         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
774         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
775         unsigned char col_hi[3], col_lo[3];
776
777         immBindBuiltinProgram(GPU_SHADER_2D_SMOOTH_COLOR);
778
779         UI_GetThemeColor3ubv(TH_LOW_GRAD, col_lo);
780         UI_GetThemeColor3ubv(TH_HIGH_GRAD, col_hi);
781
782         immBegin(GWN_PRIM_TRI_FAN, 4);
783         immAttrib3ubv(color, col_lo);
784         immVertex2f(pos, -1.0f, -1.0f);
785         immVertex2f(pos, 1.0f, -1.0f);
786
787         immAttrib3ubv(color, col_hi);
788         immVertex2f(pos, 1.0f, 1.0f);
789         immVertex2f(pos, -1.0f, 1.0f);
790         immEnd();
791
792         immUnbindProgram();
793 }
794
795 static void view3d_draw_background_none(void)
796 {
797         UI_ThemeClearColorAlpha(TH_HIGH_GRAD, 1.0f);
798         glClear(GL_COLOR_BUFFER_BIT);
799 }
800
801 static void view3d_draw_background_world(Scene *scene, RegionView3D *rv3d)
802 {
803         if (scene->world) {
804                 GPUMaterial *gpumat = GPU_material_world(scene, scene->world);
805
806                 /* calculate full shader for background */
807                 GPU_material_bind(gpumat, 1, 1, 1.0f, false, rv3d->viewmat, rv3d->viewinv, rv3d->viewcamtexcofac);
808
809                 if (GPU_material_bound(gpumat)) {
810                         /* TODO viewport (dfelinto): GPU_material_bind relies on immediate mode,
811                          * we can't get rid of the following code without a bigger refactor
812                          * or we dropping this functionality. */
813
814                         glBegin(GL_TRIANGLE_STRIP);
815                         glVertex2f(-1.0f, -1.0f);
816                         glVertex2f(1.0f, -1.0f);
817                         glVertex2f(-1.0f, 1.0f);
818                         glVertex2f(1.0f, 1.0f);
819                         glEnd();
820
821                         GPU_material_unbind(gpumat);
822                         return;
823                 }
824         }
825
826         /* if any of the above fails */
827         view3d_draw_background_none();
828 }
829
830 /* ******************** other elements ***************** */
831
832
833 #define DEBUG_GRID 0
834
835 static void gridline_range(double x0, double dx, double max, int *r_first, int *r_count)
836 {
837         /* determine range of gridlines that appear in this Area -- similar calc but separate ranges for x & y
838          * x0 is gridline 0, the axis in screen space
839          * Area covers [0 .. max) pixels */
840
841         int first = (int)ceil(-x0 / dx);
842         int last = (int)floor((max - x0) / dx);
843
844         if (first <= last) {
845                 *r_first = first;
846                 *r_count = last - first + 1;
847         }
848         else {
849                 *r_first = 0;
850                 *r_count = 0;
851         }
852
853 #if DEBUG_GRID
854         printf("   first %d * dx = %f\n", first, x0 + first * dx);
855         printf("   last %d * dx = %f\n", last, x0 + last * dx);
856         printf("   count = %d\n", *count_out);
857 #endif
858 }
859
860 static int gridline_count(ARegion *ar, double x0, double y0, double dx)
861 {
862         /* x0 & y0 establish the "phase" of the grid within this 2D region
863          * dx is the frequency, shared by x & y directions
864          * pass in dx of smallest (highest precision) grid we want to draw */
865
866 #if DEBUG_GRID
867         printf("  %s(%f, %f, dx:%f)\n", __FUNCTION__, x0, y0, dx);
868 #endif
869
870         int first, x_ct, y_ct;
871
872         gridline_range(x0, dx, ar->winx, &first, &x_ct);
873         gridline_range(y0, dx, ar->winy, &first, &y_ct);
874
875         int total_ct = x_ct + y_ct;
876
877 #if DEBUG_GRID
878         printf("   %d + %d = %d gridlines\n", x_ct, y_ct, total_ct);
879 #endif
880
881         return total_ct;
882 }
883
884 static bool drawgrid_draw(ARegion *ar, double x0, double y0, double dx, int skip_mod, unsigned pos, unsigned col, GLubyte col_value[3])
885 {
886         /* skip every skip_mod lines relative to each axis; they will be overlaid by another drawgrid_draw
887          * always skip exact x0 & y0 axes; they will be drawn later in color
888          *
889          * set grid color once, just before the first line is drawn
890          * it's harmless to set same color for every line, or every vertex
891          * but if no lines are drawn, color must not be set! */
892
893 #if DEBUG_GRID
894         printf("  %s(%f, %f, dx:%f, skip_mod:%d)\n", __FUNCTION__, x0, y0, dx, skip_mod);
895 #endif
896
897         const float x_max = (float)ar->winx;
898         const float y_max = (float)ar->winy;
899
900         int first, ct;
901         int x_ct = 0, y_ct = 0; /* count of lines actually drawn */
902         int lines_skipped_for_next_unit = 0;
903
904         /* draw vertical lines */
905         gridline_range(x0, dx, x_max, &first, &ct);
906
907         for (int i = first; i < first + ct; ++i) {
908                 if (i == 0)
909                         continue;
910                 else if (skip_mod && (i % skip_mod) == 0) {
911                         ++lines_skipped_for_next_unit;
912                         continue;
913                 }
914
915                 if (x_ct == 0)
916                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
917
918                 float x = (float)(x0 + i * dx);
919                 immVertex2f(pos, x, 0.0f);
920                 immVertex2f(pos, x, y_max);
921                 ++x_ct;
922         }
923
924         /* draw horizontal lines */
925         gridline_range(y0, dx, y_max, &first, &ct);
926
927         for (int i = first; i < first + ct; ++i) {
928                 if (i == 0)
929                         continue;
930                 else if (skip_mod && (i % skip_mod) == 0) {
931                         ++lines_skipped_for_next_unit;
932                         continue;
933                 }
934
935                 if (x_ct + y_ct == 0)
936                         immAttrib3ub(col, col_value[0], col_value[1], col_value[2]);
937
938                 float y = (float)(y0 + i * dx);
939                 immVertex2f(pos, 0.0f, y);
940                 immVertex2f(pos, x_max, y);
941                 ++y_ct;
942         }
943
944 #if DEBUG_GRID
945         int total_ct = x_ct + y_ct;
946         printf("    %d + %d = %d gridlines drawn, %d skipped for next unit\n", x_ct, y_ct, total_ct, lines_skipped_for_next_unit);
947 #endif
948
949         return lines_skipped_for_next_unit > 0;
950 }
951
952 #define GRID_MIN_PX_D 6.0
953 #define GRID_MIN_PX_F 6.0f
954
955 static void drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
956 {
957         RegionView3D *rv3d = ar->regiondata;
958
959 #if DEBUG_GRID
960         printf("%s width %d, height %d\n", __FUNCTION__, ar->winx, ar->winy);
961 #endif
962
963         double fx = rv3d->persmat[3][0];
964         double fy = rv3d->persmat[3][1];
965         double fw = rv3d->persmat[3][3];
966
967         const double wx = 0.5 * ar->winx;  /* use double precision to avoid rounding errors */
968         const double wy = 0.5 * ar->winy;
969
970         double x = wx * fx / fw;
971         double y = wy * fy / fw;
972
973         double vec4[4] = { v3d->grid, v3d->grid, 0.0, 1.0 };
974         mul_m4_v4d(rv3d->persmat, vec4);
975         fx = vec4[0];
976         fy = vec4[1];
977         fw = vec4[3];
978
979         double dx = fabs(x - wx * fx / fw);
980         if (dx == 0) dx = fabs(y - wy * fy / fw);
981
982         x += wx;
983         y += wy;
984
985         /* now x, y, and dx have their final values
986          * (x,y) is the world origin (0,0,0) mapped to Area-relative screen space
987          * dx is the distance in pixels between grid lines -- same for horiz or vert grid lines */
988
989         glLineWidth(1.0f);
990
991 #if 0 /* TODO: write to UI/widget depth buffer, not scene depth */
992         glDepthMask(GL_FALSE);  /* disable write in zbuffer */
993 #endif
994
995         Gwn_VertFormat *format = immVertexFormat();
996         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
997         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
998
999         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1000
1001         unsigned char col[3], col2[3];
1002         UI_GetThemeColor3ubv(TH_GRID, col);
1003
1004         if (unit->system) {
1005                 const void *usys;
1006                 int len;
1007
1008                 bUnit_GetSystem(unit->system, B_UNIT_LENGTH, &usys, &len);
1009
1010                 bool first = true;
1011
1012                 if (usys) {
1013                         int i = len;
1014                         while (i--) {
1015                                 double scalar = bUnit_GetScaler(usys, i);
1016
1017                                 double dx_scalar = dx * scalar / (double)unit->scale_length;
1018                                 if (dx_scalar < (GRID_MIN_PX_D * 2.0)) {
1019                                         /* very very small grid items are less useful when dealing with units */
1020                                         continue;
1021                                 }
1022
1023                                 if (first) {
1024                                         first = false;
1025
1026                                         /* Store the smallest drawn grid size units name so users know how big each grid cell is */
1027                                         *grid_unit = bUnit_GetNameDisplay(usys, i);
1028                                         rv3d->gridview = (float)((scalar * (double)v3d->grid) / (double)unit->scale_length);
1029
1030                                         int gridline_ct = gridline_count(ar, x, y, dx_scalar);
1031                                         if (gridline_ct == 0)
1032                                                 goto drawgrid_cleanup; /* nothing to draw */
1033
1034                                         immBegin(GWN_PRIM_LINES, gridline_ct * 2);
1035                                 }
1036
1037                                 float blend_fac = 1.0f - ((GRID_MIN_PX_F * 2.0f) / (float)dx_scalar);
1038                                 /* tweak to have the fade a bit nicer */
1039                                 blend_fac = (blend_fac * blend_fac) * 2.0f;
1040                                 CLAMP(blend_fac, 0.3f, 1.0f);
1041
1042                                 UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, blend_fac, col2);
1043
1044                                 const int skip_mod = (i == 0) ? 0 : (int)round(bUnit_GetScaler(usys, i - 1) / scalar);
1045 #if DEBUG_GRID
1046                                 printf("%s %f, ", bUnit_GetNameDisplay(usys, i), scalar);
1047                                 if (i > 0)
1048                                         printf("next unit is %d times larger\n", skip_mod);
1049                                 else
1050                                         printf("largest unit\n");
1051 #endif
1052                                 if (!drawgrid_draw(ar, x, y, dx_scalar, skip_mod, pos, color, col2))
1053                                         break;
1054                         }
1055                 }
1056         }
1057         else {
1058                 const double sublines = v3d->gridsubdiv;
1059                 const float  sublines_fl = v3d->gridsubdiv;
1060
1061                 int grids_to_draw = 2; /* first the faint fine grid, then the bold coarse grid */
1062
1063                 if (dx < GRID_MIN_PX_D) {
1064                         rv3d->gridview *= sublines_fl;
1065                         dx *= sublines;
1066                         if (dx < GRID_MIN_PX_D) {
1067                                 rv3d->gridview *= sublines_fl;
1068                                 dx *= sublines;
1069                                 if (dx < GRID_MIN_PX_D) {
1070                                         rv3d->gridview *= sublines_fl;
1071                                         dx *= sublines;
1072                                         grids_to_draw = (dx < GRID_MIN_PX_D) ? 0 : 1;
1073                                 }
1074                         }
1075                 }
1076                 else {
1077                         if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1078                                 rv3d->gridview /= sublines_fl;
1079                                 dx /= sublines;
1080                                 if (dx > (GRID_MIN_PX_D * 10.0)) {  /* start blending in */
1081                                         rv3d->gridview /= sublines_fl;
1082                                         dx /= sublines;
1083                                         if (dx > (GRID_MIN_PX_D * 10.0)) {
1084                                                 grids_to_draw = 1;
1085                                         }
1086                                 }
1087                         }
1088                 }
1089
1090                 int gridline_ct = gridline_count(ar, x, y, dx);
1091                 if (gridline_ct == 0)
1092                         goto drawgrid_cleanup; /* nothing to draw */
1093
1094                 immBegin(GWN_PRIM_LINES, gridline_ct * 2);
1095
1096                 if (grids_to_draw == 2) {
1097                         UI_GetThemeColorBlend3ubv(TH_HIGH_GRAD, TH_GRID, dx / (GRID_MIN_PX_D * 6.0), col2);
1098                         if (drawgrid_draw(ar, x, y, dx, v3d->gridsubdiv, pos, color, col2))
1099                                 drawgrid_draw(ar, x, y, dx * sublines, 0, pos, color, col);
1100                 }
1101                 else if (grids_to_draw == 1) {
1102                         drawgrid_draw(ar, x, y, dx, 0, pos, color, col);
1103                 }
1104         }
1105
1106         /* draw visible axes */
1107         /* horizontal line */
1108         if (0 <= y && y < ar->winy) {
1109                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_RIGHT, RV3D_VIEW_LEFT) ? 'Y' : 'X');
1110                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1111                 immVertex2f(pos, 0.0f, y);
1112                 immVertex2f(pos, (float)ar->winx, y);
1113         }
1114
1115         /* vertical line */
1116         if (0 <= x && x < ar->winx) {
1117                 UI_make_axis_color(col, col2, ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM) ? 'Y' : 'Z');
1118                 immAttrib3ub(color, col2[0], col2[1], col2[2]);
1119                 immVertex2f(pos, x, 0.0f);
1120                 immVertex2f(pos, x, (float)ar->winy);
1121         }
1122
1123         immEnd();
1124
1125 drawgrid_cleanup:
1126         immUnbindProgram();
1127
1128 #if 0 /* depth write is left enabled above */
1129         glDepthMask(GL_TRUE);  /* enable write in zbuffer */
1130 #endif
1131 }
1132
1133 #undef DEBUG_GRID
1134 #undef GRID_MIN_PX_D
1135 #undef GRID_MIN_PX_F
1136
1137 static void drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
1138 {
1139         /* draw only if there is something to draw */
1140         if (v3d->gridflag & (V3D_SHOW_FLOOR | V3D_SHOW_X | V3D_SHOW_Y | V3D_SHOW_Z)) {
1141                 /* draw how many lines?
1142                  * trunc(v3d->gridlines / 2) * 4
1143                  * + 2 for xy axes (possibly with special colors)
1144                  * + 1 for z axis (the only line not in xy plane)
1145                  * even v3d->gridlines are honored, odd rounded down */
1146                 const int gridlines = v3d->gridlines / 2;
1147                 const float grid_scale = ED_view3d_grid_scale(scene, v3d, grid_unit);
1148                 const float grid = gridlines * grid_scale;
1149
1150                 const bool show_floor = (v3d->gridflag & V3D_SHOW_FLOOR) && gridlines >= 1;
1151
1152                 bool show_axis_x = v3d->gridflag & V3D_SHOW_X;
1153                 bool show_axis_y = v3d->gridflag & V3D_SHOW_Y;
1154                 bool show_axis_z = v3d->gridflag & V3D_SHOW_Z;
1155
1156                 unsigned char col_grid[3], col_axis[3];
1157
1158                 glLineWidth(1.0f);
1159
1160                 UI_GetThemeColor3ubv(TH_GRID, col_grid);
1161
1162                 if (!write_depth)
1163                         glDepthMask(GL_FALSE);
1164
1165                 if (show_floor) {
1166                         const unsigned vertex_ct = 2 * (gridlines * 4 + 2);
1167                         const int sublines = v3d->gridsubdiv;
1168
1169                         unsigned char col_bg[3], col_grid_emphasise[3], col_grid_light[3];
1170
1171                         Gwn_VertFormat *format = immVertexFormat();
1172                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1173                         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1174
1175                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1176
1177                         immBegin(GWN_PRIM_LINES, vertex_ct);
1178
1179                         /* draw normal grid lines */
1180                         UI_GetColorPtrShade3ubv(col_grid, col_grid_light, 10);
1181
1182                         for (int a = 1; a <= gridlines; a++) {
1183                                 /* skip emphasised divider lines */
1184                                 if (a % sublines != 0) {
1185                                         const float line = a * grid_scale;
1186
1187                                         immAttrib3ubv(color, col_grid_light);
1188
1189                                         immVertex2f(pos, -grid, -line);
1190                                         immVertex2f(pos, +grid, -line);
1191                                         immVertex2f(pos, -grid, +line);
1192                                         immVertex2f(pos, +grid, +line);
1193
1194                                         immVertex2f(pos, -line, -grid);
1195                                         immVertex2f(pos, -line, +grid);
1196                                         immVertex2f(pos, +line, -grid);
1197                                         immVertex2f(pos, +line, +grid);
1198                                 }
1199                         }
1200
1201                         /* draw emphasised grid lines */
1202                         UI_GetThemeColor3ubv(TH_BACK, col_bg);
1203                         /* emphasise division lines lighter instead of darker, if background is darker than grid */
1204                         UI_GetColorPtrShade3ubv(col_grid, col_grid_emphasise,
1205                                 (col_grid[0] + col_grid[1] + col_grid[2] + 30 >
1206                                 col_bg[0] + col_bg[1] + col_bg[2]) ? 20 : -10);
1207
1208                         if (sublines <= gridlines) {
1209                                 immAttrib3ubv(color, col_grid_emphasise);
1210
1211                                 for (int a = sublines; a <= gridlines; a += sublines) {
1212                                         const float line = a * grid_scale;
1213
1214                                         immVertex2f(pos, -grid, -line);
1215                                         immVertex2f(pos, +grid, -line);
1216                                         immVertex2f(pos, -grid, +line);
1217                                         immVertex2f(pos, +grid, +line);
1218
1219                                         immVertex2f(pos, -line, -grid);
1220                                         immVertex2f(pos, -line, +grid);
1221                                         immVertex2f(pos, +line, -grid);
1222                                         immVertex2f(pos, +line, +grid);
1223                                 }
1224                         }
1225
1226                         /* draw X axis */
1227                         if (show_axis_x) {
1228                                 show_axis_x = false; /* drawing now, won't need to draw later */
1229                                 UI_make_axis_color(col_grid, col_axis, 'X');
1230                                 immAttrib3ubv(color, col_axis);
1231                         }
1232                         else
1233                                 immAttrib3ubv(color, col_grid_emphasise);
1234
1235                         immVertex2f(pos, -grid, 0.0f);
1236                         immVertex2f(pos, +grid, 0.0f);
1237
1238                         /* draw Y axis */
1239                         if (show_axis_y) {
1240                                 show_axis_y = false; /* drawing now, won't need to draw later */
1241                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1242                                 immAttrib3ubv(color, col_axis);
1243                         }
1244                         else
1245                                 immAttrib3ubv(color, col_grid_emphasise);
1246
1247                         immVertex2f(pos, 0.0f, -grid);
1248                         immVertex2f(pos, 0.0f, +grid);
1249
1250                         immEnd();
1251                         immUnbindProgram();
1252
1253                         /* done with XY plane */
1254                 }
1255
1256                 if (show_axis_x || show_axis_y || show_axis_z) {
1257                         /* draw axis lines -- sometimes grid floor is off, other times we still need to draw the Z axis */
1258
1259                         Gwn_VertFormat *format = immVertexFormat();
1260                         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
1261                         unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1262
1263                         immBindBuiltinProgram(GPU_SHADER_3D_FLAT_COLOR);
1264                         immBegin(GWN_PRIM_LINES, (show_axis_x + show_axis_y + show_axis_z) * 2);
1265
1266                         if (show_axis_x) {
1267                                 UI_make_axis_color(col_grid, col_axis, 'X');
1268                                 immAttrib3ubv(color, col_axis);
1269                                 immVertex3f(pos, -grid, 0.0f, 0.0f);
1270                                 immVertex3f(pos, +grid, 0.0f, 0.0f);
1271                         }
1272
1273                         if (show_axis_y) {
1274                                 UI_make_axis_color(col_grid, col_axis, 'Y');
1275                                 immAttrib3ubv(color, col_axis);
1276                                 immVertex3f(pos, 0.0f, -grid, 0.0f);
1277                                 immVertex3f(pos, 0.0f, +grid, 0.0f);
1278                         }
1279
1280                         if (show_axis_z) {
1281                                 UI_make_axis_color(col_grid, col_axis, 'Z');
1282                                 immAttrib3ubv(color, col_axis);
1283                                 immVertex3f(pos, 0.0f, 0.0f, -grid);
1284                                 immVertex3f(pos, 0.0f, 0.0f, +grid);
1285                         }
1286
1287                         immEnd();
1288                         immUnbindProgram();
1289                 }
1290
1291                 if (!write_depth)
1292                         glDepthMask(GL_TRUE);
1293         }
1294 }
1295
1296 /** could move this elsewhere, but tied into #ED_view3d_grid_scale */
1297 float ED_scene_grid_scale(Scene *scene, const char **grid_unit)
1298 {
1299         /* apply units */
1300         if (scene->unit.system) {
1301                 const void *usys;
1302                 int len;
1303
1304                 bUnit_GetSystem(scene->unit.system, B_UNIT_LENGTH, &usys, &len);
1305
1306                 if (usys) {
1307                         int i = bUnit_GetBaseUnit(usys);
1308                         if (grid_unit)
1309                                 *grid_unit = bUnit_GetNameDisplay(usys, i);
1310                         return (float)bUnit_GetScaler(usys, i) / scene->unit.scale_length;
1311                 }
1312         }
1313
1314         return 1.0f;
1315 }
1316
1317 float ED_view3d_grid_scale(Scene *scene, View3D *v3d, const char **grid_unit)
1318 {
1319         return v3d->grid * ED_scene_grid_scale(scene, grid_unit);
1320 }
1321
1322 static bool is_cursor_visible(Scene *scene, ViewLayer *view_layer)
1323 {
1324         if (U.app_flag & USER_APP_VIEW3D_HIDE_CURSOR) {
1325                 return false;
1326         }
1327
1328         Object *ob = OBACT(view_layer);
1329
1330         /* don't draw cursor in paint modes, but with a few exceptions */
1331         if (ob && ob->mode & OB_MODE_ALL_PAINT) {
1332                 /* exception: object is in weight paint and has deforming armature in pose mode */
1333                 if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1334                         if (BKE_object_pose_armature_get(ob) != NULL) {
1335                                 return true;
1336                         }
1337                 }
1338                 /* exception: object in texture paint mode, clone brush, use_clone_layer disabled */
1339                 else if (ob->mode & OB_MODE_TEXTURE_PAINT) {
1340                         const Paint *p = BKE_paint_get_active(scene, view_layer);
1341
1342                         if (p && p->brush && p->brush->imagepaint_tool == PAINT_TOOL_CLONE) {
1343                                 if ((scene->toolsettings->imapaint.flag & IMAGEPAINT_PROJECT_LAYER_CLONE) == 0) {
1344                                         return true;
1345                                 }
1346                         }
1347                 }
1348
1349                 /* no exception met? then don't draw cursor! */
1350                 return false;
1351         }
1352
1353         return true;
1354 }
1355
1356 static void drawcursor(Scene *scene, ARegion *ar, View3D *v3d)
1357 {
1358         int co[2];
1359
1360         /* we don't want the clipping for cursor */
1361         if (ED_view3d_project_int_global(ar, ED_view3d_cursor3d_get(scene, v3d), co, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1362                 const float f5 = 0.25f * U.widget_unit;
1363                 const float f10 = 0.5f * U.widget_unit;
1364                 const float f20 = U.widget_unit;
1365                 
1366                 glLineWidth(1.0f);
1367
1368                 Gwn_VertFormat *format = immVertexFormat();
1369                 unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1370                 unsigned int color = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 3, GWN_FETCH_INT_TO_FLOAT_UNIT);
1371
1372                 immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1373
1374                 const int segments = 16;
1375
1376                 immBegin(GWN_PRIM_LINE_LOOP, segments);
1377
1378                 for (int i = 0; i < segments; ++i) {
1379                         float angle = 2 * M_PI * ((float)i / (float)segments);
1380                         float x = co[0] + f10 * cosf(angle);
1381                         float y = co[1] + f10 * sinf(angle);
1382
1383                         if (i % 2 == 0)
1384                                 immAttrib3ub(color, 255, 0, 0);
1385                         else
1386                                 immAttrib3ub(color, 255, 255, 255);
1387
1388                         immVertex2f(pos, x, y);
1389                 }
1390                 immEnd();
1391
1392                 immUnbindProgram();
1393
1394                 GWN_vertformat_clear(format);
1395                 pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1396
1397                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1398
1399                 unsigned char crosshair_color[3];
1400                 UI_GetThemeColor3ubv(TH_VIEW_OVERLAY, crosshair_color);
1401                 immUniformColor3ubv(crosshair_color);
1402
1403                 immBegin(GWN_PRIM_LINES, 8);
1404                 immVertex2f(pos, co[0] - f20, co[1]);
1405                 immVertex2f(pos, co[0] - f5, co[1]);
1406                 immVertex2f(pos, co[0] + f5, co[1]);
1407                 immVertex2f(pos, co[0] + f20, co[1]);
1408                 immVertex2f(pos, co[0], co[1] - f20);
1409                 immVertex2f(pos, co[0], co[1] - f5);
1410                 immVertex2f(pos, co[0], co[1] + f5);
1411                 immVertex2f(pos, co[0], co[1] + f20);
1412                 immEnd();
1413
1414                 immUnbindProgram();
1415         }
1416 }
1417
1418 static void draw_view_axis(RegionView3D *rv3d, rcti *rect)
1419 {
1420         const float k = U.rvisize * U.pixelsize;  /* axis size */
1421         const int bright = - 20 * (10 - U.rvibright);  /* axis alpha offset (rvibright has range 0-10) */
1422
1423         const float startx = rect->xmin + k + 1.0f;  /* axis center in screen coordinates, x=y */
1424         const float starty = rect->ymin + k + 1.0f;
1425
1426         float axis_pos[3][2];
1427         unsigned char axis_col[3][4];
1428
1429         int axis_order[3] = {0, 1, 2};
1430         axis_sort_v3(rv3d->viewinv[2], axis_order);
1431
1432         for (int axis_i = 0; axis_i < 3; axis_i++) {
1433                 int i = axis_order[axis_i];
1434
1435                 /* get position of each axis tip on screen */
1436                 float vec[3] = { 0.0f };
1437                 vec[i] = 1.0f;
1438                 mul_qt_v3(rv3d->viewquat, vec);
1439                 axis_pos[i][0] = startx + vec[0] * k;
1440                 axis_pos[i][1] = starty + vec[1] * k;
1441
1442                 /* get color of each axis */
1443                 UI_GetThemeColorShade3ubv(TH_AXIS_X + i, bright, axis_col[i]); /* rgb */
1444                 axis_col[i][3] = 255 * hypotf(vec[0], vec[1]); /* alpha */
1445         }
1446
1447         /* draw axis lines */
1448         glLineWidth(2.0f);
1449         glEnable(GL_LINE_SMOOTH);
1450         glEnable(GL_BLEND);
1451         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1452
1453         Gwn_VertFormat *format = immVertexFormat();
1454         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1455         unsigned int col = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 4, GWN_FETCH_INT_TO_FLOAT_UNIT);
1456
1457         immBindBuiltinProgram(GPU_SHADER_2D_FLAT_COLOR);
1458         immBegin(GWN_PRIM_LINES, 6);
1459
1460         for (int axis_i = 0; axis_i < 3; axis_i++) {
1461                 int i = axis_order[axis_i];
1462
1463                 immAttrib4ubv(col, axis_col[i]);
1464                 immVertex2f(pos, startx, starty);
1465                 immVertex2fv(pos, axis_pos[i]);
1466         }
1467
1468         immEnd();
1469         immUnbindProgram();
1470         glDisable(GL_LINE_SMOOTH);
1471
1472         /* draw axis names */
1473         for (int axis_i = 0; axis_i < 3; axis_i++) {
1474                 int i = axis_order[axis_i];
1475
1476                 const char axis_text[2] = {'x' + i, '\0'};
1477                 BLF_color4ubv(BLF_default(), axis_col[i]);
1478                 BLF_draw_default_ascii(axis_pos[i][0] + 2, axis_pos[i][1] + 2, 0.0f, axis_text, 1);
1479         }
1480 }
1481
1482 #ifdef WITH_INPUT_NDOF
1483 /* draw center and axis of rotation for ongoing 3D mouse navigation */
1484 static void UNUSED_FUNCTION(draw_rotation_guide)(RegionView3D *rv3d)
1485 {
1486         float o[3];    /* center of rotation */
1487         float end[3];  /* endpoints for drawing */
1488
1489         GLubyte color[4] = {0, 108, 255, 255};  /* bright blue so it matches device LEDs */
1490
1491         negate_v3_v3(o, rv3d->ofs);
1492
1493         glEnable(GL_BLEND);
1494         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1495         glDepthMask(GL_FALSE);  /* don't overwrite zbuf */
1496
1497         Gwn_VertFormat *format = immVertexFormat();
1498         unsigned int pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 3, GWN_FETCH_FLOAT);
1499         unsigned int col = GWN_vertformat_attr_add(format, "color", GWN_COMP_U8, 4, GWN_FETCH_INT_TO_FLOAT_UNIT);
1500
1501         immBindBuiltinProgram(GPU_SHADER_3D_SMOOTH_COLOR);
1502
1503         if (rv3d->rot_angle != 0.0f) {
1504                 /* -- draw rotation axis -- */
1505                 float scaled_axis[3];
1506                 const float scale = rv3d->dist;
1507                 mul_v3_v3fl(scaled_axis, rv3d->rot_axis, scale);
1508
1509
1510                 immBegin(GWN_PRIM_LINE_STRIP, 3);
1511                 color[3] = 0; /* more transparent toward the ends */
1512                 immAttrib4ubv(col, color);
1513                 add_v3_v3v3(end, o, scaled_axis);
1514                 immVertex3fv(pos, end);
1515
1516 #if 0
1517                 color[3] = 0.2f + fabsf(rv3d->rot_angle);  /* modulate opacity with angle */
1518                 /* ^^ neat idea, but angle is frame-rate dependent, so it's usually close to 0.2 */
1519 #endif
1520
1521                 color[3] = 127; /* more opaque toward the center */
1522                 immAttrib4ubv(col, color);
1523                 immVertex3fv(pos, o);
1524
1525                 color[3] = 0;
1526                 immAttrib4ubv(col, color);
1527                 sub_v3_v3v3(end, o, scaled_axis);
1528                 immVertex3fv(pos, end);
1529                 immEnd();
1530                 
1531                 /* -- draw ring around rotation center -- */
1532                 {
1533 #define     ROT_AXIS_DETAIL 13
1534
1535                         const float s = 0.05f * scale;
1536                         const float step = 2.0f * (float)(M_PI / ROT_AXIS_DETAIL);
1537
1538                         float q[4];  /* rotate ring so it's perpendicular to axis */
1539                         const int upright = fabsf(rv3d->rot_axis[2]) >= 0.95f;
1540                         if (!upright) {
1541                                 const float up[3] = {0.0f, 0.0f, 1.0f};
1542                                 float vis_angle, vis_axis[3];
1543
1544                                 cross_v3_v3v3(vis_axis, up, rv3d->rot_axis);
1545                                 vis_angle = acosf(dot_v3v3(up, rv3d->rot_axis));
1546                                 axis_angle_to_quat(q, vis_axis, vis_angle);
1547                         }
1548
1549                         immBegin(GWN_PRIM_LINE_LOOP, ROT_AXIS_DETAIL);
1550                         color[3] = 63; /* somewhat faint */
1551                         immAttrib4ubv(col, color);
1552                         float angle = 0.0f;
1553                         for (int i = 0; i < ROT_AXIS_DETAIL; ++i, angle += step) {
1554                                 float p[3] = {s * cosf(angle), s * sinf(angle), 0.0f};
1555
1556                                 if (!upright) {
1557                                         mul_qt_v3(q, p);
1558                                 }
1559
1560                                 add_v3_v3(p, o);
1561                                 immVertex3fv(pos, p);
1562                         }
1563                         immEnd();
1564
1565 #undef      ROT_AXIS_DETAIL
1566                 }
1567
1568                 color[3] = 255;  /* solid dot */
1569         }
1570         else
1571                 color[3] = 127;  /* see-through dot */
1572
1573         immUnbindProgram();
1574
1575         /* -- draw rotation center -- */
1576         immBindBuiltinProgram(GPU_SHADER_3D_POINT_FIXED_SIZE_VARYING_COLOR);
1577         glPointSize(5.0f);
1578         immBegin(GWN_PRIM_POINTS, 1);
1579         immAttrib4ubv(col, color);
1580         immVertex3fv(pos, o);
1581         immEnd();
1582         immUnbindProgram();
1583
1584 #if 0
1585         /* find screen coordinates for rotation center, then draw pretty icon */
1586         mul_m4_v3(rv3d->persinv, rot_center);
1587         UI_icon_draw(rot_center[0], rot_center[1], ICON_NDOF_TURN);
1588         /* ^^ just playing around, does not work */
1589 #endif
1590
1591         glDisable(GL_BLEND);
1592         glDepthMask(GL_TRUE);
1593 }
1594 #endif /* WITH_INPUT_NDOF */
1595
1596 /* ******************** info ***************** */
1597
1598 /**
1599 * Render and camera border
1600 */
1601 static void view3d_draw_border(const bContext *C, ARegion *ar)
1602 {
1603         Scene *scene = CTX_data_scene(C);
1604         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1605         RegionView3D *rv3d = ar->regiondata;
1606         View3D *v3d = CTX_wm_view3d(C);
1607
1608         if (rv3d->persp == RV3D_CAMOB) {
1609                 drawviewborder(scene, depsgraph, ar, v3d);
1610         }
1611         else if (v3d->flag2 & V3D_RENDER_BORDER) {
1612                 drawrenderborder(ar, v3d);
1613         }
1614 }
1615
1616 /**
1617 * Grease Pencil
1618 */
1619 static void view3d_draw_grease_pencil(const bContext *UNUSED(C))
1620 {
1621         /* TODO viewport */
1622 }
1623
1624 /**
1625 * Viewport Name
1626 */
1627 static const char *view3d_get_name(View3D *v3d, RegionView3D *rv3d)
1628 {
1629         const char *name = NULL;
1630
1631         switch (rv3d->view) {
1632                 case RV3D_VIEW_FRONT:
1633                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Front Ortho");
1634                         else name = IFACE_("Front Persp");
1635                         break;
1636                 case RV3D_VIEW_BACK:
1637                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Back Ortho");
1638                         else name = IFACE_("Back Persp");
1639                         break;
1640                 case RV3D_VIEW_TOP:
1641                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Top Ortho");
1642                         else name = IFACE_("Top Persp");
1643                         break;
1644                 case RV3D_VIEW_BOTTOM:
1645                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Bottom Ortho");
1646                         else name = IFACE_("Bottom Persp");
1647                         break;
1648                 case RV3D_VIEW_RIGHT:
1649                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Right Ortho");
1650                         else name = IFACE_("Right Persp");
1651                         break;
1652                 case RV3D_VIEW_LEFT:
1653                         if (rv3d->persp == RV3D_ORTHO) name = IFACE_("Left Ortho");
1654                         else name = IFACE_("Left Persp");
1655                         break;
1656
1657                 default:
1658                         if (rv3d->persp == RV3D_CAMOB) {
1659                                 if ((v3d->camera) && (v3d->camera->type == OB_CAMERA)) {
1660                                         Camera *cam;
1661                                         cam = v3d->camera->data;
1662                                         if (cam->type == CAM_PERSP) {
1663                                                 name = IFACE_("Camera Persp");
1664                                         }
1665                                         else if (cam->type == CAM_ORTHO) {
1666                                                 name = IFACE_("Camera Ortho");
1667                                         }
1668                                         else {
1669                                                 BLI_assert(cam->type == CAM_PANO);
1670                                                 name = IFACE_("Camera Pano");
1671                                         }
1672                                 }
1673                                 else {
1674                                         name = IFACE_("Object as Camera");
1675                                 }
1676                         }
1677                         else {
1678                                 name = (rv3d->persp == RV3D_ORTHO) ? IFACE_("User Ortho") : IFACE_("User Persp");
1679                         }
1680         }
1681
1682         return name;
1683 }
1684
1685 static void draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
1686 {
1687         RegionView3D *rv3d = ar->regiondata;
1688         const char *name = view3d_get_name(v3d, rv3d);
1689         /* increase size for unicode languages (Chinese in utf-8...) */
1690 #ifdef WITH_INTERNATIONAL
1691         char tmpstr[96];
1692 #else
1693         char tmpstr[32];
1694 #endif
1695
1696         if (v3d->localvd) {
1697                 BLI_snprintf(tmpstr, sizeof(tmpstr), IFACE_("%s (Local)"), name);
1698                 name = tmpstr;
1699         }
1700
1701         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1702 #ifdef WITH_INTERNATIONAL
1703         BLF_draw_default(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
1704 #else
1705         BLF_draw_default_ascii(U.widget_unit + rect->xmin,  rect->ymax - U.widget_unit, 0.0f, name, sizeof(tmpstr));
1706 #endif
1707 }
1708
1709 /**
1710  * draw info beside axes in bottom left-corner:
1711  * framenum, object name, bone name (if available), marker name (if available)
1712  */
1713
1714 static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
1715 {
1716         const int cfra = CFRA;
1717         const char *msg_pin = " (Pinned)";
1718         const char *msg_sep = " : ";
1719
1720         const int font_id = BLF_default();
1721
1722         char info[300];
1723         char *s = info;
1724         short offset = 1.5f * UI_UNIT_X + rect->xmin;
1725
1726         s += sprintf(s, "(%d)", cfra);
1727
1728         /*
1729          * info can contain:
1730          * - a frame (7 + 2)
1731          * - 3 object names (MAX_NAME)
1732          * - 2 BREAD_CRUMB_SEPARATORs (6)
1733          * - a SHAPE_KEY_PINNED marker and a trailing '\0' (9+1) - translated, so give some room!
1734          * - a marker name (MAX_NAME + 3)
1735          */
1736
1737         /* get name of marker on current frame (if available) */
1738         const char *markern = BKE_scene_find_marker_name(scene, cfra);
1739
1740         /* check if there is an object */
1741         if (ob) {
1742                 *s++ = ' ';
1743                 s += BLI_strcpy_rlen(s, ob->id.name + 2);
1744
1745                 /* name(s) to display depends on type of object */
1746                 if (ob->type == OB_ARMATURE) {
1747                         bArmature *arm = ob->data;
1748
1749                         /* show name of active bone too (if possible) */
1750                         if (arm->edbo) {
1751                                 if (arm->act_edbone) {
1752                                         s += BLI_strcpy_rlen(s, msg_sep);
1753                                         s += BLI_strcpy_rlen(s, arm->act_edbone->name);
1754                                 }
1755                         }
1756                         else if (ob->mode & OB_MODE_POSE) {
1757                                 if (arm->act_bone) {
1758
1759                                         if (arm->act_bone->layer & arm->layer) {
1760                                                 s += BLI_strcpy_rlen(s, msg_sep);
1761                                                 s += BLI_strcpy_rlen(s, arm->act_bone->name);
1762                                         }
1763                                 }
1764                         }
1765                 }
1766                 else if (ELEM(ob->type, OB_MESH, OB_LATTICE, OB_CURVE)) {
1767                         /* try to display active bone and active shapekey too (if they exist) */
1768
1769                         if (ob->type == OB_MESH && ob->mode & OB_MODE_WEIGHT_PAINT) {
1770                                 Object *armobj = BKE_object_pose_armature_get(ob);
1771                                 if (armobj  && armobj->mode & OB_MODE_POSE) {
1772                                         bArmature *arm = armobj->data;
1773                                         if (arm->act_bone) {
1774                                                 if (arm->act_bone->layer & arm->layer) {
1775                                                         s += BLI_strcpy_rlen(s, msg_sep);
1776                                                         s += BLI_strcpy_rlen(s, arm->act_bone->name);
1777                                                 }
1778                                         }
1779                                 }
1780                         }
1781
1782                         Key *key = BKE_key_from_object(ob);
1783                         if (key) {
1784                                 KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1);
1785                                 if (kb) {
1786                                         s += BLI_strcpy_rlen(s, msg_sep);
1787                                         s += BLI_strcpy_rlen(s, kb->name);
1788                                         if (ob->shapeflag & OB_SHAPE_LOCK) {
1789                                                 s += BLI_strcpy_rlen(s, IFACE_(msg_pin));
1790                                         }
1791                                 }
1792                         }
1793                 }
1794
1795                 /* color depends on whether there is a keyframe */
1796                 if (id_frame_has_keyframe((ID *)ob, /* BKE_scene_frame_get(scene) */ (float)cfra, ANIMFILTER_KEYS_LOCAL))
1797                         UI_FontThemeColor(font_id, TH_TIME_KEYFRAME);
1798                 else if (ED_gpencil_has_keyframe_v3d(scene, ob, cfra))
1799                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
1800                 else
1801                         UI_FontThemeColor(font_id, TH_TEXT_HI);
1802         }
1803         else {
1804                 /* no object */
1805                 if (ED_gpencil_has_keyframe_v3d(scene, NULL, cfra))
1806                         UI_FontThemeColor(font_id, TH_TIME_GP_KEYFRAME);
1807                 else
1808                         UI_FontThemeColor(font_id, TH_TEXT_HI);
1809         }
1810
1811         if (markern) {
1812                 s += sprintf(s, " <%s>", markern);
1813         }
1814
1815         if (U.uiflag & USER_SHOW_ROTVIEWICON)
1816                 offset = U.widget_unit + (U.rvisize * 2) + rect->xmin;
1817
1818         BLF_draw_default(offset, 0.5f * U.widget_unit, 0.0f, info, sizeof(info));
1819 }
1820
1821 /* ******************** view loop ***************** */
1822
1823 /**
1824 * Information drawn on top of the solid plates and composed data
1825 */
1826 void view3d_draw_region_info(const bContext *C, ARegion *ar, const int offset)
1827 {
1828         RegionView3D *rv3d = ar->regiondata;
1829         View3D *v3d = CTX_wm_view3d(C);
1830         Scene *scene = CTX_data_scene(C);
1831         wmWindowManager *wm = CTX_wm_manager(C);
1832
1833         /* correct projection matrix */
1834         ED_region_pixelspace(ar);
1835
1836         /* local coordinate visible rect inside region, to accomodate overlapping ui */
1837         rcti rect;
1838         ED_region_visible_rect(ar, &rect);
1839
1840         /* Leave room for previously drawn info. */
1841         rect.ymax -= offset;
1842
1843         view3d_draw_border(C, ar);
1844         view3d_draw_grease_pencil(C);
1845
1846         if (U.uiflag & USER_SHOW_ROTVIEWICON) {
1847                 draw_view_axis(rv3d, &rect);
1848         }
1849
1850         if ((U.uiflag & USER_SHOW_FPS) && ED_screen_animation_no_scrub(wm)) {
1851                 ED_scene_draw_fps(scene, &rect);
1852         }
1853         else if (U.uiflag & USER_SHOW_VIEWPORTNAME) {
1854                 draw_viewport_name(ar, v3d, &rect);
1855         }
1856
1857         if (U.uiflag & USER_DRAWVIEWINFO) {
1858                 ViewLayer *view_layer = CTX_data_view_layer(C);
1859                 Object *ob = OBACT(view_layer);
1860                 draw_selected_name(scene, ob, &rect);
1861         }
1862 #if 0 /* TODO */
1863         if (grid_unit) { /* draw below the viewport name */
1864                 char numstr[32] = "";
1865
1866                 UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1867                 if (v3d->grid != 1.0f) {
1868                         BLI_snprintf(numstr, sizeof(numstr), "%s x %.4g", grid_unit, v3d->grid);
1869                 }
1870
1871                 BLF_draw_default_ascii(rect.xmin + U.widget_unit,
1872                                        rect.ymax - (USER_SHOW_VIEWPORTNAME ? 2 * U.widget_unit : U.widget_unit), 0.0f,
1873                                        numstr[0] ? numstr : grid_unit, sizeof(numstr));
1874         }
1875 #endif
1876 }
1877
1878 static void view3d_draw_view(const bContext *C, ARegion *ar)
1879 {
1880         EvaluationContext eval_ctx;
1881         CTX_data_eval_ctx(C, &eval_ctx);
1882
1883         ED_view3d_draw_setup_view(CTX_wm_window(C), &eval_ctx, CTX_data_scene(C), ar, CTX_wm_view3d(C), NULL, NULL, NULL);
1884
1885         /* Only 100% compliant on new spec goes bellow */
1886         DRW_draw_view(C);
1887 }
1888
1889 void view3d_main_region_draw(const bContext *C, ARegion *ar)
1890 {
1891         Scene *scene = CTX_data_scene(C);
1892         WorkSpace *workspace = CTX_wm_workspace(C);
1893         View3D *v3d = CTX_wm_view3d(C);
1894         RegionView3D *rv3d = ar->regiondata;
1895         ViewRender *view_render = BKE_viewrender_get(scene, workspace);
1896         RenderEngineType *type = RE_engines_find(view_render->engine_id);
1897
1898         /* Provisory Blender Internal drawing */
1899         if (type->flag & RE_USE_LEGACY_PIPELINE) {
1900                 view3d_main_region_draw_legacy(C, ar);
1901                 return;
1902         }
1903
1904         if (!rv3d->viewport) {
1905                 rv3d->viewport = GPU_viewport_create();
1906         }
1907
1908         GPU_viewport_bind(rv3d->viewport, &ar->winrct);
1909         view3d_draw_view(C, ar);
1910         GPU_viewport_unbind(rv3d->viewport);
1911
1912         v3d->flag |= V3D_INVALID_BACKBUF;
1913 }
1914
1915
1916 /* -------------------------------------------------------------------- */
1917
1918 /** \name Offscreen Drawing
1919  * \{ */
1920
1921 static void view3d_stereo3d_setup_offscreen(
1922         const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar,
1923         float winmat[4][4], const char *viewname)
1924 {
1925         /* update the viewport matrices with the new camera */
1926         if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
1927                 float viewmat[4][4];
1928                 const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
1929
1930                 BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
1931                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, NULL);
1932         }
1933         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
1934                 float viewmat[4][4];
1935                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
1936
1937                 BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
1938                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, NULL);
1939         }
1940 }
1941
1942 void ED_view3d_draw_offscreen_init(const EvaluationContext *eval_ctx, Scene *scene, ViewLayer *view_layer, View3D *v3d)
1943 {
1944         RenderEngineType *engine_type = eval_ctx->engine_type;
1945         if (engine_type->flag & RE_USE_LEGACY_PIPELINE) {
1946                 /* shadow buffers, before we setup matrices */
1947                 if (draw_glsl_material(scene, view_layer, NULL, v3d, v3d->drawtype)) {
1948                         VP_deprecated_gpu_update_lamps_shadows_world(eval_ctx, scene, v3d);
1949                 }
1950         }
1951 }
1952
1953 /*
1954  * Function to clear the view
1955  */
1956 static void view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
1957 {
1958         glClear(GL_DEPTH_BUFFER_BIT);
1959
1960         if (scene->world && (v3d->flag3 & V3D_SHOW_WORLD)) {
1961                 VP_view3d_draw_background_world(scene, ar->regiondata);
1962         }
1963         else {
1964                 VP_view3d_draw_background_none();
1965         }
1966 }
1967
1968 /* ED_view3d_draw_offscreen_init should be called before this to initialize
1969  * stuff like shadow buffers
1970  */
1971 void ED_view3d_draw_offscreen(
1972         const EvaluationContext *eval_ctx, Scene *scene, ViewLayer *view_layer,
1973         View3D *v3d, ARegion *ar, int winx, int winy,
1974         float viewmat[4][4], float winmat[4][4],
1975         bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
1976         GPUFX *fx, GPUFXSettings *fx_settings,
1977         GPUOffScreen *ofs, GPUViewport *viewport)
1978 {
1979         bool do_compositing = false;
1980         RegionView3D *rv3d = ar->regiondata;
1981
1982         /* set temporary new size */
1983         int bwinx = ar->winx;
1984         int bwiny = ar->winy;
1985         rcti brect = ar->winrct;
1986
1987         ar->winx = winx;
1988         ar->winy = winy;
1989         ar->winrct.xmin = 0;
1990         ar->winrct.ymin = 0;
1991         ar->winrct.xmax = winx;
1992         ar->winrct.ymax = winy;
1993
1994         struct bThemeState theme_state;
1995         UI_Theme_Store(&theme_state);
1996         UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
1997
1998         /* set flags */
1999         G.f |= G_RENDER_OGL;
2000
2001         if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
2002                 /* free images which can have changed on frame-change
2003                  * warning! can be slow so only free animated images - campbell */
2004                 GPU_free_images_anim();
2005         }
2006
2007         gpuPushProjectionMatrix();
2008         gpuLoadIdentity();
2009         gpuPushMatrix();
2010         gpuLoadIdentity();
2011
2012         /* clear opengl buffers */
2013         if (do_sky) {
2014                 view3d_main_region_clear(scene, v3d, ar);
2015         }
2016         else {
2017                 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
2018                 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
2019         }
2020
2021         if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
2022                 view3d_stereo3d_setup_offscreen(eval_ctx, scene, v3d, ar, winmat, viewname);
2023         else
2024                 view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, NULL);
2025
2026         /* XXX, should take depsgraph as arg */
2027         Depsgraph *depsgraph = BKE_scene_get_depsgraph(scene, view_layer, false);
2028         BLI_assert(depsgraph != NULL);
2029
2030         /* main drawing call */
2031         RenderEngineType *engine_type = eval_ctx->engine_type;
2032         if (engine_type->flag & RE_USE_LEGACY_PIPELINE) {
2033
2034                 /* framebuffer fx needed, we need to draw offscreen first */
2035                 if (v3d->fx_settings.fx_flag && fx) {
2036                         GPUSSAOSettings *ssao = NULL;
2037
2038                         if (v3d->drawtype < OB_SOLID) {
2039                                 ssao = v3d->fx_settings.ssao;
2040                                 v3d->fx_settings.ssao = NULL;
2041                         }
2042
2043                         do_compositing = GPU_fx_compositor_initialize_passes(fx, &ar->winrct, NULL, fx_settings);
2044
2045                         if (ssao)
2046                                 v3d->fx_settings.ssao = ssao;
2047                 }
2048
2049                 VP_deprecated_view3d_draw_objects(NULL, eval_ctx, scene, v3d, ar, NULL, do_bgpic, true, do_compositing ? fx : NULL);
2050
2051                 /* post process */
2052                 if (do_compositing) {
2053                         if (!winmat)
2054                                 is_persp = rv3d->is_persp;
2055                         GPU_fx_do_composite_pass(fx, winmat, is_persp, scene, ofs);
2056                 }
2057
2058                 if ((v3d->flag2 & V3D_RENDER_SHADOW) == 0) {
2059                         /* draw grease-pencil stuff */
2060                         ED_region_pixelspace(ar);
2061
2062                         if (v3d->flag2 & V3D_SHOW_GPENCIL) {
2063                                 /* draw grease-pencil stuff - needed to get paint-buffer shown too (since it's 2D) */
2064                                 ED_gpencil_draw_view3d(NULL, scene, view_layer, depsgraph, v3d, ar, false);
2065                         }
2066
2067                         /* freeing the images again here could be done after the operator runs, leaving for now */
2068                         GPU_free_images_anim();
2069                 }
2070         }
2071         else {
2072                 DRW_draw_render_loop_offscreen(depsgraph, eval_ctx->engine_type, ar, v3d, do_sky, ofs, viewport);
2073         }
2074
2075         /* restore size */
2076         ar->winx = bwinx;
2077         ar->winy = bwiny;
2078         ar->winrct = brect;
2079
2080         gpuPopProjectionMatrix();
2081         gpuPopMatrix();
2082
2083         UI_Theme_Restore(&theme_state);
2084
2085         G.f &= ~G_RENDER_OGL;
2086 }
2087
2088 /**
2089  * Utility func for ED_view3d_draw_offscreen
2090  *
2091  * \param ofs: Optional off-screen buffer, can be NULL.
2092  * (avoids re-creating when doing multiple GL renders).
2093  */
2094 ImBuf *ED_view3d_draw_offscreen_imbuf(
2095         const EvaluationContext *eval_ctx, Scene *scene, ViewLayer *view_layer,
2096         View3D *v3d, ARegion *ar, int sizex, int sizey,
2097         unsigned int flag, unsigned int draw_flags,
2098         int alpha_mode, int samples, const char *viewname,
2099         /* output vars */
2100         GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
2101 {
2102         const Depsgraph *depsgraph = eval_ctx->depsgraph;
2103         RegionView3D *rv3d = ar->regiondata;
2104         const bool draw_sky = (alpha_mode == R_ADDSKY);
2105         const bool draw_background = (draw_flags & V3D_OFSDRAW_USE_BACKGROUND);
2106         const bool use_full_sample = (draw_flags & V3D_OFSDRAW_USE_FULL_SAMPLE);
2107
2108         /* view state */
2109         GPUFXSettings fx_settings = v3d->fx_settings;
2110         bool is_ortho = false;
2111         float winmat[4][4];
2112
2113         if (ofs && ((GPU_offscreen_width(ofs) != sizex) || (GPU_offscreen_height(ofs) != sizey))) {
2114                 /* sizes differ, can't reuse */
2115                 ofs = NULL;
2116         }
2117
2118         const bool own_ofs = (ofs == NULL);
2119
2120         if (own_ofs) {
2121                 /* bind */
2122                 ofs = GPU_offscreen_create(sizex, sizey, use_full_sample ? 0 : samples, false, err_out);
2123                 if (ofs == NULL) {
2124                         return NULL;
2125                 }
2126         }
2127
2128         ED_view3d_draw_offscreen_init(eval_ctx, scene, view_layer, v3d);
2129
2130         GPU_offscreen_bind(ofs, true);
2131
2132         /* read in pixels & stamp */
2133         ImBuf *ibuf = IMB_allocImBuf(sizex, sizey, 32, flag);
2134
2135         /* render 3d view */
2136         if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
2137                 CameraParams params;
2138                 Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
2139
2140                 BKE_camera_params_init(&params);
2141                 /* fallback for non camera objects */
2142                 params.clipsta = v3d->near;
2143                 params.clipend = v3d->far;
2144                 BKE_camera_params_from_object(&params, camera);
2145                 BKE_camera_multiview_params(&scene->r, &params, camera, viewname);
2146                 BKE_camera_params_compute_viewplane(&params, sizex, sizey, scene->r.xasp, scene->r.yasp);
2147                 BKE_camera_params_compute_matrix(&params);
2148
2149                 BKE_camera_to_gpu_dof(camera, &fx_settings);
2150
2151                 is_ortho = params.is_ortho;
2152                 copy_m4_m4(winmat, params.winmat);
2153         }
2154         else {
2155                 rctf viewplane;
2156                 float clipsta, clipend;
2157
2158                 is_ortho = ED_view3d_viewplane_get(depsgraph, v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
2159                 if (is_ortho) {
2160                         orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
2161                 }
2162                 else {
2163                         perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
2164                 }
2165         }
2166
2167         if ((samples && use_full_sample) == 0) {
2168                 /* Single-pass render, common case */
2169                 ED_view3d_draw_offscreen(
2170                         eval_ctx, scene, view_layer, v3d, ar, sizex, sizey, NULL, winmat,
2171                         draw_background, draw_sky, !is_ortho, viewname,
2172                         fx, &fx_settings, ofs, NULL);
2173
2174                 if (ibuf->rect_float) {
2175                         GPU_offscreen_read_pixels(ofs, GL_FLOAT, ibuf->rect_float);
2176                 }
2177                 else if (ibuf->rect) {
2178                         GPU_offscreen_read_pixels(ofs, GL_UNSIGNED_BYTE, ibuf->rect);
2179                 }
2180         }
2181         else {
2182                 /* Multi-pass render, use accumulation buffer & jitter for 'full' oversampling.
2183                  * Use because OpenGL may use a lower quality MSAA, and only over-sample edges. */
2184                 static float jit_ofs[32][2];
2185                 float winmat_jitter[4][4];
2186                 float *rect_temp = (ibuf->rect_float) ? ibuf->rect_float : MEM_mallocN(sizex * sizey * sizeof(float[4]), "rect_temp");
2187                 float *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(float[4]), "accum_buffer");
2188                 GPUViewport *viewport = GPU_viewport_create_from_offscreen(ofs);
2189
2190                 BLI_jitter_init(jit_ofs, samples);
2191
2192                 /* first sample buffer, also initializes 'rv3d->persmat' */
2193                 ED_view3d_draw_offscreen(
2194                         eval_ctx, scene, view_layer, v3d, ar, sizex, sizey, NULL, winmat,
2195                         draw_background, draw_sky, !is_ortho, viewname,
2196                         fx, &fx_settings, ofs, viewport);
2197                 GPU_offscreen_read_pixels(ofs, GL_FLOAT, accum_buffer);
2198
2199                 /* skip the first sample */
2200                 for (int j = 1; j < samples; j++) {
2201                         copy_m4_m4(winmat_jitter, winmat);
2202                         window_translate_m4(
2203                                 winmat_jitter, rv3d->persmat,
2204                                 (jit_ofs[j][0] * 2.0f) / sizex,
2205                                 (jit_ofs[j][1] * 2.0f) / sizey);
2206
2207                         ED_view3d_draw_offscreen(
2208                                 eval_ctx, scene, view_layer, v3d, ar, sizex, sizey, NULL, winmat_jitter,
2209                                 draw_background, draw_sky, !is_ortho, viewname,
2210                                 fx, &fx_settings, ofs, viewport);
2211                         GPU_offscreen_read_pixels(ofs, GL_FLOAT, rect_temp);
2212
2213                         unsigned int i = sizex * sizey * 4;
2214                         while (i--) {
2215                                 accum_buffer[i] += rect_temp[i];
2216                         }
2217                 }
2218
2219                 {
2220                         /* don't free data owned by 'ofs' */
2221                         GPU_viewport_clear_from_offscreen(viewport);
2222                         GPU_viewport_free(viewport);
2223                         MEM_freeN(viewport);
2224                 }
2225
2226                 if (ibuf->rect_float == NULL) {
2227                         MEM_freeN(rect_temp);
2228                 }
2229
2230                 if (ibuf->rect_float) {
2231                         float *rect_float = ibuf->rect_float;
2232                         unsigned int i = sizex * sizey * 4;
2233                         while (i--) {
2234                                 rect_float[i] = accum_buffer[i] / samples;
2235                         }
2236                 }
2237                 else {
2238                         unsigned char *rect_ub = (unsigned char *)ibuf->rect;
2239                         unsigned int i = sizex * sizey * 4;
2240                         while (i--) {
2241                                 rect_ub[i] = (unsigned char)(255.0f * accum_buffer[i] / samples);
2242                         }
2243                 }
2244
2245                 MEM_freeN(accum_buffer);
2246         }
2247
2248         /* unbind */
2249         GPU_offscreen_unbind(ofs, true);
2250
2251         if (own_ofs) {
2252                 GPU_offscreen_free(ofs);
2253         }
2254
2255         if (ibuf->rect_float && ibuf->rect)
2256                 IMB_rect_from_float(ibuf);
2257
2258         return ibuf;
2259 }
2260
2261 /**
2262  * Creates own fake 3d views (wrapping #ED_view3d_draw_offscreen_imbuf)
2263  *
2264  * \param ofs: Optional off-screen buffer can be NULL.
2265  * (avoids re-creating when doing multiple GL renders).
2266  *
2267  * \note used by the sequencer
2268  */
2269 ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
2270         const EvaluationContext *eval_ctx, Scene *scene, ViewLayer *view_layer,
2271         Object *camera, int width, int height,
2272         unsigned int flag, unsigned int draw_flags, int drawtype,
2273         int alpha_mode, int samples, const char *viewname,
2274         GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
2275 {
2276         View3D v3d = {NULL};
2277         ARegion ar = {NULL};
2278         RegionView3D rv3d = {{{0}}};
2279
2280         /* connect data */
2281         v3d.regionbase.first = v3d.regionbase.last = &ar;
2282         ar.regiondata = &rv3d;
2283         ar.regiontype = RGN_TYPE_WINDOW;
2284
2285         v3d.camera = camera;
2286         v3d.lay = scene->lay;
2287         v3d.drawtype = drawtype;
2288         v3d.flag2 = V3D_RENDER_OVERRIDE;
2289
2290         if (draw_flags & V3D_OFSDRAW_USE_GPENCIL) {
2291                 v3d.flag2 |= V3D_SHOW_GPENCIL;
2292         }
2293         if (draw_flags & V3D_OFSDRAW_USE_SOLID_TEX) {
2294                 v3d.flag2 |= V3D_SOLID_TEX;
2295         }
2296         if (draw_flags & V3D_OFSDRAW_USE_BACKGROUND) {
2297                 v3d.flag3 |= V3D_SHOW_WORLD;
2298         }
2299         if (draw_flags & V3D_OFSDRAW_USE_CAMERA_DOF) {
2300                 if (camera->type == OB_CAMERA) {
2301                         v3d.fx_settings.dof = &((Camera *)camera->data)->gpu_dof;
2302                         v3d.fx_settings.fx_flag |= GPU_FX_FLAG_DOF;
2303                 }
2304         }
2305
2306         rv3d.persp = RV3D_CAMOB;
2307
2308         copy_m4_m4(rv3d.viewinv, v3d.camera->obmat);
2309         normalize_m4(rv3d.viewinv);
2310         invert_m4_m4(rv3d.viewmat, rv3d.viewinv);
2311
2312         {
2313                 CameraParams params;
2314                 Object *view_camera = BKE_camera_multiview_render(scene, v3d.camera, viewname);
2315
2316                 BKE_camera_params_init(&params);
2317                 BKE_camera_params_from_object(&params, view_camera);
2318                 BKE_camera_multiview_params(&scene->r, &params, view_camera, viewname);
2319                 BKE_camera_params_compute_viewplane(&params, width, height, scene->r.xasp, scene->r.yasp);
2320                 BKE_camera_params_compute_matrix(&params);
2321
2322                 copy_m4_m4(rv3d.winmat, params.winmat);
2323                 v3d.near = params.clipsta;
2324                 v3d.far = params.clipend;
2325                 v3d.lens = params.lens;
2326         }
2327
2328         mul_m4_m4m4(rv3d.persmat, rv3d.winmat, rv3d.viewmat);
2329         invert_m4_m4(rv3d.persinv, rv3d.viewinv);
2330
2331         return ED_view3d_draw_offscreen_imbuf(
2332                 eval_ctx, scene, view_layer, &v3d, &ar, width, height, flag,
2333                 draw_flags, alpha_mode, samples, viewname, fx, ofs, err_out);
2334 }
2335
2336 /** \} */
2337
2338
2339 /* -------------------------------------------------------------------- */
2340
2341 /** \name Legacy Interface
2342  *
2343  * This will be removed once the viewport gets replaced
2344  * meanwhile it should keep the old viewport working.
2345  *
2346  * \{ */
2347
2348 void VP_legacy_drawcursor(Scene *scene, ViewLayer *view_layer, ARegion *ar, View3D *v3d)
2349 {
2350         if (is_cursor_visible(scene, view_layer)) {
2351                 drawcursor(scene, ar, v3d);
2352         }
2353 }
2354
2355 void VP_legacy_draw_view_axis(RegionView3D *rv3d, rcti *rect)
2356 {
2357         draw_view_axis(rv3d, rect);
2358 }
2359
2360 void VP_legacy_draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
2361 {
2362         draw_viewport_name(ar, v3d, rect);
2363 }
2364
2365 void VP_legacy_draw_selected_name(Scene *scene, Object *ob, rcti *rect)
2366 {
2367         draw_selected_name(scene, ob, rect);
2368 }
2369
2370 void VP_legacy_drawgrid(UnitSettings *unit, ARegion *ar, View3D *v3d, const char **grid_unit)
2371 {
2372         drawgrid(unit, ar, v3d, grid_unit);
2373 }
2374
2375 void VP_legacy_drawfloor(Scene *scene, View3D *v3d, const char **grid_unit, bool write_depth)
2376 {
2377         drawfloor(scene, v3d, grid_unit, write_depth);
2378 }
2379
2380 void VP_legacy_view3d_main_region_setup_view(
2381         const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d,
2382         ARegion *ar, float viewmat[4][4], float winmat[4][4])
2383 {
2384         view3d_main_region_setup_view(eval_ctx, scene, v3d, ar, viewmat, winmat, NULL);
2385 }
2386
2387 bool VP_legacy_view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
2388 {
2389         return view3d_stereo3d_active(win, scene, v3d, rv3d);
2390 }
2391
2392 void VP_legacy_view3d_stereo3d_setup(const EvaluationContext *eval_ctx, Scene *scene, View3D *v3d, ARegion *ar)
2393 {
2394         view3d_stereo3d_setup(eval_ctx, scene, v3d, ar, NULL);
2395 }
2396
2397 bool VP_legacy_use_depth(Scene *scene, View3D *v3d)
2398 {
2399         return use_depth_doit(scene, v3d);
2400 }
2401
2402 void VP_drawviewborder(Scene *scene, const struct Depsgraph *depsgraph, ARegion *ar, View3D *v3d)
2403 {
2404         drawviewborder(scene, depsgraph, ar, v3d);
2405 }
2406
2407 void VP_drawrenderborder(ARegion *ar, View3D *v3d)
2408 {
2409         drawrenderborder(ar, v3d);
2410 }
2411
2412 void VP_view3d_draw_background_none(void)
2413 {
2414         if (UI_GetThemeValue(TH_SHOW_BACK_GRAD)) {
2415                 view3d_draw_background_gradient();
2416         }
2417         else {
2418                 view3d_draw_background_none();
2419         }
2420 }
2421
2422 void VP_view3d_draw_background_world(Scene *scene, RegionView3D *rv3d)
2423 {
2424         view3d_draw_background_world(scene, rv3d);
2425 }
2426
2427 void VP_view3d_main_region_clear(Scene *scene, View3D *v3d, ARegion *ar)
2428 {
2429         view3d_main_region_clear(scene, v3d, ar);
2430 }
2431
2432 /** \} */