GPU: Fix color difference when rendering to gpu_py_offscreen
[blender.git] / source / blender / draw / intern / draw_manager.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * Copyright 2016, Blender Foundation.
17  */
18
19 /** \file
20  * \ingroup draw
21  */
22
23 #include <stdio.h>
24
25 #include "BLI_listbase.h"
26 #include "BLI_mempool.h"
27 #include "BLI_rect.h"
28 #include "BLI_string.h"
29 #include "BLI_threads.h"
30
31 #include "BLF_api.h"
32
33 #include "BKE_colortools.h"
34 #include "BKE_curve.h"
35 #include "BKE_global.h"
36 #include "BKE_gpencil.h"
37 #include "BKE_lattice.h"
38 #include "BKE_mball.h"
39 #include "BKE_mesh.h"
40 #include "BKE_object.h"
41 #include "BKE_particle.h"
42 #include "BKE_pointcache.h"
43
44 #include "draw_manager.h"
45 #include "DNA_camera_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_world_types.h"
49
50 #include "ED_space_api.h"
51 #include "ED_screen.h"
52 #include "ED_gpencil.h"
53 #include "ED_view3d.h"
54
55 #include "GPU_draw.h"
56 #include "GPU_extensions.h"
57 #include "GPU_framebuffer.h"
58 #include "GPU_immediate.h"
59 #include "GPU_uniformbuffer.h"
60 #include "GPU_viewport.h"
61 #include "GPU_matrix.h"
62 #include "GPU_select.h"
63
64 #include "IMB_colormanagement.h"
65
66 #include "RE_engine.h"
67 #include "RE_pipeline.h"
68
69 #include "UI_resources.h"
70
71 #include "WM_api.h"
72 #include "wm_window.h"
73
74 #include "draw_manager_text.h"
75 #include "draw_manager_profiling.h"
76
77 /* only for callbacks */
78 #include "draw_cache_impl.h"
79
80 #include "draw_mode_engines.h"
81 #include "engines/eevee/eevee_engine.h"
82 #include "engines/basic/basic_engine.h"
83 #include "engines/workbench/workbench_engine.h"
84 #include "engines/external/external_engine.h"
85
86 #include "GPU_context.h"
87
88 #include "DEG_depsgraph.h"
89 #include "DEG_depsgraph_query.h"
90
91 #ifdef USE_GPU_SELECT
92 #  include "GPU_select.h"
93 #endif
94
95 /** Render State: No persistent data between draw calls. */
96 DRWManager DST = {NULL};
97
98 static ListBase DRW_engines = {NULL, NULL};
99
100 static void drw_state_prepare_clean_for_draw(DRWManager *dst)
101 {
102         memset(dst, 0x0, offsetof(DRWManager, gl_context));
103
104         /* Maybe not the best place for this. */
105         if (!DST.uniform_names.buffer) {
106                 DST.uniform_names.buffer = MEM_callocN(DRW_UNIFORM_BUFFER_NAME, "Name Buffer");
107                 DST.uniform_names.buffer_len = DRW_UNIFORM_BUFFER_NAME;
108         }
109         else if (DST.uniform_names.buffer_len > DRW_UNIFORM_BUFFER_NAME) {
110                 DST.uniform_names.buffer = MEM_reallocN(DST.uniform_names.buffer, DRW_UNIFORM_BUFFER_NAME);
111                 DST.uniform_names.buffer_len = DRW_UNIFORM_BUFFER_NAME;
112         }
113         DST.uniform_names.buffer_ofs = 0;
114 }
115
116 /* This function is used to reset draw manager to a state
117  * where we don't re-use data by accident across different
118  * draw calls.
119  */
120 #ifdef DEBUG
121 static void drw_state_ensure_not_reused(DRWManager *dst)
122 {
123         memset(dst, 0xff, offsetof(DRWManager, gl_context));
124 }
125 #endif
126
127 /* -------------------------------------------------------------------- */
128
129 void DRW_draw_callbacks_pre_scene(void)
130 {
131         RegionView3D *rv3d = DST.draw_ctx.rv3d;
132
133         GPU_matrix_projection_set(rv3d->winmat);
134         GPU_matrix_set(rv3d->viewmat);
135 }
136
137 void DRW_draw_callbacks_post_scene(void)
138 {
139         RegionView3D *rv3d = DST.draw_ctx.rv3d;
140
141         GPU_matrix_projection_set(rv3d->winmat);
142         GPU_matrix_set(rv3d->viewmat);
143 }
144
145 struct DRWTextStore *DRW_text_cache_ensure(void)
146 {
147         BLI_assert(DST.text_store_p);
148         if (*DST.text_store_p == NULL) {
149                 *DST.text_store_p = DRW_text_cache_create();
150         }
151         return *DST.text_store_p;
152 }
153
154
155 /* -------------------------------------------------------------------- */
156 /** \name Settings
157  * \{ */
158
159 bool DRW_object_is_renderable(const Object *ob)
160 {
161         BLI_assert((ob->base_flag & BASE_VISIBLE) != 0);
162
163         if (ob->type == OB_MESH) {
164                 if ((ob == DST.draw_ctx.object_edit) || BKE_object_is_in_editmode(ob)) {
165                         View3D *v3d = DST.draw_ctx.v3d;
166                         const int mask = (V3D_OVERLAY_EDIT_OCCLUDE_WIRE | V3D_OVERLAY_EDIT_WEIGHT);
167
168                         if (v3d && v3d->overlay.edit_flag & mask) {
169                                 return false;
170                         }
171                 }
172         }
173
174         return true;
175 }
176
177 /**
178  * Return whether this object is visible depending if
179  * we are rendering or drawing in the viewport.
180  */
181 int DRW_object_visibility_in_active_context(const Object *ob)
182 {
183         const eEvaluationMode mode = DRW_state_is_scene_render() ?
184                                              DAG_EVAL_RENDER :
185                                              DAG_EVAL_VIEWPORT;
186         return BKE_object_visibility(ob, mode);
187 }
188
189 bool DRW_object_is_flat_normal(const Object *ob)
190 {
191         if (ob->type == OB_MESH) {
192                 const Mesh *me = ob->data;
193                 if (me->mpoly && me->mpoly[0].flag & ME_SMOOTH) {
194                         return false;
195                 }
196         }
197         return true;
198 }
199
200 bool DRW_object_use_hide_faces(const struct Object *ob)
201 {
202         if (ob->type == OB_MESH) {
203                 const Mesh *me = DEG_get_original_object((Object *)ob)->data;
204
205                 switch (ob->mode) {
206                         case OB_MODE_TEXTURE_PAINT:
207                                 return (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
208                         case OB_MODE_VERTEX_PAINT:
209                         case OB_MODE_WEIGHT_PAINT:
210                                 return (me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
211                 }
212         }
213
214         return false;
215 }
216
217 bool DRW_object_is_visible_psys_in_active_context(
218         const Object *object,
219         const ParticleSystem *psys)
220 {
221         const bool for_render = DRW_state_is_image_render();
222         /* NOTE: psys_check_enabled is using object and particle system for only
223          * reading, but is using some other functions which are more generic and
224          * which are hard to make const-pointer. */
225         if (!psys_check_enabled((Object *)object, (ParticleSystem *)psys, for_render)) {
226                 return false;
227         }
228         const DRWContextState *draw_ctx = DRW_context_state_get();
229         const Scene *scene = draw_ctx->scene;
230         if (object == draw_ctx->object_edit) {
231                 return false;
232         }
233         const ParticleSettings *part = psys->part;
234         const ParticleEditSettings *pset = &scene->toolsettings->particle;
235         if (object->mode == OB_MODE_PARTICLE_EDIT) {
236                 if (psys_in_edit_mode(draw_ctx->depsgraph, psys)) {
237                         if ((pset->flag & PE_DRAW_PART) == 0) {
238                                 return false;
239                         }
240                         if ((part->childtype == 0) &&
241                             (psys->flag & PSYS_HAIR_DYNAMICS &&
242                              psys->pointcache->flag & PTCACHE_BAKED) == 0)
243                         {
244                                 return false;
245                         }
246                 }
247         }
248         return true;
249 }
250
251 struct Object *DRW_object_get_dupli_parent(const Object *UNUSED(ob))
252 {
253         return DST.dupli_parent;
254 }
255
256 struct DupliObject *DRW_object_get_dupli(const Object *UNUSED(ob))
257 {
258         return DST.dupli_source;
259 }
260
261 /** \} */
262
263
264 /* -------------------------------------------------------------------- */
265 /** \name Color Management
266  * \{ */
267
268 /* Use color management profile to draw texture to framebuffer */
269 void DRW_transform_to_display(GPUTexture *tex, bool use_view_transform, bool use_render_settings)
270 {
271         drw_state_set(DRW_STATE_WRITE_COLOR);
272
273         GPUVertFormat *vert_format = immVertexFormat();
274         uint pos = GPU_vertformat_attr_add(vert_format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
275         uint texco = GPU_vertformat_attr_add(vert_format, "texCoord", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
276
277         const float dither = 1.0f;
278
279         bool use_ocio = false;
280
281         /* View transform is already applied for offscreen, don't apply again, see: T52046 */
282         if (!(DST.options.is_image_render && !DST.options.is_scene_render)) {
283                 Scene *scene = DST.draw_ctx.scene;
284                 ColorManagedDisplaySettings *display_settings = &scene->display_settings;
285                 ColorManagedViewSettings view_settings;
286                 if (use_render_settings) {
287                         /* Use full render settings, for renders with scene lighting. */
288                         view_settings = scene->view_settings;
289                 }
290                 else if (use_view_transform) {
291                         /* Use only view transform + look and nothing else for lookdev without
292                          * scene lighting, as exposure depends on scene light intensity. */
293                         BKE_color_managed_view_settings_init_render(&view_settings, display_settings, NULL);
294                         STRNCPY(view_settings.view_transform, scene->view_settings.view_transform);
295                         STRNCPY(view_settings.look, scene->view_settings.look);
296                 }
297                 else {
298                         /* For workbench use only default view transform in configuration,
299                          * using no scene settings. */
300                         BKE_color_managed_view_settings_init_render(&view_settings, display_settings, NULL);
301                 }
302
303                 use_ocio = IMB_colormanagement_setup_glsl_draw_from_space(
304                         &view_settings, display_settings, NULL, dither, false);
305         }
306
307         if (!use_ocio) {
308                 /* View transform is already applied for offscreen, don't apply again, see: T52046 */
309                 if (DST.options.is_image_render && !DST.options.is_scene_render) {
310                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_COLOR);
311                         immUniformColor4f(1.0f, 1.0f, 1.0f, 1.0f);
312                 }
313                 else {
314                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_LINEAR_TO_SRGB);
315                 }
316                 immUniform1i("image", 0);
317         }
318
319         GPU_texture_bind(tex, 0); /* OCIO texture bind point is 0 */
320
321         float mat[4][4];
322         unit_m4(mat);
323         immUniformMatrix4fv("ModelViewProjectionMatrix", mat);
324
325         /* Full screen triangle */
326         immBegin(GPU_PRIM_TRIS, 3);
327         immAttr2f(texco, 0.0f, 0.0f);
328         immVertex2f(pos, -1.0f, -1.0f);
329
330         immAttr2f(texco, 2.0f, 0.0f);
331         immVertex2f(pos, 3.0f, -1.0f);
332
333         immAttr2f(texco, 0.0f, 2.0f);
334         immVertex2f(pos, -1.0f, 3.0f);
335         immEnd();
336
337         GPU_texture_unbind(tex);
338
339         if (use_ocio) {
340                 IMB_colormanagement_finish_glsl_draw();
341         }
342         else {
343                 immUnbindProgram();
344         }
345 }
346
347 /* Draw texture to framebuffer without any color transforms */
348 void DRW_transform_none(GPUTexture *tex)
349 {
350         drw_state_set(DRW_STATE_WRITE_COLOR);
351
352         /* Draw as texture for final render (without immediate mode). */
353         GPUBatch *geom = DRW_cache_fullscreen_quad_get();
354         GPU_batch_program_set_builtin(geom, GPU_SHADER_2D_IMAGE_COLOR);
355
356         GPU_texture_bind(tex, 0);
357
358         const float white[4] = {1.0f, 1.0f, 1.0f, 1.0f};
359         GPU_batch_uniform_4fv(geom, "color", white);
360
361         float mat[4][4];
362         unit_m4(mat);
363         GPU_batch_uniform_mat4(geom, "ModelViewProjectionMatrix", mat);
364
365         GPU_batch_program_use_begin(geom);
366         GPU_batch_draw_range_ex(geom, 0, 0, false);
367         GPU_batch_program_use_end(geom);
368
369         GPU_texture_unbind(tex);
370 }
371
372 /** \} */
373
374
375 /* -------------------------------------------------------------------- */
376 /** \name Multisample Resolve
377  * \{ */
378
379 /**
380  * Use manual multisample resolve pass.
381  * Much quicker than blitting back and forth.
382  * Assume destination fb is bound.
383  */
384 void DRW_multisamples_resolve(GPUTexture *src_depth, GPUTexture *src_color, bool use_depth)
385 {
386         DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND_PREMUL;
387
388         if (use_depth) {
389                 state |= DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL;
390         }
391         drw_state_set(state);
392
393         int samples = GPU_texture_samples(src_depth);
394
395         BLI_assert(samples > 0);
396         BLI_assert(GPU_texture_samples(src_color) == samples);
397
398         GPUBatch *geom = DRW_cache_fullscreen_quad_get();
399
400         int builtin;
401         if (use_depth) {
402                 switch (samples) {
403                         case 2:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2_DEPTH_TEST; break;
404                         case 4:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_4_DEPTH_TEST; break;
405                         case 8:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_8_DEPTH_TEST; break;
406                         case 16: builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_16_DEPTH_TEST; break;
407                         default:
408                                 BLI_assert("Mulisample count unsupported by blit shader.");
409                                 builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2_DEPTH_TEST;
410                                 break;
411                 }
412         }
413         else {
414                 switch (samples) {
415                         case 2:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2; break;
416                         case 4:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_4; break;
417                         case 8:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_8; break;
418                         case 16: builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_16; break;
419                         default:
420                                 BLI_assert("Mulisample count unsupported by blit shader.");
421                                 builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2;
422                                 break;
423                 }
424         }
425
426         GPU_batch_program_set_builtin(geom, builtin);
427
428         if (use_depth) {
429                 GPU_texture_bind(src_depth, 0);
430                 GPU_batch_uniform_1i(geom, "depthMulti", 0);
431         }
432
433         GPU_texture_bind(src_color, 1);
434         GPU_batch_uniform_1i(geom, "colorMulti", 1);
435
436         float mat[4][4];
437         unit_m4(mat);
438         GPU_batch_uniform_mat4(geom, "ModelViewProjectionMatrix", mat);
439
440         /* avoid gpuMatrix calls */
441         GPU_batch_program_use_begin(geom);
442         GPU_batch_draw_range_ex(geom, 0, 0, false);
443         GPU_batch_program_use_end(geom);
444 }
445
446 /** \} */
447
448 /* -------------------------------------------------------------------- */
449 /** \name Viewport (DRW_viewport)
450  * \{ */
451
452 void *drw_viewport_engine_data_ensure(void *engine_type)
453 {
454         void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
455
456         if (data == NULL) {
457                 data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
458         }
459         return data;
460 }
461
462 void DRW_engine_viewport_data_size_get(
463         const void *engine_type_v,
464         int *r_fbl_len, int *r_txl_len, int *r_psl_len, int *r_stl_len)
465 {
466         const DrawEngineType *engine_type = engine_type_v;
467
468         if (r_fbl_len) {
469                 *r_fbl_len = engine_type->vedata_size->fbl_len;
470         }
471         if (r_txl_len) {
472                 *r_txl_len = engine_type->vedata_size->txl_len;
473         }
474         if (r_psl_len) {
475                 *r_psl_len = engine_type->vedata_size->psl_len;
476         }
477         if (r_stl_len) {
478                 *r_stl_len = engine_type->vedata_size->stl_len;
479         }
480 }
481
482 /* WARNING: only use for custom pipeline. 99% of the time, you don't want to use this. */
483 void DRW_render_viewport_size_set(int size[2])
484 {
485         DST.size[0] = size[0];
486         DST.size[1] = size[1];
487 }
488
489 const float *DRW_viewport_size_get(void)
490 {
491         return DST.size;
492 }
493
494 const float *DRW_viewport_invert_size_get(void)
495 {
496         return DST.inv_size;
497 }
498
499 const float *DRW_viewport_screenvecs_get(void)
500 {
501         return &DST.screenvecs[0][0];
502 }
503
504 const float *DRW_viewport_pixelsize_get(void)
505 {
506         return &DST.pixsize;
507 }
508
509 static void drw_viewport_cache_resize(void)
510 {
511         /* Release the memiter before clearing the mempools that references them */
512         GPU_viewport_cache_release(DST.viewport);
513
514         if (DST.vmempool != NULL) {
515                 BLI_mempool_clear_ex(DST.vmempool->calls, BLI_mempool_len(DST.vmempool->calls));
516                 BLI_mempool_clear_ex(DST.vmempool->states, BLI_mempool_len(DST.vmempool->states));
517                 BLI_mempool_clear_ex(DST.vmempool->shgroups, BLI_mempool_len(DST.vmempool->shgroups));
518                 BLI_mempool_clear_ex(DST.vmempool->uniforms, BLI_mempool_len(DST.vmempool->uniforms));
519                 BLI_mempool_clear_ex(DST.vmempool->passes, BLI_mempool_len(DST.vmempool->passes));
520         }
521
522         DRW_instance_data_list_free_unused(DST.idatalist);
523         DRW_instance_data_list_resize(DST.idatalist);
524 }
525
526 /* Not a viewport variable, we could split this out. */
527 static void drw_context_state_init(void)
528 {
529         if (DST.draw_ctx.obact) {
530                 DST.draw_ctx.object_mode = DST.draw_ctx.obact->mode;
531         }
532         else {
533                 DST.draw_ctx.object_mode = OB_MODE_OBJECT;
534         }
535
536         /* Edit object. */
537         if (DST.draw_ctx.object_mode & OB_MODE_EDIT) {
538                 DST.draw_ctx.object_edit = DST.draw_ctx.obact;
539         }
540         else {
541                 DST.draw_ctx.object_edit = NULL;
542         }
543
544         /* Pose object. */
545         if (DST.draw_ctx.object_mode & OB_MODE_POSE) {
546                 DST.draw_ctx.object_pose = DST.draw_ctx.obact;
547         }
548         else if (DST.draw_ctx.object_mode & OB_MODE_WEIGHT_PAINT) {
549                 DST.draw_ctx.object_pose = BKE_object_pose_armature_get(DST.draw_ctx.obact);
550         }
551         else {
552                 DST.draw_ctx.object_pose = NULL;
553         }
554
555         DST.draw_ctx.sh_cfg = GPU_SHADER_CFG_DEFAULT;
556         if (DST.draw_ctx.rv3d && DST.draw_ctx.rv3d->rflag & RV3D_CLIPPING) {
557                 DST.draw_ctx.sh_cfg = GPU_SHADER_CFG_CLIPPED;
558         }
559 }
560
561 /* It also stores viewport variable to an immutable place: DST
562  * This is because a cache uniform only store reference
563  * to its value. And we don't want to invalidate the cache
564  * if this value change per viewport */
565 static void drw_viewport_var_init(void)
566 {
567         RegionView3D *rv3d = DST.draw_ctx.rv3d;
568         /* Refresh DST.size */
569         if (DST.viewport) {
570                 int size[2];
571                 GPU_viewport_size_get(DST.viewport, size);
572                 DST.size[0] = size[0];
573                 DST.size[1] = size[1];
574                 DST.inv_size[0] = 1.0f / size[0];
575                 DST.inv_size[1] = 1.0f / size[1];
576
577                 DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
578                 DST.default_framebuffer = fbl->default_fb;
579
580                 DST.vmempool = GPU_viewport_mempool_get(DST.viewport);
581
582                 if (DST.vmempool->calls == NULL) {
583                         DST.vmempool->calls = BLI_mempool_create(sizeof(DRWCall), 0, 512, 0);
584                 }
585                 if (DST.vmempool->states == NULL) {
586                         DST.vmempool->states = BLI_mempool_create(sizeof(DRWCallState), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
587                 }
588                 if (DST.vmempool->shgroups == NULL) {
589                         DST.vmempool->shgroups = BLI_mempool_create(sizeof(DRWShadingGroup), 0, 256, 0);
590                 }
591                 if (DST.vmempool->uniforms == NULL) {
592                         DST.vmempool->uniforms = BLI_mempool_create(sizeof(DRWUniform), 0, 512, 0);
593                 }
594                 if (DST.vmempool->passes == NULL) {
595                         DST.vmempool->passes = BLI_mempool_create(sizeof(DRWPass), 0, 64, 0);
596                 }
597
598                 DST.idatalist = GPU_viewport_instance_data_list_get(DST.viewport);
599                 DRW_instance_data_list_reset(DST.idatalist);
600         }
601         else {
602                 DST.size[0] = 0;
603                 DST.size[1] = 0;
604
605                 DST.inv_size[0] = 0;
606                 DST.inv_size[1] = 0;
607
608                 DST.default_framebuffer = NULL;
609                 DST.vmempool = NULL;
610         }
611
612         if (rv3d != NULL) {
613                 /* Refresh DST.screenvecs */
614                 copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
615                 copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
616                 normalize_v3(DST.screenvecs[0]);
617                 normalize_v3(DST.screenvecs[1]);
618
619                 /* Refresh DST.pixelsize */
620                 DST.pixsize = rv3d->pixsize;
621
622                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERS], rv3d->persmat);
623                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERSINV], rv3d->persinv);
624                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEW], rv3d->viewmat);
625                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEWINV], rv3d->viewinv);
626                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_WIN], rv3d->winmat);
627                 invert_m4_m4(DST.original_mat.mat[DRW_MAT_WININV], rv3d->winmat);
628
629                 memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DST.original_mat.mat));
630
631                 copy_v4_v4(DST.view_data.viewcamtexcofac, rv3d->viewcamtexcofac);
632         }
633         else {
634                 copy_v4_fl4(DST.view_data.viewcamtexcofac, 1.0f, 1.0f, 0.0f, 0.0f);
635         }
636
637         /* Reset facing */
638         DST.frontface = GL_CCW;
639         DST.backface = GL_CW;
640         glFrontFace(DST.frontface);
641
642         if (DST.draw_ctx.object_edit) {
643                 ED_view3d_init_mats_rv3d(DST.draw_ctx.object_edit, rv3d);
644         }
645
646         /* Alloc array of texture reference. */
647         if (DST.RST.bound_texs == NULL) {
648                 DST.RST.bound_texs = MEM_callocN(sizeof(GPUTexture *) * GPU_max_textures(), "Bound GPUTexture refs");
649         }
650         if (DST.RST.bound_tex_slots == NULL) {
651                 DST.RST.bound_tex_slots = MEM_callocN(sizeof(char) * GPU_max_textures(), "Bound Texture Slots");
652         }
653         if (DST.RST.bound_ubos == NULL) {
654                 DST.RST.bound_ubos = MEM_callocN(sizeof(GPUUniformBuffer *) * GPU_max_ubo_binds(), "Bound GPUUniformBuffer refs");
655         }
656         if (DST.RST.bound_ubo_slots == NULL) {
657                 DST.RST.bound_ubo_slots = MEM_callocN(sizeof(char) * GPU_max_ubo_binds(), "Bound Ubo Slots");
658         }
659
660         if (G_draw.view_ubo == NULL) {
661                 G_draw.view_ubo = DRW_uniformbuffer_create(sizeof(ViewUboStorage), NULL);
662         }
663
664         DST.override_mat = 0;
665         DST.dirty_mat = true;
666         DST.state_cache_id = 1;
667
668         DST.clipping.updated = false;
669
670         memset(DST.object_instance_data, 0x0, sizeof(DST.object_instance_data));
671 }
672
673 void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
674 {
675         BLI_assert(type >= 0 && type < DRW_MAT_COUNT);
676         /* Can't use this in render mode. */
677         BLI_assert(((DST.override_mat & (1 << type)) != 0) || DST.draw_ctx.rv3d != NULL);
678
679         copy_m4_m4(mat, DST.view_data.matstate.mat[type]);
680 }
681
682 void DRW_viewport_matrix_get_all(DRWMatrixState *state)
683 {
684         memcpy(state, DST.view_data.matstate.mat, sizeof(DRWMatrixState));
685 }
686
687 void DRW_viewport_matrix_override_set(const float mat[4][4], DRWViewportMatrixType type)
688 {
689         BLI_assert(type < DRW_MAT_COUNT);
690         copy_m4_m4(DST.view_data.matstate.mat[type], mat);
691         DST.override_mat |= (1 << type);
692         DST.dirty_mat = true;
693         DST.clipping.updated = false;
694 }
695
696 void DRW_viewport_matrix_override_unset(DRWViewportMatrixType type)
697 {
698         BLI_assert(type < DRW_MAT_COUNT);
699         copy_m4_m4(DST.view_data.matstate.mat[type], DST.original_mat.mat[type]);
700         DST.override_mat &= ~(1 << type);
701         DST.dirty_mat = true;
702         DST.clipping.updated = false;
703 }
704
705 void DRW_viewport_matrix_override_set_all(DRWMatrixState *state)
706 {
707         memcpy(DST.view_data.matstate.mat, state, sizeof(DRWMatrixState));
708         DST.override_mat = 0xFFFFFF;
709         DST.dirty_mat = true;
710         DST.clipping.updated = false;
711 }
712
713 void DRW_viewport_matrix_override_unset_all(void)
714 {
715         memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DRWMatrixState));
716         DST.override_mat = 0;
717         DST.dirty_mat = true;
718         DST.clipping.updated = false;
719 }
720
721 bool DRW_viewport_is_persp_get(void)
722 {
723         RegionView3D *rv3d = DST.draw_ctx.rv3d;
724         if (rv3d) {
725                 return rv3d->is_persp;
726         }
727         else {
728                 return DST.view_data.matstate.mat[DRW_MAT_WIN][3][3] == 0.0f;
729         }
730 }
731
732 float DRW_viewport_near_distance_get(void)
733 {
734         float projmat[4][4];
735         DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
736
737         if (DRW_viewport_is_persp_get()) {
738                 return -projmat[3][2] / (projmat[2][2] - 1.0f);
739         }
740         else {
741                 return -(projmat[3][2] + 1.0f) / projmat[2][2];
742         }
743 }
744
745 float DRW_viewport_far_distance_get(void)
746 {
747         float projmat[4][4];
748         DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
749
750         if (DRW_viewport_is_persp_get()) {
751                 return -projmat[3][2] / (projmat[2][2] + 1.0f);
752         }
753         else {
754                 return -(projmat[3][2] - 1.0f) / projmat[2][2];
755         }
756 }
757
758 DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
759 {
760         return GPU_viewport_framebuffer_list_get(DST.viewport);
761 }
762
763 DefaultTextureList *DRW_viewport_texture_list_get(void)
764 {
765         return GPU_viewport_texture_list_get(DST.viewport);
766 }
767
768 void DRW_viewport_request_redraw(void)
769 {
770         GPU_viewport_tag_update(DST.viewport);
771 }
772
773 /** \} */
774
775
776 /* -------------------------------------------------------------------- */
777 /** \name ViewLayers (DRW_scenelayer)
778  * \{ */
779
780 void *DRW_view_layer_engine_data_get(DrawEngineType *engine_type)
781 {
782         for (ViewLayerEngineData *sled = DST.draw_ctx.view_layer->drawdata.first; sled; sled = sled->next) {
783                 if (sled->engine_type == engine_type) {
784                         return sled->storage;
785                 }
786         }
787         return NULL;
788 }
789
790 void **DRW_view_layer_engine_data_ensure_ex(
791         ViewLayer *view_layer, DrawEngineType *engine_type, void (*callback)(void *storage))
792 {
793         ViewLayerEngineData *sled;
794
795         for (sled = view_layer->drawdata.first; sled; sled = sled->next) {
796                 if (sled->engine_type == engine_type) {
797                         return &sled->storage;
798                 }
799         }
800
801         sled = MEM_callocN(sizeof(ViewLayerEngineData), "ViewLayerEngineData");
802         sled->engine_type = engine_type;
803         sled->free = callback;
804         BLI_addtail(&view_layer->drawdata, sled);
805
806         return &sled->storage;
807 }
808
809 void **DRW_view_layer_engine_data_ensure(DrawEngineType *engine_type, void (*callback)(void *storage))
810 {
811         return DRW_view_layer_engine_data_ensure_ex(DST.draw_ctx.view_layer, engine_type, callback);
812 }
813
814 /** \} */
815
816
817 /* -------------------------------------------------------------------- */
818 /** \name Draw Data (DRW_drawdata)
819  * \{ */
820
821 /* Used for DRW_drawdata_from_id()
822  * All ID-datablocks which have their own 'local' DrawData
823  * should have the same arrangement in their structs.
824  */
825 typedef struct IdDdtTemplate {
826         ID id;
827         struct AnimData *adt;
828         DrawDataList drawdata;
829 } IdDdtTemplate;
830
831 /* Check if ID can have AnimData */
832 static bool id_type_can_have_drawdata(const short id_type)
833 {
834         /* Only some ID-blocks have this info for now */
835         /* TODO: finish adding this for the other blocktypes */
836         switch (id_type) {
837                 /* has DrawData */
838                 case ID_OB:
839                 case ID_WO:
840                         return true;
841
842                 /* no DrawData */
843                 default:
844                         return false;
845         }
846 }
847
848 static bool id_can_have_drawdata(const ID *id)
849 {
850         /* sanity check */
851         if (id == NULL) {
852                 return false;
853         }
854
855         return id_type_can_have_drawdata(GS(id->name));
856 }
857
858 /* Get DrawData from the given ID-block. In order for this to work, we assume that
859  * the DrawData pointer is stored in the struct in the same fashion as in IdDdtTemplate.
860  */
861 DrawDataList *DRW_drawdatalist_from_id(ID *id)
862 {
863         /* only some ID-blocks have this info for now, so we cast the
864          * types that do to be of type IdDdtTemplate, and extract the
865          * DrawData that way
866          */
867         if (id_can_have_drawdata(id)) {
868                 IdDdtTemplate *idt = (IdDdtTemplate *)id;
869                 return &idt->drawdata;
870         }
871         else {
872                 return NULL;
873         }
874 }
875
876 DrawData *DRW_drawdata_get(ID *id, DrawEngineType *engine_type)
877 {
878         DrawDataList *drawdata = DRW_drawdatalist_from_id(id);
879
880         if (drawdata == NULL) {
881                 return NULL;
882         }
883
884         LISTBASE_FOREACH(DrawData *, dd, drawdata) {
885                 if (dd->engine_type == engine_type) {
886                         return dd;
887                 }
888         }
889         return NULL;
890 }
891
892 DrawData *DRW_drawdata_ensure(
893         ID *id,
894         DrawEngineType *engine_type,
895         size_t size,
896         DrawDataInitCb init_cb,
897         DrawDataFreeCb free_cb)
898 {
899         BLI_assert(size >= sizeof(DrawData));
900         BLI_assert(id_can_have_drawdata(id));
901         /* Try to re-use existing data. */
902         DrawData *dd = DRW_drawdata_get(id, engine_type);
903         if (dd != NULL) {
904                 return dd;
905         }
906
907         DrawDataList *drawdata = DRW_drawdatalist_from_id(id);
908
909         /* Allocate new data. */
910         if ((GS(id->name) == ID_OB) && (((Object *)id)->base_flag & BASE_FROM_DUPLI) != 0) {
911                 /* NOTE: data is not persistent in this case. It is reset each redraw. */
912                 BLI_assert(free_cb == NULL); /* No callback allowed. */
913                 /* Round to sizeof(float) for DRW_instance_data_request(). */
914                 const size_t t = sizeof(float) - 1;
915                 size = (size + t) & ~t;
916                 size_t fsize = size / sizeof(float);
917                 BLI_assert(fsize < MAX_INSTANCE_DATA_SIZE);
918                 if (DST.object_instance_data[fsize] == NULL) {
919                         DST.object_instance_data[fsize] = DRW_instance_data_request(DST.idatalist, fsize);
920                 }
921                 dd = (DrawData *)DRW_instance_data_next(DST.object_instance_data[fsize]);
922                 memset(dd, 0, size);
923         }
924         else {
925                 dd = MEM_callocN(size, "DrawData");
926         }
927         dd->engine_type = engine_type;
928         dd->free = free_cb;
929         /* Perform user-side initialization, if needed. */
930         if (init_cb != NULL) {
931                 init_cb(dd);
932         }
933         /* Register in the list. */
934         BLI_addtail((ListBase *)drawdata, dd);
935         return dd;
936 }
937
938 void DRW_drawdata_free(ID *id)
939 {
940         DrawDataList *drawdata = DRW_drawdatalist_from_id(id);
941
942         if (drawdata == NULL) {
943                 return;
944         }
945
946         LISTBASE_FOREACH(DrawData *, dd, drawdata) {
947                 if (dd->free != NULL) {
948                         dd->free(dd);
949                 }
950         }
951
952         BLI_freelistN((ListBase *)drawdata);
953 }
954
955 /* Unlink (but don't free) the drawdata from the DrawDataList if the ID is an OB from dupli. */
956 static void drw_drawdata_unlink_dupli(ID *id)
957 {
958         if ((GS(id->name) == ID_OB) && (((Object *)id)->base_flag & BASE_FROM_DUPLI) != 0) {
959                 DrawDataList *drawdata = DRW_drawdatalist_from_id(id);
960
961                 if (drawdata == NULL) {
962                         return;
963                 }
964
965                 BLI_listbase_clear((ListBase *)drawdata);
966         }
967 }
968
969 /** \} */
970
971
972 /* -------------------------------------------------------------------- */
973 /** \name Rendering (DRW_engines)
974  * \{ */
975
976 static void drw_engines_init(void)
977 {
978         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
979                 DrawEngineType *engine = link->data;
980                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
981                 PROFILE_START(stime);
982
983                 if (engine->engine_init) {
984                         engine->engine_init(data);
985                 }
986
987                 PROFILE_END_UPDATE(data->init_time, stime);
988         }
989 }
990
991 static void drw_engines_cache_init(void)
992 {
993         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
994                 DrawEngineType *engine = link->data;
995                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
996
997                 if (data->text_draw_cache) {
998                         DRW_text_cache_destroy(data->text_draw_cache);
999                         data->text_draw_cache = NULL;
1000                 }
1001                 if (DST.text_store_p == NULL) {
1002                         DST.text_store_p = &data->text_draw_cache;
1003                 }
1004
1005                 if (engine->cache_init) {
1006                         engine->cache_init(data);
1007                 }
1008         }
1009 }
1010
1011 static void drw_engines_world_update(Scene *scene)
1012 {
1013         if (scene->world == NULL) {
1014                 return;
1015         }
1016
1017         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1018                 DrawEngineType *engine = link->data;
1019                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1020
1021                 if (engine->id_update) {
1022                         engine->id_update(data, &scene->world->id);
1023                 }
1024         }
1025 }
1026
1027 static void drw_engines_cache_populate(Object *ob)
1028 {
1029         DST.ob_state = NULL;
1030
1031         /* HACK: DrawData is copied by COW from the duplicated object.
1032          * This is valid for IDs that cannot be instantiated but this
1033          * is not what we want in this case so we clear the pointer
1034          * ourselves here. */
1035         drw_drawdata_unlink_dupli((ID *)ob);
1036
1037         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1038                 DrawEngineType *engine = link->data;
1039                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1040
1041                 if (engine->id_update) {
1042                         engine->id_update(data, &ob->id);
1043                 }
1044
1045                 if (engine->cache_populate) {
1046                         engine->cache_populate(data, ob);
1047                 }
1048         }
1049
1050         /* TODO: in the future it would be nice to generate once for all viewports.
1051          * But we need threaded DRW manager first. */
1052         drw_batch_cache_generate_requested(ob);
1053
1054         /* ... and clearing it here too because theses draw data are
1055          * from a mempool and must not be free individually by depsgraph. */
1056         drw_drawdata_unlink_dupli((ID *)ob);
1057 }
1058
1059 static void drw_engines_cache_finish(void)
1060 {
1061         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1062                 DrawEngineType *engine = link->data;
1063                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1064
1065                 if (engine->cache_finish) {
1066                         engine->cache_finish(data);
1067                 }
1068         }
1069 }
1070
1071 static void drw_engines_draw_background(void)
1072 {
1073         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1074                 DrawEngineType *engine = link->data;
1075                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1076
1077                 if (engine->draw_background) {
1078                         PROFILE_START(stime);
1079
1080                         DRW_stats_group_start(engine->idname);
1081                         engine->draw_background(data);
1082                         DRW_stats_group_end();
1083
1084                         PROFILE_END_UPDATE(data->background_time, stime);
1085                         return;
1086                 }
1087         }
1088
1089         /* No draw_background found, doing default background */
1090         if (DRW_state_draw_background()) {
1091                 DRW_draw_background();
1092         }
1093 }
1094
1095 static void drw_engines_draw_scene(void)
1096 {
1097         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1098                 DrawEngineType *engine = link->data;
1099                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1100                 PROFILE_START(stime);
1101
1102                 if (engine->draw_scene) {
1103                         DRW_stats_group_start(engine->idname);
1104                         engine->draw_scene(data);
1105                         /* Restore for next engine */
1106                         if (DRW_state_is_fbo()) {
1107                                 GPU_framebuffer_bind(DST.default_framebuffer);
1108                         }
1109                         DRW_stats_group_end();
1110                 }
1111
1112                 PROFILE_END_UPDATE(data->render_time, stime);
1113         }
1114         /* Reset state after drawing */
1115         DRW_state_reset();
1116 }
1117
1118 static void drw_engines_draw_text(void)
1119 {
1120         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1121                 DrawEngineType *engine = link->data;
1122                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1123                 PROFILE_START(stime);
1124
1125                 if (data->text_draw_cache) {
1126                         DRW_text_cache_draw(data->text_draw_cache, DST.draw_ctx.ar);
1127                 }
1128
1129                 PROFILE_END_UPDATE(data->render_time, stime);
1130         }
1131 }
1132
1133 /* Draw render engine info. */
1134 void DRW_draw_region_engine_info(int xoffset, int yoffset)
1135 {
1136         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1137                 DrawEngineType *engine = link->data;
1138                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
1139
1140                 if (data->info[0] != '\0') {
1141                         char *chr_current = data->info;
1142                         char *chr_start = chr_current;
1143                         int line_len = 0;
1144
1145                         const int font_id = BLF_default();
1146                         UI_FontThemeColor(font_id, TH_TEXT_HI);
1147
1148                         BLF_enable(font_id, BLF_SHADOW);
1149                         BLF_shadow(font_id, 5, (const float[4]){0.0f, 0.0f, 0.0f, 1.0f});
1150                         BLF_shadow_offset(font_id, 1, -1);
1151
1152                         while (*chr_current++ != '\0') {
1153                                 line_len++;
1154                                 if (*chr_current == '\n') {
1155                                         char info[GPU_INFO_SIZE];
1156                                         BLI_strncpy(info, chr_start, line_len + 1);
1157                                         yoffset -= U.widget_unit;
1158                                         BLF_draw_default(xoffset, yoffset, 0.0f, info, sizeof(info));
1159
1160                                         /* Re-start counting. */
1161                                         chr_start = chr_current + 1;
1162                                         line_len = -1;
1163                                 }
1164                         }
1165
1166                         char info[GPU_INFO_SIZE];
1167                         BLI_strncpy(info, chr_start, line_len + 1);
1168                         yoffset -= U.widget_unit;
1169                         BLF_draw_default(xoffset, yoffset, 0.0f, info, sizeof(info));
1170
1171                         BLF_disable(font_id, BLF_SHADOW);
1172                 }
1173         }
1174 }
1175
1176 static void use_drw_engine(DrawEngineType *engine)
1177 {
1178         LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
1179         ld->data = engine;
1180         BLI_addtail(&DST.enabled_engines, ld);
1181 }
1182
1183 /**
1184  * Use for external render engines.
1185  */
1186 static void drw_engines_enable_external(void)
1187 {
1188         use_drw_engine(DRW_engine_viewport_external_type.draw_engine);
1189 }
1190
1191 /* TODO revisit this when proper layering is implemented */
1192 /* Gather all draw engines needed and store them in DST.enabled_engines
1193  * That also define the rendering order of engines */
1194 static void drw_engines_enable_from_engine(RenderEngineType *engine_type, int drawtype, bool use_xray)
1195 {
1196         switch (drawtype) {
1197                 case OB_WIRE:
1198                         use_drw_engine(&draw_engine_workbench_transparent);
1199                         break;
1200
1201                 case OB_SOLID:
1202                         if (use_xray) {
1203                                 use_drw_engine(&draw_engine_workbench_transparent);
1204                         }
1205                         else {
1206                                 use_drw_engine(&draw_engine_workbench_solid);
1207                         }
1208                         break;
1209
1210                 case OB_MATERIAL:
1211                 case OB_RENDER:
1212                 default:
1213                         /* TODO layers */
1214                         if (engine_type->draw_engine != NULL) {
1215                                 use_drw_engine(engine_type->draw_engine);
1216                         }
1217
1218                         if ((engine_type->flag & RE_INTERNAL) == 0) {
1219                                 drw_engines_enable_external();
1220                         }
1221                         break;
1222         }
1223 }
1224
1225 static void drw_engines_enable_from_object_mode(void)
1226 {
1227         use_drw_engine(&draw_engine_object_type);
1228         /* TODO(fclem) remove this, it does not belong to it's own engine. */
1229         use_drw_engine(&draw_engine_motion_path_type);
1230 }
1231
1232 static void drw_engines_enable_from_paint_mode(int mode)
1233 {
1234         switch (mode) {
1235                 case CTX_MODE_SCULPT:
1236                         use_drw_engine(&draw_engine_sculpt_type);
1237                         break;
1238                 case CTX_MODE_PAINT_WEIGHT:
1239                 case CTX_MODE_PAINT_VERTEX:
1240                         use_drw_engine(&draw_engine_paint_vertex_type);
1241                         break;
1242                 case CTX_MODE_PAINT_TEXTURE:
1243                         use_drw_engine(&draw_engine_paint_texture_type);
1244                         break;
1245                 default:
1246                         break;
1247         }
1248 }
1249
1250 static void drw_engines_enable_from_mode(int mode)
1251 {
1252         switch (mode) {
1253                 case CTX_MODE_EDIT_MESH:
1254                         use_drw_engine(&draw_engine_edit_mesh_type);
1255                         break;
1256                 case CTX_MODE_EDIT_SURFACE:
1257                 case CTX_MODE_EDIT_CURVE:
1258                         use_drw_engine(&draw_engine_edit_curve_type);
1259                         break;
1260                 case CTX_MODE_EDIT_TEXT:
1261                         use_drw_engine(&draw_engine_edit_text_type);
1262                         break;
1263                 case CTX_MODE_EDIT_ARMATURE:
1264                         use_drw_engine(&draw_engine_edit_armature_type);
1265                         break;
1266                 case CTX_MODE_EDIT_METABALL:
1267                         use_drw_engine(&draw_engine_edit_metaball_type);
1268                         break;
1269                 case CTX_MODE_EDIT_LATTICE:
1270                         use_drw_engine(&draw_engine_edit_lattice_type);
1271                         break;
1272                 case CTX_MODE_PARTICLE:
1273                         use_drw_engine(&draw_engine_particle_type);
1274                         break;
1275                 case CTX_MODE_POSE:
1276                 case CTX_MODE_PAINT_WEIGHT:
1277                         /* The pose engine clears the depth of the default framebuffer
1278                          * to draw an object with `OB_DRAWXRAY`.
1279                          * (different of workbench that has its own framebuffer).
1280                          * So make sure you call its `draw_scene` after all the other engines. */
1281                         use_drw_engine(&draw_engine_pose_type);
1282                         break;
1283                 case CTX_MODE_SCULPT:
1284                 case CTX_MODE_PAINT_VERTEX:
1285                 case CTX_MODE_PAINT_TEXTURE:
1286                 case CTX_MODE_OBJECT:
1287                 case CTX_MODE_PAINT_GPENCIL:
1288                 case CTX_MODE_EDIT_GPENCIL:
1289                 case CTX_MODE_SCULPT_GPENCIL:
1290                 case CTX_MODE_WEIGHT_GPENCIL:
1291                         break;
1292                 default:
1293                         BLI_assert(!"Draw mode invalid");
1294                         break;
1295         }
1296 }
1297
1298 static void drw_engines_enable_from_overlays(int UNUSED(overlay_flag))
1299 {
1300         use_drw_engine(&draw_engine_overlay_type);
1301 }
1302 /**
1303  * Use for select and depth-drawing.
1304  */
1305 static void drw_engines_enable_basic(void)
1306 {
1307         use_drw_engine(DRW_engine_viewport_basic_type.draw_engine);
1308 }
1309
1310 static void drw_engines_enable(ViewLayer *view_layer, RenderEngineType *engine_type)
1311 {
1312         Object *obact = OBACT(view_layer);
1313         const enum eContextObjectMode mode = CTX_data_mode_enum_ex(
1314                 DST.draw_ctx.object_edit, obact, DST.draw_ctx.object_mode);
1315         View3D *v3d = DST.draw_ctx.v3d;
1316         const int drawtype = v3d->shading.type;
1317         const bool use_xray = XRAY_ENABLED(v3d);
1318
1319         drw_engines_enable_from_engine(engine_type, drawtype, use_xray);
1320         /* grease pencil */
1321         use_drw_engine(&draw_engine_gpencil_type);
1322
1323         if (DRW_state_draw_support()) {
1324                 /* Draw paint modes first so that they are drawn below the wireframes. */
1325                 drw_engines_enable_from_paint_mode(mode);
1326                 drw_engines_enable_from_overlays(v3d->overlay.flag);
1327                 drw_engines_enable_from_object_mode();
1328                 drw_engines_enable_from_mode(mode);
1329         }
1330         else {
1331                 /* Force enable overlays engine for wireframe mode */
1332                 if (v3d->shading.type == OB_WIRE) {
1333                         drw_engines_enable_from_overlays(v3d->overlay.flag);
1334                 }
1335         }
1336 }
1337
1338 static void drw_engines_disable(void)
1339 {
1340         BLI_freelistN(&DST.enabled_engines);
1341 }
1342
1343 static uint DRW_engines_get_hash(void)
1344 {
1345         uint hash = 0;
1346         /* The cache depends on enabled engines */
1347         /* FIXME : if collision occurs ... segfault */
1348         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1349                 DrawEngineType *engine = link->data;
1350                 hash += BLI_ghashutil_strhash_p(engine->idname);
1351         }
1352
1353         return hash;
1354 }
1355
1356 /* -------------------------------------------------------------------- */
1357 /** \name View Update
1358  * \{ */
1359
1360 void DRW_notify_view_update(const DRWUpdateContext *update_ctx)
1361 {
1362         RenderEngineType *engine_type = update_ctx->engine_type;
1363         ARegion *ar = update_ctx->ar;
1364         View3D *v3d = update_ctx->v3d;
1365         RegionView3D *rv3d = ar->regiondata;
1366         Depsgraph *depsgraph = update_ctx->depsgraph;
1367         Scene *scene = update_ctx->scene;
1368         ViewLayer *view_layer = update_ctx->view_layer;
1369
1370         /* Separate update for each stereo view. */
1371         for (int view = 0; view < 2; view++) {
1372                 GPUViewport *viewport = WM_draw_region_get_viewport(ar, view);
1373                 if (!viewport) {
1374                         continue;
1375                 }
1376
1377                 /* XXX Really nasty locking. But else this could
1378                  * be executed by the material previews thread
1379                  * while rendering a viewport. */
1380                 BLI_ticket_mutex_lock(DST.gl_context_mutex);
1381
1382                 /* Reset before using it. */
1383                 drw_state_prepare_clean_for_draw(&DST);
1384
1385                 DST.viewport = viewport;
1386                 DST.draw_ctx = (DRWContextState){
1387                         .ar = ar, .rv3d = rv3d, .v3d = v3d,
1388                         .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
1389                         .engine_type = engine_type,
1390                         .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
1391                 };
1392
1393                 drw_engines_enable(view_layer, engine_type);
1394
1395                 for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1396                         DrawEngineType *draw_engine = link->data;
1397                         ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine);
1398
1399                         if (draw_engine->view_update) {
1400                                 draw_engine->view_update(data);
1401                         }
1402                 }
1403
1404                 DST.viewport = NULL;
1405
1406                 drw_engines_disable();
1407
1408                 BLI_ticket_mutex_unlock(DST.gl_context_mutex);
1409         }
1410 }
1411
1412 /** \} */
1413
1414 /* -------------------------------------------------------------------- */
1415 /** \name Main Draw Loops (DRW_draw)
1416  * \{ */
1417
1418 /* Everything starts here.
1419  * This function takes care of calling all cache and rendering functions
1420  * for each relevant engine / mode engine. */
1421 void DRW_draw_view(const bContext *C)
1422 {
1423         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1424         ARegion *ar = CTX_wm_region(C);
1425         View3D *v3d = CTX_wm_view3d(C);
1426         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1427         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->shading.type);
1428         GPUViewport *viewport = WM_draw_region_get_bound_viewport(ar);
1429
1430         /* Reset before using it. */
1431         drw_state_prepare_clean_for_draw(&DST);
1432         DST.options.draw_text = (
1433                 (v3d->flag2 & V3D_HIDE_OVERLAYS) == 0 &&
1434                 (v3d->overlay.flag & V3D_OVERLAY_HIDE_TEXT) != 0);
1435         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, C);
1436 }
1437
1438 /**
1439  * Used for both regular and off-screen drawing.
1440  * Need to reset DST before calling this function
1441  */
1442 void DRW_draw_render_loop_ex(
1443         struct Depsgraph *depsgraph,
1444         RenderEngineType *engine_type,
1445         ARegion *ar, View3D *v3d,
1446         GPUViewport *viewport,
1447         const bContext *evil_C)
1448 {
1449
1450         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1451         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1452         RegionView3D *rv3d = ar->regiondata;
1453         const bool do_annotations = (
1454                 ((v3d->flag2 & V3D_SHOW_ANNOTATION) != 0) &&
1455                 ((v3d->flag2 & V3D_HIDE_OVERLAYS) == 0));
1456         const bool do_camera_frame = !DST.options.is_image_render;
1457
1458         DST.draw_ctx.evil_C = evil_C;
1459         DST.viewport = viewport;
1460
1461         /* Setup viewport */
1462         GPU_viewport_engines_data_validate(DST.viewport, DRW_engines_get_hash());
1463
1464         DST.draw_ctx = (DRWContextState){
1465             .ar = ar, .rv3d = rv3d, .v3d = v3d,
1466             .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
1467             .engine_type = engine_type,
1468             .depsgraph = depsgraph,
1469
1470             /* reuse if caller sets */
1471             .evil_C = DST.draw_ctx.evil_C,
1472         };
1473         drw_context_state_init();
1474         drw_viewport_var_init();
1475
1476         /* Get list of enabled engines */
1477         drw_engines_enable(view_layer, engine_type);
1478
1479         /* Update ubos */
1480         DRW_globals_update();
1481
1482         drw_debug_init();
1483         DRW_hair_init();
1484
1485         /* No framebuffer allowed before drawing. */
1486         BLI_assert(GPU_framebuffer_active_get() == NULL);
1487
1488         /* Init engines */
1489         drw_engines_init();
1490
1491         /* Cache filling */
1492         {
1493                 PROFILE_START(stime);
1494                 drw_engines_cache_init();
1495                 drw_engines_world_update(scene);
1496
1497                 const int object_type_exclude_viewport = v3d->object_type_exclude_viewport;
1498                 DEG_OBJECT_ITER_BEGIN(depsgraph, ob,
1499                         DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
1500                         DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET |
1501                         DEG_ITER_OBJECT_FLAG_VISIBLE |
1502                         DEG_ITER_OBJECT_FLAG_DUPLI)
1503                 {
1504                         if ((object_type_exclude_viewport & (1 << ob->type)) != 0) {
1505                                 continue;
1506                         }
1507                         if (v3d->localvd && ((v3d->local_view_uuid & ob->base_local_view_bits) == 0)) {
1508                                 continue;
1509                         }
1510                         DST.dupli_parent = data_.dupli_parent;
1511                         DST.dupli_source = data_.dupli_object_current;
1512                         drw_engines_cache_populate(ob);
1513                 }
1514                 DEG_OBJECT_ITER_END;
1515
1516                 drw_engines_cache_finish();
1517
1518                 DRW_render_instance_buffer_finish();
1519
1520 #ifdef USE_PROFILE
1521                 double *cache_time = GPU_viewport_cache_time_get(DST.viewport);
1522                 PROFILE_END_UPDATE(*cache_time, stime);
1523 #endif
1524         }
1525
1526         DRW_stats_begin();
1527
1528         GPU_framebuffer_bind(DST.default_framebuffer);
1529
1530         /* Start Drawing */
1531         DRW_state_reset();
1532
1533         DRW_hair_update();
1534
1535         drw_engines_draw_background();
1536
1537         /* WIP, single image drawn over the camera view (replace) */
1538         bool do_bg_image = false;
1539         if (rv3d->persp == RV3D_CAMOB) {
1540                 Object *cam_ob = v3d->camera;
1541                 if (cam_ob && cam_ob->type == OB_CAMERA) {
1542                         Camera *cam = cam_ob->data;
1543                         if (!BLI_listbase_is_empty(&cam->bg_images)) {
1544                                 do_bg_image = true;
1545                         }
1546                 }
1547         }
1548
1549         GPU_framebuffer_bind(DST.default_framebuffer);
1550
1551         if (do_bg_image) {
1552                 ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, false, do_camera_frame);
1553         }
1554
1555         DRW_draw_callbacks_pre_scene();
1556         if (DST.draw_ctx.evil_C) {
1557                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_PRE_VIEW);
1558         }
1559
1560         drw_engines_draw_scene();
1561
1562 #ifdef __APPLE__
1563         /* Fix 3D view being "laggy" on macos. (See T56996) */
1564         GPU_flush();
1565 #endif
1566
1567         /* annotations - temporary drawing buffer (3d space) */
1568         /* XXX: Or should we use a proper draw/overlay engine for this case? */
1569         if (do_annotations) {
1570                 GPU_depth_test(false);
1571                 /* XXX: as scene->gpd is not copied for COW yet */
1572                 ED_annotation_draw_view3d(DEG_get_input_scene(depsgraph), depsgraph, v3d, ar, true);
1573                 GPU_depth_test(true);
1574         }
1575
1576         DRW_draw_callbacks_post_scene();
1577         if (DST.draw_ctx.evil_C) {
1578                 DRW_state_reset();
1579                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_POST_VIEW);
1580                 /* Callback can be nasty and do whatever they want with the state.
1581                  * Don't trust them! */
1582                 DRW_state_reset();
1583         }
1584
1585         DRW_state_reset();
1586
1587         drw_debug_draw();
1588
1589         GPU_depth_test(false);
1590         drw_engines_draw_text();
1591         GPU_depth_test(true);
1592
1593         if (DST.draw_ctx.evil_C) {
1594                 /* needed so gizmo isn't obscured */
1595                 if (((v3d->flag2 & V3D_HIDE_OVERLAYS) == 0) &&
1596                     ((v3d->gizmo_flag & V3D_GIZMO_HIDE) == 0))
1597                 {
1598                         glDisable(GL_DEPTH_TEST);
1599                         DRW_draw_gizmo_3d();
1600                 }
1601
1602                 DRW_draw_region_info();
1603
1604                 /* annotations - temporary drawing buffer (screenspace) */
1605                 /* XXX: Or should we use a proper draw/overlay engine for this case? */
1606                 if (((v3d->flag2 & V3D_HIDE_OVERLAYS) == 0) &&
1607                     (do_annotations))
1608                 {
1609                         GPU_depth_test(false);
1610                         /* XXX: as scene->gpd is not copied for COW yet */
1611                         ED_annotation_draw_view3d(DEG_get_input_scene(depsgraph), depsgraph, v3d, ar, false);
1612                         GPU_depth_test(true);
1613                 }
1614
1615                 if ((v3d->flag2 & V3D_HIDE_OVERLAYS) == 0) {
1616                         /* Draw 2D after region info so we can draw on top of the camera passepartout overlay.
1617                          * 'DRW_draw_region_info' sets the projection in pixel-space. */
1618                         GPU_depth_test(false);
1619                         DRW_draw_gizmo_2d();
1620                         GPU_depth_test(true);
1621                 }
1622         }
1623
1624         DRW_stats_reset();
1625
1626         if (do_bg_image) {
1627                 ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, true, do_camera_frame);
1628         }
1629
1630         if (G.debug_value > 20 && G.debug_value < 30) {
1631                 GPU_depth_test(false);
1632                 rcti rect; /* local coordinate visible rect inside region, to accommodate overlapping ui */
1633                 ED_region_visible_rect(DST.draw_ctx.ar, &rect);
1634                 DRW_stats_draw(&rect);
1635                 GPU_depth_test(true);
1636         }
1637
1638         if (WM_draw_region_get_bound_viewport(ar)) {
1639                 /* Don't unbind the framebuffer yet in this case and let
1640                  * GPU_viewport_unbind do it, so that we can still do further
1641                  * drawing of action zones on top. */
1642         }
1643         else {
1644                 GPU_framebuffer_restore();
1645         }
1646
1647         DRW_state_reset();
1648         drw_engines_disable();
1649
1650         drw_viewport_cache_resize();
1651
1652 #ifdef DEBUG
1653         /* Avoid accidental reuse. */
1654         drw_state_ensure_not_reused(&DST);
1655 #endif
1656 }
1657
1658 void DRW_draw_render_loop(
1659         struct Depsgraph *depsgraph,
1660         ARegion *ar, View3D *v3d,
1661         GPUViewport *viewport)
1662 {
1663         /* Reset before using it. */
1664         drw_state_prepare_clean_for_draw(&DST);
1665
1666         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1667         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->shading.type);
1668
1669         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, NULL);
1670 }
1671
1672 /* @viewport CAN be NULL, in this case we create one. */
1673 void DRW_draw_render_loop_offscreen(
1674         struct Depsgraph *depsgraph, RenderEngineType *engine_type,
1675         ARegion *ar, View3D *v3d,
1676         const bool draw_background,
1677         const bool do_color_management,
1678         GPUOffScreen *ofs,
1679         GPUViewport *viewport)
1680 {
1681         /* Create temporary viewport if needed. */
1682         GPUViewport *render_viewport = viewport;
1683         if (viewport == NULL) {
1684                 render_viewport = GPU_viewport_create_from_offscreen(ofs);
1685         }
1686
1687         GPU_framebuffer_restore();
1688
1689         /* Reset before using it. */
1690         drw_state_prepare_clean_for_draw(&DST);
1691         /* WATCH: Force color management to output CManaged byte buffer by
1692          * forcing is_image_render to false. */
1693         DST.options.is_image_render = !do_color_management;
1694         DST.options.draw_background = draw_background;
1695         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, render_viewport, NULL);
1696
1697         /* Free temporary viewport. */
1698         if (viewport == NULL) {
1699                 /* don't free data owned by 'ofs' */
1700                 GPU_viewport_clear_from_offscreen(render_viewport);
1701                 GPU_viewport_free(render_viewport);
1702         }
1703
1704         /* we need to re-bind (annoying!) */
1705         GPU_offscreen_bind(ofs, false);
1706 }
1707
1708 /* Helper to check if exit object type to render. */
1709 bool DRW_render_check_grease_pencil(Depsgraph *depsgraph)
1710 {
1711         DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob)
1712         {
1713                 if (ob->type == OB_GPENCIL) {
1714                         if (DRW_object_visibility_in_active_context(ob) & OB_VISIBLE_SELF) {
1715                                 return true;
1716                         }
1717                 }
1718         }
1719         DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END
1720
1721         return false;
1722 }
1723
1724 static void DRW_render_gpencil_to_image(RenderEngine *engine, struct RenderLayer *render_layer, const rcti *rect)
1725 {
1726         if (draw_engine_gpencil_type.render_to_image) {
1727                 ViewportEngineData *gpdata = drw_viewport_engine_data_ensure(&draw_engine_gpencil_type);
1728                 draw_engine_gpencil_type.render_to_image(gpdata, engine, render_layer, rect);
1729         }
1730 }
1731
1732 void DRW_render_gpencil(struct RenderEngine *engine, struct Depsgraph *depsgraph)
1733 {
1734         /* This function is only valid for Cycles
1735          * Eevee done all work in the Eevee render directly.
1736          * Maybe it can be done equal for both engines?
1737          */
1738         if (STREQ(engine->type->name, "Eevee")) {
1739                 return;
1740         }
1741
1742         /* Early out if there are no grease pencil objects, especially important
1743          * to avoid failing in in background renders without OpenGL context. */
1744         if (!DRW_render_check_grease_pencil(depsgraph)) {
1745                 return;
1746         }
1747
1748         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1749         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1750         RenderEngineType *engine_type = engine->type;
1751         RenderData *r = &scene->r;
1752         Render *render = engine->re;
1753         /* Changing Context */
1754         if (G.background && DST.gl_context == NULL) {
1755                 WM_init_opengl(G_MAIN);
1756         }
1757
1758         void *re_gl_context = RE_gl_context_get(render);
1759         void *re_gpu_context = NULL;
1760
1761         /* Changing Context */
1762         if (re_gl_context != NULL) {
1763                 DRW_opengl_render_context_enable(re_gl_context);
1764                 /* We need to query gpu context after a gl context has been bound. */
1765                 re_gpu_context = RE_gpu_context_get(render);
1766                 DRW_gawain_render_context_enable(re_gpu_context);
1767         }
1768         else {
1769                 DRW_opengl_context_enable();
1770         }
1771
1772         /* Reset before using it. */
1773         drw_state_prepare_clean_for_draw(&DST);
1774         DST.options.is_image_render = true;
1775         DST.options.is_scene_render = true;
1776         DST.options.draw_background = scene->r.alphamode == R_ADDSKY;
1777         DST.buffer_finish_called = true;
1778
1779         DST.draw_ctx = (DRWContextState) {
1780                 .scene = scene, .view_layer = view_layer,
1781                 .engine_type = engine_type,
1782                 .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
1783         };
1784         drw_context_state_init();
1785
1786         DST.viewport = GPU_viewport_create();
1787         const int size[2] = { (r->size * r->xsch) / 100, (r->size * r->ysch) / 100 };
1788         GPU_viewport_size_set(DST.viewport, size);
1789
1790         drw_viewport_var_init();
1791
1792         /* Main rendering. */
1793         rctf view_rect;
1794         rcti render_rect;
1795         RE_GetViewPlane(render, &view_rect, &render_rect);
1796         if (BLI_rcti_is_empty(&render_rect)) {
1797                 BLI_rcti_init(&render_rect, 0, size[0], 0, size[1]);
1798         }
1799
1800         RenderResult *render_result = RE_engine_get_result(engine);
1801         RenderLayer *render_layer = render_result->layers.first;
1802
1803         DRW_render_gpencil_to_image(engine, render_layer, &render_rect);
1804
1805         /* Force cache to reset. */
1806         drw_viewport_cache_resize();
1807         GPU_viewport_free(DST.viewport);
1808         DRW_state_reset();
1809
1810         glDisable(GL_DEPTH_TEST);
1811
1812         /* Restore Drawing area. */
1813         GPU_framebuffer_restore();
1814
1815         /* Changing Context */
1816         /* GPXX Review this context */
1817         DRW_opengl_context_disable();
1818
1819         DST.buffer_finish_called = false;
1820 }
1821
1822 void DRW_render_to_image(RenderEngine *engine, struct Depsgraph *depsgraph)
1823 {
1824         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1825         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1826         RenderEngineType *engine_type = engine->type;
1827         DrawEngineType *draw_engine_type = engine_type->draw_engine;
1828         Render *render = engine->re;
1829
1830         if (G.background && DST.gl_context == NULL) {
1831                 WM_init_opengl(G_MAIN);
1832         }
1833
1834         void *re_gl_context = RE_gl_context_get(render);
1835         void *re_gpu_context = NULL;
1836
1837         /* Changing Context */
1838         if (re_gl_context != NULL) {
1839                 DRW_opengl_render_context_enable(re_gl_context);
1840                 /* We need to query gpu context after a gl context has been bound. */
1841                 re_gpu_context = RE_gpu_context_get(render);
1842                 DRW_gawain_render_context_enable(re_gpu_context);
1843         }
1844         else {
1845                 DRW_opengl_context_enable();
1846         }
1847
1848         /* IMPORTANT: We dont support immediate mode in render mode!
1849          * This shall remain in effect until immediate mode supports
1850          * multiple threads. */
1851
1852         /* Reset before using it. */
1853         drw_state_prepare_clean_for_draw(&DST);
1854         DST.options.is_image_render = true;
1855         DST.options.is_scene_render = true;
1856         DST.options.draw_background = scene->r.alphamode == R_ADDSKY;
1857
1858         DST.draw_ctx = (DRWContextState){
1859             .scene = scene, .view_layer = view_layer,
1860             .engine_type = engine_type,
1861             .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
1862         };
1863         drw_context_state_init();
1864
1865         DST.viewport = GPU_viewport_create();
1866         const int size[2] = {engine->resolution_x, engine->resolution_y};
1867         GPU_viewport_size_set(DST.viewport, size);
1868
1869         drw_viewport_var_init();
1870
1871         ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine_type);
1872
1873         /* set default viewport */
1874         glViewport(0, 0, size[0], size[1]);
1875
1876         /* Main rendering. */
1877         rctf view_rect;
1878         rcti render_rect;
1879         RE_GetViewPlane(render, &view_rect, &render_rect);
1880         if (BLI_rcti_is_empty(&render_rect)) {
1881                 BLI_rcti_init(&render_rect, 0, size[0], 0, size[1]);
1882         }
1883
1884         /* Reset state before drawing */
1885         DRW_state_reset();
1886
1887         /* Init render result. */
1888         RenderResult *render_result = RE_engine_begin_result(
1889                 engine,
1890                 0,
1891                 0,
1892                 (int)size[0],
1893                 (int)size[1],
1894                 view_layer->name,
1895                 /* RR_ALL_VIEWS */ NULL);
1896
1897         RenderLayer *render_layer = render_result->layers.first;
1898         for (RenderView *render_view = render_result->views.first;
1899              render_view != NULL;
1900              render_view = render_view->next)
1901         {
1902                 RE_SetActiveRenderView(render, render_view->name);
1903                 engine_type->draw_engine->render_to_image(data, engine, render_layer, &render_rect);
1904                 /* grease pencil: render result is merged in the previous render result. */
1905                 if (DRW_render_check_grease_pencil(depsgraph)) {
1906                         DRW_state_reset();
1907                         DRW_render_gpencil_to_image(engine, render_layer, &render_rect);
1908                 }
1909                 DST.buffer_finish_called = false;
1910         }
1911
1912         RE_engine_end_result(engine, render_result, false, false, false);
1913
1914         /* Force cache to reset. */
1915         drw_viewport_cache_resize();
1916
1917         GPU_viewport_free(DST.viewport);
1918         GPU_framebuffer_restore();
1919
1920 #ifdef DEBUG
1921         /* Avoid accidental reuse. */
1922         drw_state_ensure_not_reused(&DST);
1923 #endif
1924
1925         /* Reset state after drawing */
1926         DRW_state_reset();
1927
1928         /* Changing Context */
1929         if (re_gl_context != NULL) {
1930                 DRW_gawain_render_context_disable(re_gpu_context);
1931                 DRW_opengl_render_context_disable(re_gl_context);
1932         }
1933         else {
1934                 DRW_opengl_context_disable();
1935         }
1936 }
1937
1938 void DRW_render_object_iter(
1939         void *vedata, RenderEngine *engine, struct Depsgraph *depsgraph,
1940         void (*callback)(void *vedata, Object *ob, RenderEngine *engine, struct Depsgraph *depsgraph))
1941 {
1942         const DRWContextState *draw_ctx = DRW_context_state_get();
1943
1944         DRW_hair_init();
1945
1946         const int object_type_exclude_viewport = draw_ctx->v3d ? draw_ctx->v3d->object_type_exclude_viewport : 0;
1947         DEG_OBJECT_ITER_BEGIN(depsgraph, ob,
1948                 DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
1949                 DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET |
1950                 DEG_ITER_OBJECT_FLAG_VISIBLE |
1951                 DEG_ITER_OBJECT_FLAG_DUPLI)
1952         {
1953                 if ((object_type_exclude_viewport & (1 << ob->type)) == 0) {
1954                         DST.dupli_parent = data_.dupli_parent;
1955                         DST.dupli_source = data_.dupli_object_current;
1956                         DST.ob_state = NULL;
1957                         callback(vedata, ob, engine, depsgraph);
1958
1959                         drw_batch_cache_generate_requested(ob);
1960                 }
1961         }
1962         DEG_OBJECT_ITER_END
1963 }
1964
1965 /* Assume a valid gl context is bound (and that the gl_context_mutex has been acquired).
1966  * This function only setup DST and execute the given function.
1967  * Warning: similar to DRW_render_to_image you cannot use default lists (dfbl & dtxl). */
1968 void DRW_custom_pipeline(
1969         DrawEngineType *draw_engine_type,
1970         struct Depsgraph *depsgraph,
1971         void (*callback)(void *vedata, void *user_data),
1972         void *user_data)
1973 {
1974         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1975         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1976
1977         /* Reset before using it. */
1978         drw_state_prepare_clean_for_draw(&DST);
1979         DST.options.is_image_render = true;
1980         DST.options.is_scene_render = true;
1981         DST.options.draw_background = false;
1982
1983         DST.draw_ctx = (DRWContextState){
1984             .scene = scene,
1985             .view_layer = view_layer,
1986             .engine_type = NULL,
1987             .depsgraph = depsgraph,
1988             .object_mode = OB_MODE_OBJECT,
1989         };
1990         drw_context_state_init();
1991
1992         DST.viewport = GPU_viewport_create();
1993         const int size[2] = {1, 1};
1994         GPU_viewport_size_set(DST.viewport, size);
1995
1996         drw_viewport_var_init();
1997
1998         DRW_hair_init();
1999
2000         ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine_type);
2001
2002         /* Execute the callback */
2003         callback(data, user_data);
2004         DST.buffer_finish_called = false;
2005
2006         GPU_viewport_free(DST.viewport);
2007         GPU_framebuffer_restore();
2008
2009         /* The use of custom pipeline in other thread using the same
2010          * resources as the main thread (viewport) may lead to data
2011          * races and undefined behavior on certain drivers. Using
2012          * GPU_finish to sync seems to fix the issue. (see T62997) */
2013         GPU_finish();
2014
2015 #ifdef DEBUG
2016         /* Avoid accidental reuse. */
2017         drw_state_ensure_not_reused(&DST);
2018 #endif
2019 }
2020
2021 static struct DRWSelectBuffer {
2022         struct GPUFrameBuffer *framebuffer_depth_only;
2023         struct GPUFrameBuffer *framebuffer_select_id;
2024         struct GPUTexture *texture_depth;
2025         struct GPUTexture *texture_u32;
2026 } g_select_buffer = {NULL};
2027
2028 static void draw_select_framebuffer_depth_only_setup(const int size[2])
2029 {
2030         if (g_select_buffer.framebuffer_depth_only == NULL) {
2031                 g_select_buffer.framebuffer_depth_only = GPU_framebuffer_create();
2032                 g_select_buffer.framebuffer_select_id = GPU_framebuffer_create();
2033         }
2034
2035         if ((g_select_buffer.texture_depth != NULL) &&
2036             ((GPU_texture_width(g_select_buffer.texture_depth) != size[0]) ||
2037              (GPU_texture_height(g_select_buffer.texture_depth) != size[1])))
2038         {
2039                 GPU_texture_free(g_select_buffer.texture_depth);
2040                 g_select_buffer.texture_depth = NULL;
2041         }
2042
2043         if (g_select_buffer.texture_depth == NULL) {
2044                 g_select_buffer.texture_depth = GPU_texture_create_2d(
2045                         size[0], size[1], GPU_DEPTH_COMPONENT24, NULL, NULL);
2046
2047                 GPU_framebuffer_texture_attach(
2048                         g_select_buffer.framebuffer_depth_only,
2049                         g_select_buffer.texture_depth, 0, 0);
2050
2051                 GPU_framebuffer_texture_attach(
2052                         g_select_buffer.framebuffer_select_id,
2053                         g_select_buffer.texture_depth, 0, 0);
2054
2055                 GPU_framebuffer_check_valid(
2056                         g_select_buffer.framebuffer_depth_only, NULL);
2057                 GPU_framebuffer_check_valid(
2058                         g_select_buffer.framebuffer_select_id, NULL);
2059         }
2060 }
2061
2062 static void draw_select_framebuffer_select_id_setup(const int size[2])
2063 {
2064         draw_select_framebuffer_depth_only_setup(size);
2065
2066         if ((g_select_buffer.texture_u32 != NULL) &&
2067             ((GPU_texture_width(g_select_buffer.texture_u32) != size[0]) ||
2068              (GPU_texture_height(g_select_buffer.texture_u32) != size[1])))
2069         {
2070                 GPU_texture_free(g_select_buffer.texture_u32);
2071                 g_select_buffer.texture_u32 = NULL;
2072         }
2073
2074         if (g_select_buffer.texture_u32 == NULL) {
2075                 g_select_buffer.texture_u32 = GPU_texture_create_2d(
2076                         size[0], size[1], GPU_R32UI, NULL, NULL);
2077
2078                 GPU_framebuffer_texture_attach(
2079                         g_select_buffer.framebuffer_select_id,
2080                         g_select_buffer.texture_u32, 0, 0);
2081
2082                 GPU_framebuffer_check_valid(
2083                         g_select_buffer.framebuffer_select_id, NULL);
2084         }
2085 }
2086
2087 /* Must run after all instance datas have been added. */
2088 void DRW_render_instance_buffer_finish(void)
2089 {
2090         BLI_assert(!DST.buffer_finish_called && "DRW_render_instance_buffer_finish called twice!");
2091         DST.buffer_finish_called = true;
2092         DRW_instance_buffer_finish(DST.idatalist);
2093 }
2094
2095 /**
2096  * object mode select-loop, see: ED_view3d_draw_select_loop (legacy drawing).
2097  */
2098 void DRW_draw_select_loop(
2099         struct Depsgraph *depsgraph,
2100         ARegion *ar, View3D *v3d,
2101         bool UNUSED(use_obedit_skip), bool draw_surface, bool UNUSED(use_nearest), const rcti *rect,
2102         DRW_SelectPassFn select_pass_fn, void *select_pass_user_data,
2103         DRW_ObjectFilterFn object_filter_fn, void *object_filter_user_data)
2104 {
2105         Scene *scene = DEG_get_evaluated_scene(depsgraph);
2106         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->shading.type);
2107         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
2108         Object *obact = OBACT(view_layer);
2109         Object *obedit = OBEDIT_FROM_OBACT(obact);
2110 #ifndef USE_GPU_SELECT
2111         UNUSED_VARS(vc, scene, view_layer, v3d, ar, rect);
2112 #else
2113         RegionView3D *rv3d = ar->regiondata;
2114
2115         /* Reset before using it. */
2116         drw_state_prepare_clean_for_draw(&DST);
2117
2118         bool use_obedit = false;
2119         int obedit_mode = 0;
2120         if (obedit != NULL) {
2121                 if (obedit->type == OB_MBALL) {
2122                         use_obedit = true;
2123                         obedit_mode = CTX_MODE_EDIT_METABALL;
2124                 }
2125                 else if (obedit->type == OB_ARMATURE) {
2126                         use_obedit = true;
2127                         obedit_mode = CTX_MODE_EDIT_ARMATURE;
2128                 }
2129         }
2130         if (v3d->overlay.flag & V3D_OVERLAY_BONE_SELECT) {
2131                 if (!(v3d->flag2 & V3D_HIDE_OVERLAYS)) {
2132                         /* Note: don't use "BKE_object_pose_armature_get" here, it breaks selection. */
2133                         Object *obpose = OBPOSE_FROM_OBACT(obact);
2134                         if (obpose) {
2135                                 use_obedit = true;
2136                                 obedit_mode = CTX_MODE_POSE;
2137                         }
2138                 }
2139         }
2140
2141         int viewport_size[2] = {BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)};
2142         struct GPUViewport *viewport = GPU_viewport_create();
2143         GPU_viewport_size_set(viewport, viewport_size);
2144
2145         DST.viewport = viewport;
2146         DST.options.is_select = true;
2147
2148         /* Get list of enabled engines */
2149         if (use_obedit) {
2150                 drw_engines_enable_from_paint_mode(obedit_mode);
2151                 drw_engines_enable_from_mode(obedit_mode);
2152         }
2153         else if (!draw_surface) {
2154                 /* grease pencil selection */
2155                 use_drw_engine(&draw_engine_gpencil_type);
2156
2157                 drw_engines_enable_from_overlays(v3d->overlay.flag);
2158                 drw_engines_enable_from_object_mode();
2159         }
2160         else {
2161                 drw_engines_enable_basic();
2162                 /* grease pencil selection */
2163                 use_drw_engine(&draw_engine_gpencil_type);
2164
2165                 drw_engines_enable_from_overlays(v3d->overlay.flag);
2166                 drw_engines_enable_from_object_mode();
2167         }
2168
2169         /* Setup viewport */
2170
2171         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
2172         DST.draw_ctx = (DRWContextState){
2173                 .ar = ar, .rv3d = rv3d, .v3d = v3d,
2174                 .scene = scene, .view_layer = view_layer, .obact = obact,
2175                 .engine_type = engine_type,
2176                 .depsgraph = depsgraph,
2177         };
2178         drw_context_state_init();
2179         drw_viewport_var_init();
2180
2181         /* Update ubos */
2182         DRW_globals_update();
2183
2184         /* Init engines */
2185         drw_engines_init();
2186         DRW_hair_init();
2187
2188         {
2189                 drw_engines_cache_init();
2190                 drw_engines_world_update(scene);
2191
2192                 if (use_obedit) {
2193 #if 0
2194                         drw_engines_cache_populate(obact);
2195 #else
2196                         FOREACH_OBJECT_IN_MODE_BEGIN (view_layer, v3d, obact->type, obact->mode, ob_iter) {
2197                                 drw_engines_cache_populate(ob_iter);
2198                         }
2199                         FOREACH_OBJECT_IN_MODE_END;
2200 #endif
2201                 }
2202                 else {
2203                         const int object_type_exclude_select = (
2204                                 v3d->object_type_exclude_viewport | v3d->object_type_exclude_select
2205                         );
2206                         bool filter_exclude = false;
2207                         DEG_OBJECT_ITER_BEGIN(depsgraph, ob,
2208                                 DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
2209                                 DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET |
2210                                 DEG_ITER_OBJECT_FLAG_VISIBLE |
2211                                 DEG_ITER_OBJECT_FLAG_DUPLI)
2212                         {
2213                                 if (v3d->localvd && ((v3d->local_view_uuid & ob->base_local_view_bits) == 0)) {
2214                                         continue;
2215                                 }
2216
2217                                 if ((ob->base_flag & BASE_SELECTABLE) &&
2218                                     (object_type_exclude_select & (1 << ob->type)) == 0)
2219                                 {
2220                                         if (object_filter_fn != NULL) {
2221                                                 if (ob->base_flag & BASE_FROM_DUPLI) {
2222                                                         /* pass (use previous filter_exclude value) */
2223                                                 }
2224                                                 else {
2225                                                         filter_exclude = (object_filter_fn(ob, object_filter_user_data) == false);
2226                                                 }
2227                                                 if (filter_exclude) {
2228                                                         continue;
2229                                                 }
2230                                         }
2231
2232                                         /* This relies on dupli instances being after their instancing object. */
2233                                         if ((ob->base_flag & BASE_FROM_DUPLI) == 0) {
2234                                                 Object *ob_orig = DEG_get_original_object(ob);
2235                                                 DRW_select_load_id(ob_orig->select_id);
2236                                         }
2237                                         DST.dupli_parent = data_.dupli_parent;
2238                                         DST.dupli_source = data_.dupli_object_current;
2239                                         drw_engines_cache_populate(ob);
2240                                 }
2241                         }
2242                         DEG_OBJECT_ITER_END;
2243                 }
2244
2245                 drw_engines_cache_finish();
2246
2247                 DRW_render_instance_buffer_finish();
2248         }
2249
2250         /* Setup framebuffer */
2251         draw_select_framebuffer_depth_only_setup(viewport_size);
2252         GPU_framebuffer_bind(g_select_buffer.framebuffer_depth_only);
2253         GPU_framebuffer_clear_depth(g_select_buffer.framebuffer_depth_only, 1.0f);
2254
2255         /* Start Drawing */
2256         DRW_state_reset();
2257         DRW_draw_callbacks_pre_scene();
2258
2259         DRW_hair_update();
2260
2261         DRW_state_lock(
2262                 DRW_STATE_WRITE_DEPTH |
2263                 DRW_STATE_DEPTH_ALWAYS |
2264                 DRW_STATE_DEPTH_LESS_EQUAL |
2265                 DRW_STATE_DEPTH_EQUAL |
2266                 DRW_STATE_DEPTH_GREATER |
2267                 DRW_STATE_DEPTH_ALWAYS);
2268
2269         /* Only 1-2 passes. */
2270         while (true) {
2271                 if (!select_pass_fn(DRW_SELECT_PASS_PRE, select_pass_user_data)) {
2272                         break;
2273                 }
2274
2275                 drw_engines_draw_scene();
2276
2277                 if (!select_pass_fn(DRW_SELECT_PASS_POST, select_pass_user_data)) {
2278                         break;
2279                 }
2280         }
2281
2282         DRW_state_lock(0);
2283
2284         DRW_draw_callbacks_post_scene();
2285
2286         DRW_state_reset();
2287         drw_engines_disable();
2288
2289 #ifdef DEBUG
2290         /* Avoid accidental reuse. */
2291         drw_state_ensure_not_reused(&DST);
2292 #endif
2293         GPU_framebuffer_restore();
2294
2295         /* Cleanup for selection state */
2296         GPU_viewport_free(viewport);
2297 #endif  /* USE_GPU_SELECT */
2298 }
2299
2300 static void draw_depth_texture_to_screen(GPUTexture *texture)
2301 {
2302         const float w = (float)GPU_texture_width(texture);
2303         const float h = (float)GPU_texture_height(texture);
2304
2305         GPUVertFormat *format = immVertexFormat();
2306         uint texcoord = GPU_vertformat_attr_add(format, "texCoord", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2307         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2308
2309         immBindBuiltinProgram(GPU_SHADER_3D_IMAGE_DEPTH_COPY);
2310
2311         GPU_texture_bind(texture, 0);
2312
2313         immUniform1i("image", 0); /* default GL_TEXTURE0 unit */
2314
2315         immBegin(GPU_PRIM_TRI_STRIP, 4);
2316
2317         immAttr2f(texcoord, 0.0f, 0.0f);
2318         immVertex2f(pos, 0.0f, 0.0f);
2319
2320         immAttr2f(texcoord, 1.0f, 0.0f);
2321         immVertex2f(pos, w, 0.0f);
2322
2323         immAttr2f(texcoord, 0.0f, 1.0f);
2324         immVertex2f(pos, 0.0f, h);
2325
2326         immAttr2f(texcoord, 1.0f, 1.0f);
2327         immVertex2f(pos, w, h);
2328
2329         immEnd();
2330
2331         GPU_texture_unbind(texture);
2332
2333         immUnbindProgram();
2334 }
2335
2336
2337 /**
2338  * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
2339  */
2340 static void drw_draw_depth_loop_imp(void)
2341 {
2342         DRW_opengl_context_enable();
2343
2344         /* Setup framebuffer */
2345         DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
2346         GPU_framebuffer_bind(fbl->depth_only_fb);
2347         GPU_framebuffer_clear_depth(fbl->depth_only_fb, 1.0f);
2348
2349         /* Setup viewport */
2350         drw_context_state_init();
2351         drw_viewport_var_init();
2352
2353         /* Update ubos */
2354         DRW_globals_update();
2355
2356         /* Init engines */
2357         drw_engines_init();
2358         DRW_hair_init();
2359
2360         {
2361                 drw_engines_cache_init();
2362                 drw_engines_world_update(DST.draw_ctx.scene);
2363
2364                 View3D *v3d = DST.draw_ctx.v3d;
2365                 const int object_type_exclude_viewport = v3d->object_type_exclude_viewport;
2366                 DEG_OBJECT_ITER_BEGIN(DST.draw_ctx.depsgraph, ob,
2367                         DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
2368                         DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET |
2369                         DEG_ITER_OBJECT_FLAG_VISIBLE |
2370                         DEG_ITER_OBJECT_FLAG_DUPLI)
2371                 {
2372                         if ((object_type_exclude_viewport & (1 << ob->type)) != 0) {
2373                                 continue;
2374                         }
2375
2376                         if (v3d->localvd && ((v3d->local_view_uuid & ob->base_local_view_bits) == 0)) {
2377                                 continue;
2378                         }
2379
2380                         DST.dupli_parent = data_.dupli_parent;
2381                         DST.dupli_source = data_.dupli_object_current;
2382                         drw_engines_cache_populate(ob);
2383                 }
2384                 DEG_OBJECT_ITER_END;
2385
2386                 drw_engines_cache_finish();
2387
2388                 DRW_render_instance_buffer_finish();
2389         }
2390
2391         /* Start Drawing */
2392         DRW_state_reset();
2393
2394         DRW_hair_update();
2395
2396         DRW_draw_callbacks_pre_scene();
2397         drw_engines_draw_scene();
2398         DRW_draw_callbacks_post_scene();
2399
2400         DRW_state_reset();
2401
2402         /* TODO: Reading depth for operators should be done here. */
2403
2404         GPU_framebuffer_restore();
2405
2406         /* Changin context */
2407         DRW_opengl_context_disable();
2408 }
2409
2410 /**
2411  * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
2412  */
2413 void DRW_draw_depth_loop(
2414         struct Depsgraph *depsgraph,
2415         ARegion *ar, View3D *v3d,
2416         GPUViewport *viewport)
2417 {
2418         Scene *scene = DEG_get_evaluated_scene(depsgraph);
2419         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->shading.type);
2420         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
2421         RegionView3D *rv3d = ar->regiondata;
2422
2423         /* Reset before using it. */
2424         drw_state_prepare_clean_for_draw(&DST);
2425
2426         DST.viewport = viewport;
2427         DST.options.is_depth = true;
2428
2429         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
2430         DST.draw_ctx = (DRWContextState){
2431                 .ar = ar, .rv3d = rv3d, .v3d = v3d,
2432                 .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
2433                 .engine_type = engine_type,
2434                 .depsgraph = depsgraph,
2435         };
2436
2437         /* Get list of enabled engines */
2438         {
2439                 drw_engines_enable_basic();
2440                 if (DRW_state_draw_support()) {
2441                         drw_engines_enable_from_object_mode();
2442                 }
2443         }
2444
2445         drw_draw_depth_loop_imp();
2446
2447         drw_engines_disable();
2448
2449         /* XXX Drawing the resulting buffer to the BACK_BUFFER */
2450         GPU_matrix_push();
2451         GPU_matrix_push_projection();
2452         wmOrtho2_region_pixelspace(DST.draw_ctx.ar);
2453         GPU_matrix_identity_set();
2454
2455         glEnable(GL_DEPTH_TEST); /* Cannot write to depth buffer without testing */
2456         glDepthFunc(GL_ALWAYS);
2457         DefaultTextureList *dtxl = (DefaultTextureList *)GPU_viewport_texture_list_get(DST.viewport);
2458         draw_depth_texture_to_screen(dtxl->depth);
2459         glDepthFunc(GL_LEQUAL);
2460
2461         GPU_matrix_pop();
2462         GPU_matrix_pop_projection();
2463
2464 #ifdef DEBUG
2465         /* Avoid accidental reuse. */
2466         drw_state_ensure_not_reused(&DST);
2467 #endif
2468 }
2469
2470 /**
2471  * Converted from ED_view3d_draw_depth_gpencil (legacy drawing).
2472  */
2473 void DRW_draw_depth_loop_gpencil(
2474         struct Depsgraph *depsgraph,
2475         ARegion *ar, View3D *v3d,
2476         GPUViewport *viewport)
2477 {
2478         Scene *scene = DEG_get_evaluated_scene(depsgraph);
2479         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
2480         RegionView3D *rv3d = ar->regiondata;
2481
2482         /* Reset before using it. */
2483         drw_state_prepare_clean_for_draw(&DST);
2484
2485         DST.viewport = viewport;
2486         DST.options.is_depth = true;
2487
2488         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
2489         DST.draw_ctx = (DRWContextState){
2490                 .ar = ar, .rv3d = rv3d, .v3d = v3d,
2491                 .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
2492                 .depsgraph = depsgraph,
2493         };
2494
2495         use_drw_engine(&draw_engine_gpencil_type);
2496         drw_draw_depth_loop_imp();
2497         drw_engines_disable();
2498
2499 #ifdef DEBUG
2500         /* Avoid accidental reuse. */
2501         drw_state_ensure_not_reused(&DST);
2502 #endif
2503 }
2504
2505
2506 /* Set an opengl context to be used with shaders that draw on U32 colors. */
2507 void DRW_framebuffer_select_id_setup(ARegion *ar, const bool clear)
2508 {
2509         RegionView3D *rv3d = ar->regiondata;
2510
2511         DRW_opengl_context_enable();
2512
2513         /* Setup framebuffer */
2514         int viewport_size[2] = {ar->winx, ar->winy};
2515         draw_select_framebuffer_select_id_setup(viewport_size);
2516         GPU_framebuffer_bind(g_select_buffer.framebuffer_select_id);
2517
2518         /* dithering and AA break color coding, so disable */
2519         glDisable(GL_DITHER);
2520
2521         GPU_depth_test(true);
2522         glDisable(GL_SCISSOR_TEST);
2523
2524         if (clear) {
2525                 GPU_framebuffer_clear_color_depth(
2526                         g_select_buffer.framebuffer_select_id, (const float[4]){0.0f}, 1.0f);
2527         }
2528
2529         if (rv3d->rflag & RV3D_CLIPPING) {
2530                 ED_view3d_clipping_set(rv3d);
2531         }
2532 }
2533
2534
2535 /* Ends the context for selection and restoring the previous one. */
2536 void DRW_framebuffer_select_id_release(ARegion *ar)
2537 {
2538         RegionView3D *rv3d = ar->regiondata;
2539
2540         if (rv3d->rflag & RV3D_CLIPPING) {
2541                 ED_view3d_clipping_disable();
2542         }
2543
2544         GPU_depth_test(false);
2545
2546         GPU_framebuffer_restore();
2547
2548         DRW_opengl_context_disable();
2549 }
2550
2551
2552 /* Read a block of pixels from the select frame buffer. */
2553 void DRW_framebuffer_select_id_read(const rcti *rect, uint *r_buf)
2554 {
2555         /* clamp rect by texture */
2556         rcti r = {
2557                 .xmin = 0,
2558                 .xmax = GPU_texture_width(g_select_buffer.texture_u32),
2559                 .ymin = 0,
2560                 .ymax = GPU_texture_height(g_select_buffer.texture_u32),
2561         };
2562
2563         rcti rect_clamp = *rect;
2564         BLI_rcti_isect(&r, rect, &rect_clamp);
2565
2566         GPU_texture_read_rect(
2567                 g_select_buffer.texture_u32, GPU_DATA_UNSIGNED_INT, &rect_clamp, r_buf);
2568
2569         if (!BLI_rcti_compare(rect, &rect_clamp)) {
2570                 GPU_select_buffer_stride_realign(rect, &rect_clamp, r_buf);
2571         }
2572 }
2573
2574 /** \} */
2575
2576
2577 /* -------------------------------------------------------------------- */
2578 /** \name Draw Manager State (DRW_state)
2579  * \{ */
2580
2581 void DRW_state_dfdy_factors_get(float dfdyfac[2])
2582 {
2583         GPU_get_dfdy_factors(dfdyfac);
2584 }
2585
2586 /**
2587  * When false, drawing doesn't output to a pixel buffer
2588  * eg: Occlusion queries, or when we have setup a context to draw in already.
2589  */
2590 bool DRW_state_is_fbo(void)
2591 {
2592         return ((DST.default_framebuffer != NULL) || DST.options.is_image_render);
2593 }
2594
2595 /**
2596  * For when engines need to know if this is drawing for selection or not.
2597  */
2598 bool DRW_state_is_select(void)
2599 {
2600         return DST.options.is_select;
2601 }
2602
2603 bool DRW_state_is_depth(void)
2604 {
2605         return DST.options.is_depth;
2606 }
2607
2608 /**
2609  * Whether we are rendering for an image
2610  */
2611 bool DRW_state_is_image_render(void)
2612 {
2613         return DST.options.is_image_render;
2614 }
2615
2616 /**
2617  * Whether we are rendering only the render engine,
2618  * or if we should also render the mode engines.
2619  */
2620 bool DRW_state_is_scene_render(void)
2621 {
2622         BLI_assert(DST.options.is_scene_render ?
2623                    DST.options.is_image_render : true);
2624         return DST.options.is_scene_render;
2625 }
2626
2627 /**
2628  * Whether we are rendering simple opengl render
2629  */
2630 bool DRW_state_is_opengl_render(void)
2631 {
2632         return DST.options.is_image_render && !DST.options.is_scene_render;
2633 }
2634
2635 bool DRW_state_is_playback(void)
2636 {
2637         if (DST.draw_ctx.evil_C != NULL) {
2638                 struct wmWindowManager *wm = CTX_wm_manager(DST.draw_ctx.evil_C);
2639                 return ED_screen_animation_playing(wm) != NULL;
2640         }
2641         return false;
2642 }
2643
2644
2645 /**
2646  * Should text draw in this mode?
2647  */
2648 bool DRW_state_show_text(void)
2649 {
2650         return (DST.options.is_select) == 0 &&
2651                (DST.options.is_depth) == 0 &&
2652                (DST.options.is_scene_render) == 0 &&
2653                (DST.options.draw_text) == 0;
2654 }
2655
2656 /**
2657  * Should draw support elements
2658  * Objects center, selection outline, probe data, ...
2659  */
2660 bool DRW_state_draw_support(void)
2661 {
2662         View3D *v3d = DST.draw_ctx.v3d;
2663         return (DRW_state_is_scene_render() == false) &&
2664                 (v3d != NULL) &&
2665                 ((v3d->flag2 & V3D_HIDE_OVERLAYS) == 0);
2666 }
2667
2668 /**
2669  * Whether we should render the background
2670  */
2671 bool DRW_state_draw_background(void)
2672 {
2673         if (DRW_state_is_image_render() == false) {
2674                 return true;
2675         }
2676         return DST.options.draw_background;
2677 }
2678
2679 /** \} */
2680
2681
2682 /* -------------------------------------------------------------------- */
2683 /** \name Context State (DRW_context_state)
2684  * \{ */
2685
2686 const DRWContextState *DRW_context_state_get(void)
2687 {
2688         return &DST.draw_ctx;
2689 }
2690
2691 /** \} */
2692
2693
2694 /* -------------------------------------------------------------------- */
2695 /** \name Init/Exit (DRW_engines)
2696  * \{ */
2697
2698 bool DRW_engine_render_support(DrawEngineType *draw_engine_type)
2699 {
2700         return draw_engine_type->render_to_image;
2701 }
2702
2703 void DRW_engine_register(DrawEngineType *draw_engine_type)
2704 {
2705         BLI_addtail(&DRW_engines, draw_engine_type);
2706 }
2707
2708 void DRW_engines_register(void)
2709 {
2710         RE_engines_register(&DRW_engine_viewport_eevee_type);
2711         RE_engines_register(&DRW_engine_viewport_workbench_type);
2712
2713         DRW_engine_register(&draw_engine_workbench_solid);
2714         DRW_engine_register(&draw_engine_workbench_transparent);
2715
2716         DRW_engine_register(&draw_engine_object_type);
2717         DRW_engine_register(&draw_engine_edit_armature_type);
2718         DRW_engine_register(&draw_engine_edit_curve_type);
2719         DRW_engine_register(&draw_engine_edit_lattice_type);
2720         DRW_engine_register(&draw_engine_edit_mesh_type);
2721         DRW_engine_register(&draw_engine_edit_metaball_type);
2722         DRW_engine_register(&draw_engine_edit_text_type);
2723         DRW_engine_register(&draw_engine_motion_path_type);
2724         DRW_engine_register(&draw_engine_overlay_type);
2725         DRW_engine_register(&draw_engine_paint_texture_type);
2726         DRW_engine_register(&draw_engine_paint_vertex_type);
2727         DRW_engine_register(&draw_engine_particle_type);
2728         DRW_engine_register(&draw_engine_pose_type);
2729         DRW_engine_register(&draw_engine_sculpt_type);
2730         DRW_engine_register(&draw_engine_gpencil_type);
2731
2732         /* setup callbacks */
2733         {
2734                 BKE_mball_batch_cache_dirty_tag_cb = DRW_mball_batch_cache_dirty_tag;
2735                 BKE_mball_batch_cache_free_cb = DRW_mball_batch_cache_free;
2736
2737                 BKE_curve_batch_cache_dirty_tag_cb = DRW_curve_batch_cache_dirty_tag;
2738                 BKE_curve_batch_cache_free_cb = DRW_curve_batch_cache_free;
2739
2740                 BKE_mesh_batch_cache_dirty_tag_cb = DRW_mesh_batch_cache_dirty_tag;
2741                 BKE_mesh_batch_cache_free_cb = DRW_mesh_batch_cache_free;
2742
2743                 BKE_lattice_batch_cache_dirty_tag_cb = DRW_lattice_batch_cache_dirty_tag;
2744                 BKE_lattice_batch_cache_free_cb = DRW_lattice_batch_cache_free;
2745
2746                 BKE_particle_batch_cache_dirty_tag_cb = DRW_particle_batch_cache_dirty_tag;
2747                 BKE_particle_batch_cache_free_cb = DRW_particle_batch_cache_free;
2748
2749                 BKE_gpencil_batch_cache_dirty_tag_cb = DRW_gpencil_batch_cache_dirty_tag;
2750                 BKE_gpencil_batch_cache_free_cb = DRW_gpencil_batch_cache_free;
2751         }
2752 }
2753
2754 void DRW_engines_free(void)
2755 {
2756         if (DST.gl_context == NULL) {
2757                 /* Nothing has been setup. Nothing to clear.
2758                  * Otherwise, DRW_opengl_context_enable can
2759                  * create a context in background mode. (see T62355) */
2760                 return;
2761         }
2762
2763         DRW_opengl_context_enable();
2764
2765         DRW_TEXTURE_FREE_SAFE(g_select_buffer.texture_u32);
2766         DRW_TEXTURE_FREE_SAFE(g_select_buffer.texture_depth);
2767         GPU_FRAMEBUFFER_FREE_SAFE(g_select_buffer.framebuffer_select_id);
2768         GPU_FRAMEBUFFER_FREE_SAFE(g_select_buffer.framebuffer_depth_only);
2769
2770         DRW_hair_free();
2771         DRW_shape_cache_free();
2772         DRW_stats_free();
2773         DRW_globals_free();
2774
2775         DrawEngineType *next;
2776         for (DrawEngineType *type = DRW_engines.first; type; type = next) {
2777                 next = type->next;
2778                 BLI_remlink(&R_engines, type);
2779
2780                 if (type->engine_free) {
2781                         type->engine_free();
2782                 }
2783         }
2784
2785         DRW_UBO_FREE_SAFE(G_draw.block_ubo);
2786         DRW_UBO_FREE_SAFE(G_draw.view_ubo);
2787         DRW_TEXTURE_FREE_SAFE(G_draw.ramp);
2788         DRW_TEXTURE_FREE_SAFE(G_draw.weight_ramp);
2789         MEM_SAFE_FREE(g_pos_format);
2790
2791         MEM_SAFE_FREE(DST.RST.bound_texs);
2792         MEM_SAFE_FREE(DST.RST.bound_tex_slots);
2793         MEM_SAFE_FREE(DST.RST.bound_ubos);
2794         MEM_SAFE_FREE(DST.RST.bound_ubo_slots);
2795
2796         MEM_SAFE_FREE(DST.uniform_names.buffer);
2797
2798         DRW_opengl_context_disable();
2799 }
2800
2801 /** \} */
2802
2803 /** \name Init/Exit (DRW_opengl_ctx)
2804  * \{ */
2805
2806 void DRW_opengl_context_create(void)
2807 {
2808         BLI_assert(DST.gl_context == NULL); /* Ensure it's called once */
2809
2810         DST.gl_context_mutex = BLI_ticket_mutex_alloc();
2811         if (!G.background) {
2812                 immDeactivate();
2813         }
2814         /* This changes the active context. */
2815         DST.gl_context = WM_opengl_context_create();
2816         WM_opengl_context_activate(DST.gl_context);
2817         /* Be sure to create gawain.context too. */
2818         DST.gpu_context = GPU_context_create();
2819         if (!G.background) {
2820                 immActivate();
2821         }
2822         /* Set default Blender OpenGL state */
2823         GPU_state_init();
2824         /* So we activate the window's one afterwards. */
2825         wm_window_reset_drawable();
2826 }
2827
2828 void DRW_opengl_context_destroy(void)
2829 {
2830         BLI_assert(BLI_thread_is_main());
2831         if (DST.gl_context != NULL) {
2832                 WM_opengl_context_activate(DST.gl_context);
2833                 GPU_context_active_set(DST.gpu_context);
2834                 GPU_context_discard(DST.gpu_context);
2835                 WM_opengl_context_dispose(DST.gl_context);
2836                 BLI_ticket_mutex_free(DST.gl_context_mutex);
2837         }
2838 }
2839
2840 void DRW_opengl_context_enable_ex(bool restore)
2841 {
2842         if (DST.gl_context != NULL) {
2843                 /* IMPORTANT: We dont support immediate mode in render mode!
2844                  * This shall remain in effect until immediate mode supports
2845                  * multiple threads. */
2846                 BLI_ticket_mutex_lock(DST.gl_context_mutex);
2847                 if (BLI_thread_is_main() && restore) {
2848                         if (!G.background) {
2849                                 immDeactivate();
2850                         }
2851                 }
2852                 WM_opengl_context_activate(DST.gl_context);
2853                 GPU_context_active_set(DST.gpu_context);
2854                 if (BLI_thread_is_main() && restore) {
2855                         if (!G.background) {
2856                                 immActivate();
2857                         }
2858                         BLF_batch_reset();
2859                 }
2860         }
2861 }
2862
2863 void DRW_opengl_context_disable_ex(bool restore)
2864 {
2865         if (DST.gl_context != NULL) {
2866 #ifdef __APPLE__
2867                 /* Need to flush before disabling draw context, otherwise it does not
2868                  * always finish drawing and viewport can be empty or partially drawn */
2869                 GPU_flush();
2870 #endif
2871
2872                 if (BLI_thread_is_main() && restore) {
2873                         wm_window_reset_drawable();
2874                 }
2875                 else {
2876                         WM_opengl_context_release(DST.gl_context);
2877                         GPU_context_active_set(NULL);
2878                 }
2879
2880                 BLI_ticket_mutex_unlock(DST.gl_context_mutex);
2881         }
2882 }
2883
2884 void DRW_opengl_context_enable(void)
2885 {
2886         if (G.background && DST.gl_context == NULL) {
2887                 WM_init_opengl(G_MAIN);
2888         }
2889         DRW_opengl_context_enable_ex(true);
2890 }
2891
2892 void DRW_opengl_context_disable(void)
2893 {
2894         DRW_opengl_context_disable_ex(true);
2895 }
2896
2897 void DRW_opengl_render_context_enable(void *re_gl_context)
2898 {
2899         /* If thread is main you should use DRW_opengl_context_enable(). */
2900         BLI_assert(!BLI_thread_is_main());
2901
2902         /* TODO get rid of the blocking. Only here because of the static global DST. */
2903         BLI_ticket_mutex_lock(DST.gl_context_mutex);
2904         WM_opengl_context_activate(re_gl_context);
2905 }
2906
2907 void DRW_opengl_render_context_disable(void *re_gl_context)
2908 {
2909         GPU_flush();
2910         WM_opengl_context_release(re_gl_context);
2911         /* TODO get rid of the blocking. */
2912         BLI_ticket_mutex_unlock(DST.gl_context_mutex);
2913 }
2914
2915 /* Needs to be called AFTER DRW_opengl_render_context_enable() */
2916 void DRW_gawain_render_context_enable(void *re_gpu_context)
2917 {
2918         /* If thread is main you should use DRW_opengl_context_enable(). */
2919         BLI_assert(!BLI_thread_is_main());
2920
2921         GPU_context_active_set(re_gpu_context);
2922         DRW_shape_cache_reset(); /* XXX fix that too. */
2923 }
2924
2925 /* Needs to be called BEFORE DRW_opengl_render_context_disable() */
2926 void DRW_gawain_render_context_disable(void *UNUSED(re_gpu_context))
2927 {
2928         DRW_shape_cache_reset(); /* XXX fix that too. */
2929         GPU_context_active_set(NULL);
2930 }
2931
2932 /** \} */