Fix object-dupli selection w/ COW
[blender.git] / source / blender / draw / intern / draw_manager.c
1 /*
2  * Copyright 2016, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file blender/draw/intern/draw_manager.c
23  *  \ingroup draw
24  */
25
26 #include <stdio.h>
27
28 #include "BLI_listbase.h"
29 #include "BLI_mempool.h"
30 #include "BLI_rect.h"
31 #include "BLI_string.h"
32 #include "BLI_threads.h"
33
34 #include "BLF_api.h"
35
36 #include "BKE_global.h"
37 #include "BKE_mesh.h"
38 #include "BKE_object.h"
39 #include "BKE_particle.h"
40 #include "BKE_pointcache.h"
41 #include "BKE_workspace.h"
42
43 #include "draw_manager.h"
44 #include "DNA_camera_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_meshdata_types.h"
47
48 #include "ED_space_api.h"
49 #include "ED_screen.h"
50 #include "ED_particle.h"
51 #include "ED_view3d.h"
52
53 #include "GPU_draw.h"
54 #include "GPU_extensions.h"
55 #include "GPU_framebuffer.h"
56 #include "GPU_immediate.h"
57 #include "GPU_uniformbuffer.h"
58 #include "GPU_viewport.h"
59 #include "GPU_matrix.h"
60
61 #include "IMB_colormanagement.h"
62
63 #include "RE_engine.h"
64 #include "RE_pipeline.h"
65
66 #include "UI_interface.h"
67 #include "UI_resources.h"
68
69 #include "WM_api.h"
70 #include "wm_window.h"
71
72 #include "draw_manager_text.h"
73 #include "draw_manager_profiling.h"
74
75 /* only for callbacks */
76 #include "draw_cache_impl.h"
77
78 #include "draw_mode_engines.h"
79 #include "engines/clay/clay_engine.h"
80 #include "engines/eevee/eevee_engine.h"
81 #include "engines/basic/basic_engine.h"
82 #include "engines/workbench/workbench_engine.h"
83 #include "engines/external/external_engine.h"
84
85 #include "../../../intern/gawain/gawain/gwn_context.h"
86
87 #include "DEG_depsgraph.h"
88 #include "DEG_depsgraph_query.h"
89
90 #ifdef USE_GPU_SELECT
91 #  include "GPU_select.h"
92 #endif
93
94 /** Render State: No persistent data between draw calls. */
95 DRWManager DST = {NULL};
96
97 ListBase DRW_engines = {NULL, NULL};
98
99 extern struct GPUUniformBuffer *view_ubo; /* draw_manager_exec.c */
100
101 static void drw_state_prepare_clean_for_draw(DRWManager *dst)
102 {
103         memset(dst, 0x0, offsetof(DRWManager, ogl_context));
104 }
105
106 /* This function is used to reset draw manager to a state
107  * where we don't re-use data by accident across different
108  * draw calls.
109  */
110 #ifdef DEBUG
111 static void drw_state_ensure_not_reused(DRWManager *dst)
112 {
113         memset(dst, 0xff, offsetof(DRWManager, ogl_context));
114 }
115 #endif
116
117 /* -------------------------------------------------------------------- */
118
119 void DRW_draw_callbacks_pre_scene(void)
120 {
121         RegionView3D *rv3d = DST.draw_ctx.rv3d;
122
123         gpuLoadProjectionMatrix(rv3d->winmat);
124         gpuLoadMatrix(rv3d->viewmat);
125 }
126
127 void DRW_draw_callbacks_post_scene(void)
128 {
129         RegionView3D *rv3d = DST.draw_ctx.rv3d;
130
131         gpuLoadProjectionMatrix(rv3d->winmat);
132         gpuLoadMatrix(rv3d->viewmat);
133 }
134
135 struct DRWTextStore *DRW_text_cache_ensure(void)
136 {
137         BLI_assert(DST.text_store_p);
138         if (*DST.text_store_p == NULL) {
139                 *DST.text_store_p = DRW_text_cache_create();
140         }
141         return *DST.text_store_p;
142 }
143
144
145 /* -------------------------------------------------------------------- */
146
147 /** \name Settings
148  * \{ */
149
150 bool DRW_object_is_renderable(Object *ob)
151 {
152         BLI_assert(BKE_object_is_visible(ob, OB_VISIBILITY_CHECK_UNKNOWN_RENDER_MODE));
153
154         if (ob->type == OB_MESH) {
155                 if ((ob == DST.draw_ctx.object_edit) || BKE_object_is_in_editmode(ob)) {
156                         View3D *v3d = DST.draw_ctx.v3d;
157                         const int mask = (V3D_OVERLAY_EDIT_OCCLUDE_WIRE | V3D_OVERLAY_EDIT_WEIGHT);
158
159                         if (v3d && v3d->overlay.edit_flag & mask) {
160                                 return false;
161                         }
162                 }
163         }
164
165         return true;
166 }
167
168 /**
169  * Return whether this object is visible depending if
170  * we are rendering or drawing in the viewport.
171  */
172 bool DRW_check_object_visible_within_active_context(Object *ob)
173 {
174         const eObjectVisibilityCheck mode = DRW_state_is_scene_render() ?
175                                              OB_VISIBILITY_CHECK_FOR_RENDER :
176                                              OB_VISIBILITY_CHECK_FOR_VIEWPORT;
177         return BKE_object_is_visible(ob, mode);
178 }
179
180 bool DRW_object_is_flat_normal(const Object *ob)
181 {
182         if (ob->type == OB_MESH) {
183                 const Mesh *me = ob->data;
184                 if (me->mpoly && me->mpoly[0].flag & ME_SMOOTH) {
185                         return false;
186                 }
187         }
188         return true;
189 }
190
191 /**
192  * Return true if the object has its own draw mode.
193  * Caller must check this is active */
194 int DRW_object_is_mode_shade(const Object *ob)
195 {
196         BLI_assert(ob == DST.draw_ctx.obact);
197         UNUSED_VARS_NDEBUG(ob);
198         if ((DST.draw_ctx.object_mode & OB_MODE_EDIT) == 0) {
199                 if ((DST.draw_ctx.object_mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)) > 0) {
200                         if (ELEM(DST.draw_ctx.v3d->drawtype, OB_MATERIAL, OB_RENDER)) {
201                                 return false;
202                         }
203                         else if ((DST.draw_ctx.v3d->flag2 & V3D_SHOW_MODE_SHADE_OVERRIDE) == 0) {
204                                 return true;
205                         }
206                         else {
207                                 return false;
208                         }
209                 }
210         }
211         return -1;
212 }
213
214 int DRW_object_is_paint_mode(const Object *ob)
215 {
216         if (ob == DST.draw_ctx.obact) {
217                 if ((DST.draw_ctx.object_mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)) > 0) {
218                         return true;
219                 }
220         }
221         return false;
222 }
223
224 bool DRW_check_psys_visible_within_active_context(
225         Object *object,
226         struct ParticleSystem *psys)
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 /** \} */
252
253
254 /* -------------------------------------------------------------------- */
255
256 /** \name Color Management
257  * \{ */
258
259 /* Use color management profile to draw texture to framebuffer */
260 void DRW_transform_to_display(GPUTexture *tex)
261 {
262         drw_state_set(DRW_STATE_WRITE_COLOR);
263
264         Gwn_VertFormat *vert_format = immVertexFormat();
265         uint pos = GWN_vertformat_attr_add(vert_format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
266         uint texco = GWN_vertformat_attr_add(vert_format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
267
268         const float dither = 1.0f;
269
270         bool use_ocio = false;
271
272         /* View transform is already applied for offscreen, don't apply again, see: T52046 */
273         if (!(DST.options.is_image_render && !DST.options.is_scene_render)) {
274                 Scene *scene = DST.draw_ctx.scene;
275                 use_ocio = IMB_colormanagement_setup_glsl_draw_from_space(
276                         &scene->view_settings, &scene->display_settings, NULL, dither, false);
277         }
278
279         if (!use_ocio) {
280                 /* View transform is already applied for offscreen, don't apply again, see: T52046 */
281                 if (DST.options.is_image_render && !DST.options.is_scene_render) {
282                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_COLOR);
283                         immUniformColor4f(1.0f, 1.0f, 1.0f, 1.0f);
284                 }
285                 else {
286                         immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_LINEAR_TO_SRGB);
287                 }
288                 immUniform1i("image", 0);
289         }
290
291         GPU_texture_bind(tex, 0); /* OCIO texture bind point is 0 */
292
293         float mat[4][4];
294         unit_m4(mat);
295         immUniformMatrix4fv("ModelViewProjectionMatrix", mat);
296
297         /* Full screen triangle */
298         immBegin(GWN_PRIM_TRIS, 3);
299         immAttrib2f(texco, 0.0f, 0.0f);
300         immVertex2f(pos, -1.0f, -1.0f);
301
302         immAttrib2f(texco, 2.0f, 0.0f);
303         immVertex2f(pos, 3.0f, -1.0f);
304
305         immAttrib2f(texco, 0.0f, 2.0f);
306         immVertex2f(pos, -1.0f, 3.0f);
307         immEnd();
308
309         GPU_texture_unbind(tex);
310
311         if (use_ocio) {
312                 IMB_colormanagement_finish_glsl_draw();
313         }
314         else {
315                 immUnbindProgram();
316         }
317 }
318
319 /** \} */
320
321
322 /* -------------------------------------------------------------------- */
323
324 /** \name Multisample Resolve
325  * \{ */
326
327 /* Use manual multisample resolve pass.
328  * Much quicker than blitting back and forth.
329  * Assume destination fb is bound*/
330 void DRW_multisamples_resolve(GPUTexture *src_depth, GPUTexture *src_color)
331 {
332         drw_state_set(DRW_STATE_WRITE_COLOR | DRW_STATE_BLEND_PREMUL |
333                       DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL);
334
335         int samples = GPU_texture_samples(src_depth);
336
337         BLI_assert(samples > 0);
338         BLI_assert(GPU_texture_samples(src_color) == samples);
339
340         Gwn_Batch *geom = DRW_cache_fullscreen_quad_get();
341
342         int builtin;
343         switch (samples) {
344                 case 2:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2; break;
345                 case 4:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_4; break;
346                 case 8:  builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_8; break;
347                 case 16: builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_16; break;
348                 default:
349                         BLI_assert(0);
350                         builtin = GPU_SHADER_2D_IMAGE_MULTISAMPLE_2;
351                         break;
352         }
353
354         GWN_batch_program_set_builtin(geom, builtin);
355
356         GPU_texture_bind(src_depth, 0);
357         GPU_texture_bind(src_color, 1);
358         GWN_batch_uniform_1i(geom, "depthMulti", 0);
359         GWN_batch_uniform_1i(geom, "colorMulti", 1);
360
361         float mat[4][4];
362         unit_m4(mat);
363         GWN_batch_uniform_mat4(geom, "ModelViewProjectionMatrix", mat);
364
365         /* avoid gpuMatrix calls */
366         GWN_batch_program_use_begin(geom);
367         GWN_batch_draw_range_ex(geom, 0, 0, false);
368         GWN_batch_program_use_end(geom);
369 }
370
371 /** \} */
372
373 /* -------------------------------------------------------------------- */
374
375 /** \name Viewport (DRW_viewport)
376  * \{ */
377
378 void *drw_viewport_engine_data_ensure(void *engine_type)
379 {
380         void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
381
382         if (data == NULL) {
383                 data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
384         }
385         return data;
386 }
387
388 void DRW_engine_viewport_data_size_get(
389         const void *engine_type_v,
390         int *r_fbl_len, int *r_txl_len, int *r_psl_len, int *r_stl_len)
391 {
392         const DrawEngineType *engine_type = engine_type_v;
393
394         if (r_fbl_len) {
395                 *r_fbl_len = engine_type->vedata_size->fbl_len;
396         }
397         if (r_txl_len) {
398                 *r_txl_len = engine_type->vedata_size->txl_len;
399         }
400         if (r_psl_len) {
401                 *r_psl_len = engine_type->vedata_size->psl_len;
402         }
403         if (r_stl_len) {
404                 *r_stl_len = engine_type->vedata_size->stl_len;
405         }
406 }
407
408 const float *DRW_viewport_size_get(void)
409 {
410         return DST.size;
411 }
412
413 const float *DRW_viewport_invert_size_get(void)
414 {
415         return DST.inv_size;
416 }
417
418 const float *DRW_viewport_screenvecs_get(void)
419 {
420         return &DST.screenvecs[0][0];
421 }
422
423 const float *DRW_viewport_pixelsize_get(void)
424 {
425         return &DST.pixsize;
426 }
427
428 static void drw_viewport_cache_resize(void)
429 {
430         /* Release the memiter before clearing the mempools that references them */
431         GPU_viewport_cache_release(DST.viewport);
432
433         if (DST.vmempool != NULL) {
434                 BLI_mempool_clear_ex(DST.vmempool->calls, BLI_mempool_len(DST.vmempool->calls));
435                 BLI_mempool_clear_ex(DST.vmempool->states, BLI_mempool_len(DST.vmempool->states));
436                 BLI_mempool_clear_ex(DST.vmempool->shgroups, BLI_mempool_len(DST.vmempool->shgroups));
437                 BLI_mempool_clear_ex(DST.vmempool->uniforms, BLI_mempool_len(DST.vmempool->uniforms));
438                 BLI_mempool_clear_ex(DST.vmempool->passes, BLI_mempool_len(DST.vmempool->passes));
439         }
440
441         DRW_instance_data_list_free_unused(DST.idatalist);
442         DRW_instance_data_list_resize(DST.idatalist);
443 }
444
445 /* Not a viewport variable, we could split this out. */
446 static void drw_context_state_init(void)
447 {
448         if (DST.draw_ctx.obact) {
449                 DST.draw_ctx.object_mode = DST.draw_ctx.obact->mode;
450         }
451         else {
452                 DST.draw_ctx.object_mode = OB_MODE_OBJECT;
453         }
454
455         /* Edit object. */
456         if (DST.draw_ctx.object_mode & OB_MODE_EDIT) {
457                 DST.draw_ctx.object_edit = DST.draw_ctx.obact;
458         }
459         else {
460                 DST.draw_ctx.object_edit = NULL;
461         }
462
463         /* Pose object. */
464         if (DST.draw_ctx.object_mode & OB_MODE_POSE) {
465                 DST.draw_ctx.object_pose = DST.draw_ctx.obact;
466         }
467         else if (DST.draw_ctx.object_mode & OB_MODE_WEIGHT_PAINT) {
468                 DST.draw_ctx.object_pose = BKE_object_pose_armature_get(DST.draw_ctx.obact);
469         }
470         else {
471                 DST.draw_ctx.object_pose = NULL;
472         }
473 }
474
475 /* It also stores viewport variable to an immutable place: DST
476  * This is because a cache uniform only store reference
477  * to its value. And we don't want to invalidate the cache
478  * if this value change per viewport */
479 static void drw_viewport_var_init(void)
480 {
481         RegionView3D *rv3d = DST.draw_ctx.rv3d;
482         /* Refresh DST.size */
483         if (DST.viewport) {
484                 int size[2];
485                 GPU_viewport_size_get(DST.viewport, size);
486                 DST.size[0] = size[0];
487                 DST.size[1] = size[1];
488                 DST.inv_size[0] = 1.0f / size[0];
489                 DST.inv_size[1] = 1.0f / size[1];
490
491                 DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
492                 DST.default_framebuffer = fbl->default_fb;
493
494                 DST.vmempool = GPU_viewport_mempool_get(DST.viewport);
495
496                 if (DST.vmempool->calls == NULL) {
497                         DST.vmempool->calls = BLI_mempool_create(sizeof(DRWCall), 0, 512, 0);
498                 }
499                 if (DST.vmempool->states == NULL) {
500                         DST.vmempool->states = BLI_mempool_create(sizeof(DRWCallState), 0, 512, BLI_MEMPOOL_ALLOW_ITER);
501                 }
502                 if (DST.vmempool->shgroups == NULL) {
503                         DST.vmempool->shgroups = BLI_mempool_create(sizeof(DRWShadingGroup), 0, 256, 0);
504                 }
505                 if (DST.vmempool->uniforms == NULL) {
506                         DST.vmempool->uniforms = BLI_mempool_create(sizeof(DRWUniform), 0, 512, 0);
507                 }
508                 if (DST.vmempool->passes == NULL) {
509                         DST.vmempool->passes = BLI_mempool_create(sizeof(DRWPass), 0, 64, 0);
510                 }
511
512                 DST.idatalist = GPU_viewport_instance_data_list_get(DST.viewport);
513                 DRW_instance_data_list_reset(DST.idatalist);
514         }
515         else {
516                 DST.size[0] = 0;
517                 DST.size[1] = 0;
518
519                 DST.inv_size[0] = 0;
520                 DST.inv_size[1] = 0;
521
522                 DST.default_framebuffer = NULL;
523                 DST.vmempool = NULL;
524         }
525
526         if (rv3d != NULL) {
527                 /* Refresh DST.screenvecs */
528                 copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
529                 copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
530                 normalize_v3(DST.screenvecs[0]);
531                 normalize_v3(DST.screenvecs[1]);
532
533                 /* Refresh DST.pixelsize */
534                 DST.pixsize = rv3d->pixsize;
535
536                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERS], rv3d->persmat);
537                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_PERSINV], rv3d->persinv);
538                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEW], rv3d->viewmat);
539                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_VIEWINV], rv3d->viewinv);
540                 copy_m4_m4(DST.original_mat.mat[DRW_MAT_WIN], rv3d->winmat);
541                 invert_m4_m4(DST.original_mat.mat[DRW_MAT_WININV], rv3d->winmat);
542
543                 memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DST.original_mat.mat));
544
545                 copy_v4_v4(DST.view_data.viewcamtexcofac, rv3d->viewcamtexcofac);
546         }
547         else {
548                 copy_v4_fl4(DST.view_data.viewcamtexcofac, 1.0f, 1.0f, 0.0f, 0.0f);
549         }
550
551         /* Reset facing */
552         DST.frontface = GL_CCW;
553         DST.backface = GL_CW;
554         glFrontFace(DST.frontface);
555
556         if (DST.draw_ctx.object_edit) {
557                 ED_view3d_init_mats_rv3d(DST.draw_ctx.object_edit, rv3d);
558         }
559
560         /* Alloc array of texture reference. */
561         if (DST.RST.bound_texs == NULL) {
562                 DST.RST.bound_texs = MEM_callocN(sizeof(GPUTexture *) * GPU_max_textures(), "Bound GPUTexture refs");
563         }
564         if (DST.RST.bound_tex_slots == NULL) {
565                 DST.RST.bound_tex_slots = MEM_callocN(sizeof(char) * GPU_max_textures(), "Bound Texture Slots");
566         }
567         if (DST.RST.bound_ubos == NULL) {
568                 DST.RST.bound_ubos = MEM_callocN(sizeof(GPUUniformBuffer *) * GPU_max_ubo_binds(), "Bound GPUUniformBuffer refs");
569         }
570         if (DST.RST.bound_ubo_slots == NULL) {
571                 DST.RST.bound_ubo_slots = MEM_callocN(sizeof(char) * GPU_max_ubo_binds(), "Bound Ubo Slots");
572         }
573
574         if (view_ubo == NULL) {
575                 view_ubo = DRW_uniformbuffer_create(sizeof(ViewUboStorage), NULL);
576         }
577
578         DST.override_mat = 0;
579         DST.dirty_mat = true;
580         DST.state_cache_id = 1;
581
582         DST.clipping.updated = false;
583
584         memset(DST.object_instance_data, 0x0, sizeof(DST.object_instance_data));
585 }
586
587 void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
588 {
589         BLI_assert(type >= 0 && type < DRW_MAT_COUNT);
590         /* Can't use this in render mode. */
591         BLI_assert(((DST.override_mat & (1 << type)) != 0) || DST.draw_ctx.rv3d != NULL);
592
593         copy_m4_m4(mat, DST.view_data.matstate.mat[type]);
594 }
595
596 void DRW_viewport_matrix_get_all(DRWMatrixState *state)
597 {
598         memcpy(state, DST.view_data.matstate.mat, sizeof(DRWMatrixState));
599 }
600
601 void DRW_viewport_matrix_override_set(const float mat[4][4], DRWViewportMatrixType type)
602 {
603         BLI_assert(type < DRW_MAT_COUNT);
604         copy_m4_m4(DST.view_data.matstate.mat[type], mat);
605         DST.override_mat |= (1 << type);
606         DST.dirty_mat = true;
607         DST.clipping.updated = false;
608 }
609
610 void DRW_viewport_matrix_override_unset(DRWViewportMatrixType type)
611 {
612         BLI_assert(type < DRW_MAT_COUNT);
613         copy_m4_m4(DST.view_data.matstate.mat[type], DST.original_mat.mat[type]);
614         DST.override_mat &= ~(1 << type);
615         DST.dirty_mat = true;
616         DST.clipping.updated = false;
617 }
618
619 void DRW_viewport_matrix_override_set_all(DRWMatrixState *state)
620 {
621         memcpy(DST.view_data.matstate.mat, state, sizeof(DRWMatrixState));
622         DST.override_mat = 0xFFFFFF;
623         DST.dirty_mat = true;
624         DST.clipping.updated = false;
625 }
626
627 void DRW_viewport_matrix_override_unset_all(void)
628 {
629         memcpy(DST.view_data.matstate.mat, DST.original_mat.mat, sizeof(DRWMatrixState));
630         DST.override_mat = 0;
631         DST.dirty_mat = true;
632         DST.clipping.updated = false;
633 }
634
635 bool DRW_viewport_is_persp_get(void)
636 {
637         RegionView3D *rv3d = DST.draw_ctx.rv3d;
638         if (rv3d) {
639                 return rv3d->is_persp;
640         }
641         else {
642                 return DST.view_data.matstate.mat[DRW_MAT_WIN][3][3] == 0.0f;
643         }
644 }
645
646 float DRW_viewport_near_distance_get(void)
647 {
648         float projmat[4][4];
649         DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
650
651         if (DRW_viewport_is_persp_get()) {
652                 return -projmat[3][2] / (projmat[2][2] - 1.0f);
653         }
654         else {
655                 return -(projmat[3][2] + 1.0f) / projmat[2][2];
656         }
657 }
658
659 float DRW_viewport_far_distance_get(void)
660 {
661         float projmat[4][4];
662         DRW_viewport_matrix_get(projmat, DRW_MAT_WIN);
663
664         if (DRW_viewport_is_persp_get()) {
665                 return -projmat[3][2] / (projmat[2][2] + 1.0f);
666         }
667         else {
668                 return -(projmat[3][2] - 1.0f) / projmat[2][2];
669         }
670 }
671
672 DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
673 {
674         return GPU_viewport_framebuffer_list_get(DST.viewport);
675 }
676
677 DefaultTextureList *DRW_viewport_texture_list_get(void)
678 {
679         return GPU_viewport_texture_list_get(DST.viewport);
680 }
681
682 void DRW_viewport_request_redraw(void)
683 {
684         GPU_viewport_tag_update(DST.viewport);
685 }
686
687 /** \} */
688
689
690 /* -------------------------------------------------------------------- */
691 /** \name ViewLayers (DRW_scenelayer)
692  * \{ */
693
694 void *DRW_view_layer_engine_data_get(DrawEngineType *engine_type)
695 {
696         for (ViewLayerEngineData *sled = DST.draw_ctx.view_layer->drawdata.first; sled; sled = sled->next) {
697                 if (sled->engine_type == engine_type) {
698                         return sled->storage;
699                 }
700         }
701         return NULL;
702 }
703
704 void **DRW_view_layer_engine_data_ensure_ex(
705         ViewLayer *view_layer, DrawEngineType *engine_type, void (*callback)(void *storage))
706 {
707         ViewLayerEngineData *sled;
708
709         for (sled = view_layer->drawdata.first; sled; sled = sled->next) {
710                 if (sled->engine_type == engine_type) {
711                         return &sled->storage;
712                 }
713         }
714
715         sled = MEM_callocN(sizeof(ViewLayerEngineData), "ViewLayerEngineData");
716         sled->engine_type = engine_type;
717         sled->free = callback;
718         BLI_addtail(&view_layer->drawdata, sled);
719
720         return &sled->storage;
721 }
722
723 void **DRW_view_layer_engine_data_ensure(DrawEngineType *engine_type, void (*callback)(void *storage))
724 {
725         return DRW_view_layer_engine_data_ensure_ex(DST.draw_ctx.view_layer, engine_type, callback);
726 }
727
728 /** \} */
729
730
731 /* -------------------------------------------------------------------- */
732
733 /** \name Objects (DRW_object)
734  * \{ */
735
736 ObjectEngineData *DRW_object_engine_data_get(Object *ob, DrawEngineType *engine_type)
737 {
738         for (ObjectEngineData *oed = ob->drawdata.first; oed; oed = oed->next) {
739                 if (oed->engine_type == engine_type) {
740                         return oed;
741                 }
742         }
743         return NULL;
744 }
745
746 ObjectEngineData *DRW_object_engine_data_ensure(
747         Object *ob,
748         DrawEngineType *engine_type,
749         size_t size,
750         ObjectEngineDataInitCb init_cb,
751         ObjectEngineDataFreeCb free_cb)
752 {
753         BLI_assert(size >= sizeof(ObjectEngineData));
754         /* Try to re-use existing data. */
755         ObjectEngineData *oed = DRW_object_engine_data_get(ob, engine_type);
756         if (oed != NULL) {
757                 return oed;
758         }
759         /* Allocate new data. */
760         if ((ob->base_flag & BASE_FROMDUPLI) != 0) {
761                 /* NOTE: data is not persistent in this case. It is reset each redraw. */
762                 BLI_assert(free_cb == NULL); /* No callback allowed. */
763                 /* Round to sizeof(float) for DRW_instance_data_request(). */
764                 const size_t t = sizeof(float) - 1;
765                 size = (size + t) & ~t;
766                 size_t fsize = size / sizeof(float);
767                 BLI_assert(fsize < MAX_INSTANCE_DATA_SIZE);
768                 if (DST.object_instance_data[fsize] == NULL) {
769                         DST.object_instance_data[fsize] = DRW_instance_data_request(DST.idatalist, fsize);
770                 }
771                 oed = (ObjectEngineData *)DRW_instance_data_next(DST.object_instance_data[fsize]);
772                 memset(oed, 0, size);
773         }
774         else {
775                 oed = MEM_callocN(size, "ObjectEngineData");
776         }
777         oed->engine_type = engine_type;
778         oed->free = free_cb;
779         /* Perform user-side initialization, if needed. */
780         if (init_cb != NULL) {
781                 init_cb(oed);
782         }
783         /* Register in the list. */
784         BLI_addtail(&ob->drawdata, oed);
785         return oed;
786 }
787
788 /** \} */
789
790
791 /* -------------------------------------------------------------------- */
792
793 /** \name Rendering (DRW_engines)
794  * \{ */
795
796 static void drw_engines_init(void)
797 {
798         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
799                 DrawEngineType *engine = link->data;
800                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
801                 PROFILE_START(stime);
802
803                 if (engine->engine_init) {
804                         engine->engine_init(data);
805                 }
806
807                 PROFILE_END_UPDATE(data->init_time, stime);
808         }
809 }
810
811 static void drw_engines_cache_init(void)
812 {
813         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
814                 DrawEngineType *engine = link->data;
815                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
816
817                 if (data->text_draw_cache) {
818                         DRW_text_cache_destroy(data->text_draw_cache);
819                         data->text_draw_cache = NULL;
820                 }
821                 if (DST.text_store_p == NULL) {
822                         DST.text_store_p = &data->text_draw_cache;
823                 }
824
825                 if (engine->cache_init) {
826                         engine->cache_init(data);
827                 }
828         }
829 }
830
831 static void drw_engines_cache_populate(Object *ob)
832 {
833         DST.ob_state = NULL;
834
835         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
836                 DrawEngineType *engine = link->data;
837                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
838
839                 if (engine->id_update) {
840                         engine->id_update(data, &ob->id);
841                 }
842
843                 if (engine->cache_populate) {
844                         engine->cache_populate(data, ob);
845                 }
846         }
847 }
848
849 static void drw_engines_cache_finish(void)
850 {
851         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
852                 DrawEngineType *engine = link->data;
853                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
854
855                 if (engine->cache_finish) {
856                         engine->cache_finish(data);
857                 }
858         }
859 }
860
861 static void drw_engines_draw_background(void)
862 {
863         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
864                 DrawEngineType *engine = link->data;
865                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
866
867                 if (engine->draw_background) {
868                         PROFILE_START(stime);
869
870                         DRW_stats_group_start(engine->idname);
871                         engine->draw_background(data);
872                         DRW_stats_group_end();
873
874                         PROFILE_END_UPDATE(data->background_time, stime);
875                         return;
876                 }
877         }
878
879         /* No draw_background found, doing default background */
880         if (DRW_state_draw_background()) {
881                 DRW_draw_background();
882         }
883 }
884
885 static void drw_engines_draw_scene(void)
886 {
887         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
888                 DrawEngineType *engine = link->data;
889                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
890                 PROFILE_START(stime);
891
892                 if (engine->draw_scene) {
893                         DRW_stats_group_start(engine->idname);
894                         engine->draw_scene(data);
895                         /* Restore for next engine */
896                         if (DRW_state_is_fbo()) {
897                                 GPU_framebuffer_bind(DST.default_framebuffer);
898                         }
899                         DRW_stats_group_end();
900                 }
901
902                 PROFILE_END_UPDATE(data->render_time, stime);
903         }
904 }
905
906 static void drw_engines_draw_text(void)
907 {
908         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
909                 DrawEngineType *engine = link->data;
910                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
911                 PROFILE_START(stime);
912
913                 if (data->text_draw_cache) {
914                         DRW_text_cache_draw(data->text_draw_cache, DST.draw_ctx.v3d, DST.draw_ctx.ar, false);
915                 }
916
917                 PROFILE_END_UPDATE(data->render_time, stime);
918         }
919 }
920
921 #define MAX_INFO_LINES 10
922
923 /**
924  * Returns the offset required for the drawing of engines info.
925  */
926 int DRW_draw_region_engine_info_offset(void)
927 {
928         int lines = 0;
929         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
930                 DrawEngineType *engine = link->data;
931                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
932
933                 /* Count the number of lines. */
934                 if (data->info[0] != '\0') {
935                         lines++;
936                         char *c = data->info;
937                         while (*c++ != '\0') {
938                                 if (*c == '\n') {
939                                         lines++;
940                                 }
941                         }
942                 }
943         }
944         return MIN2(MAX_INFO_LINES, lines) * UI_UNIT_Y;
945 }
946
947 /**
948  * Actual drawing;
949  */
950 void DRW_draw_region_engine_info(void)
951 {
952         const char *info_array_final[MAX_INFO_LINES + 1];
953         /* This should be maxium number of engines running at the same time. */
954         char info_array[MAX_INFO_LINES][GPU_INFO_SIZE];
955         int i = 0;
956
957         const DRWContextState *draw_ctx = DRW_context_state_get();
958         ARegion *ar = draw_ctx->ar;
959         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
960
961         UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
962         mul_v3_fl(fill_color, fill_color[3]);
963
964         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
965                 DrawEngineType *engine = link->data;
966                 ViewportEngineData *data = drw_viewport_engine_data_ensure(engine);
967
968                 if (data->info[0] != '\0') {
969                         char *chr_current = data->info;
970                         char *chr_start = chr_current;
971                         int line_len = 0;
972
973                         while (*chr_current++ != '\0') {
974                                 line_len++;
975                                 if (*chr_current == '\n') {
976                                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
977                                         /* Re-start counting. */
978                                         chr_start = chr_current + 1;
979                                         line_len = -1;
980                                 }
981                         }
982
983                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
984
985                         if (i >= MAX_INFO_LINES) {
986                                 break;
987                         }
988                 }
989         }
990
991         for (int j = 0; j < i; j++) {
992                 info_array_final[j] = info_array[j];
993         }
994         info_array_final[i] = NULL;
995
996         if (info_array[0] != NULL) {
997                 ED_region_info_draw_multiline(ar, info_array_final, fill_color, true);
998         }
999 }
1000
1001 #undef MAX_INFO_LINES
1002
1003 static void use_drw_engine(DrawEngineType *engine)
1004 {
1005         LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
1006         ld->data = engine;
1007         BLI_addtail(&DST.enabled_engines, ld);
1008 }
1009
1010 /**
1011  * Use for external render engines.
1012  */
1013 static void drw_engines_enable_external(void)
1014 {
1015         use_drw_engine(DRW_engine_viewport_external_type.draw_engine);
1016 }
1017
1018 /* TODO revisit this when proper layering is implemented */
1019 /* Gather all draw engines needed and store them in DST.enabled_engines
1020  * That also define the rendering order of engines */
1021 static void drw_engines_enable_from_engine(RenderEngineType *engine_type, int drawtype, int shading_flags)
1022 {
1023         switch (drawtype) {
1024                 case OB_WIRE:
1025                         break;
1026
1027                 case OB_SOLID:
1028                 case OB_TEXTURE:
1029                         if (shading_flags & V3D_SHADING_XRAY) {
1030                                 use_drw_engine(&draw_engine_workbench_transparent);
1031                         }
1032                         else {
1033                                 use_drw_engine(&draw_engine_workbench_solid);
1034                         }
1035                         break;
1036
1037                 case OB_MATERIAL:
1038                 case OB_RENDER:
1039                 default:
1040                         /* TODO layers */
1041                         if (engine_type->draw_engine != NULL) {
1042                                 use_drw_engine(engine_type->draw_engine);
1043                         }
1044
1045                         if ((engine_type->flag & RE_INTERNAL) == 0) {
1046                                 drw_engines_enable_external();
1047                         }
1048                         break;
1049         }
1050 }
1051
1052 static void drw_engines_enable_from_object_mode(void)
1053 {
1054         use_drw_engine(&draw_engine_object_type);
1055         /* TODO(fclem) remove this, it does not belong to it's own engine. */
1056         use_drw_engine(&draw_engine_motion_path_type);
1057 }
1058
1059 static void drw_engines_enable_from_mode(int mode)
1060 {
1061         switch (mode) {
1062                 case CTX_MODE_EDIT_MESH:
1063                         use_drw_engine(&draw_engine_edit_mesh_type);
1064                         break;
1065                 case CTX_MODE_EDIT_CURVE:
1066                         use_drw_engine(&draw_engine_edit_curve_type);
1067                         break;
1068                 case CTX_MODE_EDIT_SURFACE:
1069                         use_drw_engine(&draw_engine_edit_surface_type);
1070                         break;
1071                 case CTX_MODE_EDIT_TEXT:
1072                         use_drw_engine(&draw_engine_edit_text_type);
1073                         break;
1074                 case CTX_MODE_EDIT_ARMATURE:
1075                         use_drw_engine(&draw_engine_edit_armature_type);
1076                         break;
1077                 case CTX_MODE_EDIT_METABALL:
1078                         use_drw_engine(&draw_engine_edit_metaball_type);
1079                         break;
1080                 case CTX_MODE_EDIT_LATTICE:
1081                         use_drw_engine(&draw_engine_edit_lattice_type);
1082                         break;
1083                 case CTX_MODE_POSE:
1084                         use_drw_engine(&draw_engine_pose_type);
1085                         break;
1086                 case CTX_MODE_SCULPT:
1087                         use_drw_engine(&draw_engine_sculpt_type);
1088                         break;
1089                 case CTX_MODE_PAINT_WEIGHT:
1090                         use_drw_engine(&draw_engine_pose_type);
1091                         use_drw_engine(&draw_engine_paint_weight_type);
1092                         break;
1093                 case CTX_MODE_PAINT_VERTEX:
1094                         use_drw_engine(&draw_engine_paint_vertex_type);
1095                         break;
1096                 case CTX_MODE_PAINT_TEXTURE:
1097                         use_drw_engine(&draw_engine_paint_texture_type);
1098                         break;
1099                 case CTX_MODE_PARTICLE:
1100                         use_drw_engine(&draw_engine_particle_type);
1101                         break;
1102                 case CTX_MODE_OBJECT:
1103                         break;
1104                 default:
1105                         BLI_assert(!"Draw mode invalid");
1106                         break;
1107         }
1108 }
1109
1110 static void drw_engines_enable_from_overlays(int overlay_flag)
1111 {
1112         if (overlay_flag) {
1113                 use_drw_engine(&draw_engine_overlay_type);
1114         }
1115 }
1116 /**
1117  * Use for select and depth-drawing.
1118  */
1119 static void drw_engines_enable_basic(void)
1120 {
1121         use_drw_engine(DRW_engine_viewport_basic_type.draw_engine);
1122 }
1123
1124 static void drw_engines_enable(ViewLayer *view_layer, RenderEngineType *engine_type)
1125 {
1126         Object *obact = OBACT(view_layer);
1127         const int mode = CTX_data_mode_enum_ex(DST.draw_ctx.object_edit, obact, DST.draw_ctx.object_mode);
1128         View3D * v3d = DST.draw_ctx.v3d;
1129         const int drawtype = v3d->drawtype;
1130
1131         drw_engines_enable_from_engine(engine_type, drawtype, v3d->shading.flag);
1132
1133         if (DRW_state_draw_support()) {
1134                 drw_engines_enable_from_overlays(v3d->overlay.flag);
1135                 drw_engines_enable_from_object_mode();
1136                 drw_engines_enable_from_mode(mode);
1137         }
1138 }
1139
1140 static void drw_engines_disable(void)
1141 {
1142         BLI_freelistN(&DST.enabled_engines);
1143 }
1144
1145 static uint DRW_engines_get_hash(void)
1146 {
1147         uint hash = 0;
1148         /* The cache depends on enabled engines */
1149         /* FIXME : if collision occurs ... segfault */
1150         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1151                 DrawEngineType *engine = link->data;
1152                 hash += BLI_ghashutil_strhash_p(engine->idname);
1153         }
1154
1155         return hash;
1156 }
1157
1158 /* -------------------------------------------------------------------- */
1159
1160 /** \name View Update
1161  * \{ */
1162
1163 void DRW_notify_view_update(const DRWUpdateContext *update_ctx)
1164 {
1165         RenderEngineType *engine_type = update_ctx->engine_type;
1166         ARegion *ar = update_ctx->ar;
1167         View3D *v3d = update_ctx->v3d;
1168         RegionView3D *rv3d = ar->regiondata;
1169         Depsgraph *depsgraph = update_ctx->depsgraph;
1170         Scene *scene = update_ctx->scene;
1171         ViewLayer *view_layer = update_ctx->view_layer;
1172
1173         /* Separate update for each stereo view. */
1174         for (int view = 0; view < 2; view++) {
1175                 GPUViewport *viewport = WM_draw_region_get_viewport(ar, view);
1176                 if (!viewport) {
1177                         continue;
1178                 }
1179
1180                 /* XXX Really nasty locking. But else this could
1181                  * be executed by the material previews thread
1182                  * while rendering a viewport. */
1183                 BLI_mutex_lock(&DST.ogl_context_mutex);
1184
1185                 /* Reset before using it. */
1186                 drw_state_prepare_clean_for_draw(&DST);
1187
1188                 DST.viewport = viewport;
1189                 DST.draw_ctx = (DRWContextState){
1190                         .ar = ar, .rv3d = rv3d, .v3d = v3d,
1191                         .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
1192                         .engine_type = engine_type,
1193                         .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
1194                 };
1195
1196                 drw_engines_enable(view_layer, engine_type);
1197
1198                 for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1199                         DrawEngineType *draw_engine = link->data;
1200                         ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine);
1201
1202                         if (draw_engine->view_update) {
1203                                 draw_engine->view_update(data);
1204                         }
1205                 }
1206
1207                 DST.viewport = NULL;
1208
1209                 drw_engines_disable();
1210
1211                 BLI_mutex_unlock(&DST.ogl_context_mutex);
1212         }
1213 }
1214
1215 /** \} */
1216
1217 /* -------------------------------------------------------------------- */
1218
1219 /** \name Main Draw Loops (DRW_draw)
1220  * \{ */
1221
1222 /* Everything starts here.
1223  * This function takes care of calling all cache and rendering functions
1224  * for each relevant engine / mode engine. */
1225 void DRW_draw_view(const bContext *C)
1226 {
1227         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1228         ARegion *ar = CTX_wm_region(C);
1229         View3D *v3d = CTX_wm_view3d(C);
1230         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1231         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
1232         GPUViewport *viewport = WM_draw_region_get_bound_viewport(ar);
1233
1234         /* Reset before using it. */
1235         drw_state_prepare_clean_for_draw(&DST);
1236         DST.options.draw_text = (
1237                 (v3d->flag2 & V3D_RENDER_OVERRIDE) == 0 &&
1238                 (v3d->overlay.flag & V3D_OVERLAY_HIDE_TEXT) != 0);
1239         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, C);
1240 }
1241
1242 /**
1243  * Used for both regular and off-screen drawing.
1244  * Need to reset DST before calling this function
1245  */
1246 void DRW_draw_render_loop_ex(
1247         struct Depsgraph *depsgraph,
1248         RenderEngineType *engine_type,
1249         ARegion *ar, View3D *v3d,
1250         GPUViewport *viewport,
1251         const bContext *evil_C)
1252 {
1253
1254         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1255         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1256         RegionView3D *rv3d = ar->regiondata;
1257
1258         DST.draw_ctx.evil_C = evil_C;
1259
1260         DST.viewport = viewport;
1261         v3d->zbuf = true;
1262
1263         /* Setup viewport */
1264         GPU_viewport_engines_data_validate(DST.viewport, DRW_engines_get_hash());
1265
1266         DST.draw_ctx = (DRWContextState){
1267             .ar = ar, .rv3d = rv3d, .v3d = v3d,
1268             .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
1269             .engine_type = engine_type,
1270             .depsgraph = depsgraph,
1271
1272             /* reuse if caller sets */
1273             .evil_C = DST.draw_ctx.evil_C,
1274         };
1275         drw_context_state_init();
1276         drw_viewport_var_init();
1277
1278         /* Get list of enabled engines */
1279         drw_engines_enable(view_layer, engine_type);
1280
1281         /* Update ubos */
1282         DRW_globals_update();
1283
1284         drw_debug_init();
1285         DRW_hair_init();
1286
1287         /* No framebuffer allowed before drawing. */
1288         BLI_assert(GPU_framebuffer_current_get() == 0);
1289
1290         /* Init engines */
1291         drw_engines_init();
1292
1293         /* Cache filling */
1294         {
1295                 PROFILE_START(stime);
1296                 drw_engines_cache_init();
1297
1298                 DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob, DRW_iterator_mode_get())
1299                 {
1300                         drw_engines_cache_populate(ob);
1301                 }
1302                 DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END;
1303
1304                 drw_engines_cache_finish();
1305
1306                 DRW_render_instance_buffer_finish();
1307
1308 #ifdef USE_PROFILE
1309                 double *cache_time = GPU_viewport_cache_time_get(DST.viewport);
1310                 PROFILE_END_UPDATE(*cache_time, stime);
1311 #endif
1312         }
1313
1314         DRW_stats_begin();
1315         DRW_hair_update();
1316
1317         GPU_framebuffer_bind(DST.default_framebuffer);
1318
1319         /* Start Drawing */
1320         DRW_state_reset();
1321
1322         drw_engines_draw_background();
1323
1324         /* WIP, single image drawn over the camera view (replace) */
1325         bool do_bg_image = false;
1326         if (rv3d->persp == RV3D_CAMOB) {
1327                 Object *cam_ob = v3d->camera;
1328                 if (cam_ob && cam_ob->type == OB_CAMERA) {
1329                         Camera *cam = cam_ob->data;
1330                         if (!BLI_listbase_is_empty(&cam->bg_images)) {
1331                                 do_bg_image = true;
1332                         }
1333                 }
1334         }
1335
1336         if (do_bg_image) {
1337                 ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, false, true);
1338         }
1339
1340
1341         DRW_draw_callbacks_pre_scene();
1342         if (DST.draw_ctx.evil_C) {
1343                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_PRE_VIEW);
1344         }
1345
1346         drw_engines_draw_scene();
1347
1348         DRW_draw_callbacks_post_scene();
1349         if (DST.draw_ctx.evil_C) {
1350                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_POST_VIEW);
1351         }
1352
1353         DRW_state_reset();
1354
1355         drw_debug_draw();
1356
1357         glDisable(GL_DEPTH_TEST);
1358         drw_engines_draw_text();
1359         glEnable(GL_DEPTH_TEST);
1360
1361         if (DST.draw_ctx.evil_C) {
1362                 /* needed so manipulator isn't obscured */
1363                 glDisable(GL_DEPTH_TEST);
1364                 DRW_draw_manipulator_3d();
1365
1366                 DRW_draw_region_info();
1367
1368                 /* Draw 2D after region info so we can draw on top of the camera passepartout overlay.
1369                  * 'DRW_draw_region_info' sets the projection in pixel-space. */
1370                 DRW_draw_manipulator_2d();
1371                 glEnable(GL_DEPTH_TEST);
1372         }
1373
1374         DRW_stats_reset();
1375
1376         if (do_bg_image) {
1377                 ED_view3d_draw_bgpic_test(scene, depsgraph, ar, v3d, true, true);
1378         }
1379
1380         if (G.debug_value > 20) {
1381                 glDisable(GL_DEPTH_TEST);
1382                 rcti rect; /* local coordinate visible rect inside region, to accomodate overlapping ui */
1383                 ED_region_visible_rect(DST.draw_ctx.ar, &rect);
1384                 DRW_stats_draw(&rect);
1385                 glEnable(GL_DEPTH_TEST);
1386         }
1387
1388         if (WM_draw_region_get_bound_viewport(ar)) {
1389                 /* Don't unbind the framebuffer yet in this case and let
1390                  * GPU_viewport_unbind do it, so that we can still do further
1391                  * drawing of action zones on top. */
1392         }
1393         else {
1394                 GPU_framebuffer_restore();
1395         }
1396
1397         DRW_state_reset();
1398         drw_engines_disable();
1399
1400         drw_viewport_cache_resize();
1401
1402 #ifdef DEBUG
1403         /* Avoid accidental reuse. */
1404         drw_state_ensure_not_reused(&DST);
1405 #endif
1406 }
1407
1408 void DRW_draw_render_loop(
1409         struct Depsgraph *depsgraph,
1410         ARegion *ar, View3D *v3d,
1411         GPUViewport *viewport)
1412 {
1413         /* Reset before using it. */
1414         drw_state_prepare_clean_for_draw(&DST);
1415
1416         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1417         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
1418
1419         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, viewport, NULL);
1420 }
1421
1422 /* @viewport CAN be NULL, in this case we create one. */
1423 void DRW_draw_render_loop_offscreen(
1424         struct Depsgraph *depsgraph, RenderEngineType *engine_type,
1425         ARegion *ar, View3D *v3d,
1426         const bool draw_background, GPUOffScreen *ofs,
1427         GPUViewport *viewport)
1428 {
1429         /* Create temporary viewport if needed. */
1430         GPUViewport *render_viewport = viewport;
1431         if (viewport == NULL) {
1432                 render_viewport = GPU_viewport_create_from_offscreen(ofs);
1433         }
1434
1435         GPU_framebuffer_restore();
1436
1437         /* Reset before using it. */
1438         drw_state_prepare_clean_for_draw(&DST);
1439         DST.options.is_image_render = true;
1440         DST.options.draw_background = draw_background;
1441         DRW_draw_render_loop_ex(depsgraph, engine_type, ar, v3d, render_viewport, NULL);
1442
1443         /* Free temporary viewport. */
1444         if (viewport == NULL) {
1445                 /* don't free data owned by 'ofs' */
1446                 GPU_viewport_clear_from_offscreen(render_viewport);
1447                 GPU_viewport_free(render_viewport);
1448         }
1449
1450         /* we need to re-bind (annoying!) */
1451         GPU_offscreen_bind(ofs, false);
1452 }
1453
1454 void DRW_render_to_image(RenderEngine *engine, struct Depsgraph *depsgraph)
1455 {
1456         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1457         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1458         RenderEngineType *engine_type = engine->type;
1459         DrawEngineType *draw_engine_type = engine_type->draw_engine;
1460         RenderData *r = &scene->r;
1461         Render *render = engine->re;
1462
1463         if (G.background && DST.ogl_context == NULL) {
1464                 WM_init_opengl();
1465         }
1466
1467         /* Changing Context */
1468         DRW_opengl_context_enable();
1469         /* IMPORTANT: We dont support immediate mode in render mode!
1470          * This shall remain in effect until immediate mode supports
1471          * multiple threads. */
1472
1473         /* Reset before using it. */
1474         drw_state_prepare_clean_for_draw(&DST);
1475         DST.options.is_image_render = true;
1476         DST.options.is_scene_render = true;
1477         DST.options.draw_background = scene->r.alphamode == R_ADDSKY;
1478
1479         DST.draw_ctx = (DRWContextState){
1480             .scene = scene, .view_layer = view_layer,
1481             .engine_type = engine_type,
1482             .depsgraph = depsgraph, .object_mode = OB_MODE_OBJECT,
1483         };
1484         drw_context_state_init();
1485
1486         DST.viewport = GPU_viewport_create();
1487         const int size[2] = {(r->size * r->xsch) / 100, (r->size * r->ysch) / 100};
1488         GPU_viewport_size_set(DST.viewport, size);
1489
1490         drw_viewport_var_init();
1491
1492         ViewportEngineData *data = drw_viewport_engine_data_ensure(draw_engine_type);
1493
1494         /* set default viewport */
1495         glViewport(0, 0, size[0], size[1]);
1496
1497         /* Main rendering. */
1498         rctf view_rect;
1499         rcti render_rect;
1500         RE_GetViewPlane(render, &view_rect, &render_rect);
1501         if (BLI_rcti_is_empty(&render_rect)) {
1502                 BLI_rcti_init(&render_rect, 0, size[0], 0, size[1]);
1503         }
1504
1505         /* Init render result. */
1506         RenderResult *render_result = RE_engine_begin_result(
1507                 engine,
1508                 0,
1509                 0,
1510                 (int)size[0],
1511                 (int)size[1],
1512                 view_layer->name,
1513                 /* RR_ALL_VIEWS */ NULL);
1514
1515         RenderLayer *render_layer = render_result->layers.first;
1516         for (RenderView *render_view = render_result->views.first;
1517              render_view != NULL;
1518              render_view = render_view->next)
1519         {
1520                 RE_SetActiveRenderView(render, render_view->name);
1521                 engine_type->draw_engine->render_to_image(data, engine, render_layer, &render_rect);
1522                 DST.buffer_finish_called = false;
1523         }
1524
1525         RE_engine_end_result(engine, render_result, false, false, false);
1526
1527         /* Force cache to reset. */
1528         drw_viewport_cache_resize();
1529
1530         /* TODO grease pencil */
1531
1532         GPU_viewport_free(DST.viewport);
1533         GPU_framebuffer_restore();
1534
1535         /* Changing Context */
1536         DRW_opengl_context_disable();
1537
1538 #ifdef DEBUG
1539         /* Avoid accidental reuse. */
1540         drw_state_ensure_not_reused(&DST);
1541 #endif
1542 }
1543
1544 void DRW_render_object_iter(
1545         void *vedata, RenderEngine *engine, struct Depsgraph *depsgraph,
1546         void (*callback)(void *vedata, Object *ob, RenderEngine *engine, struct Depsgraph *depsgraph))
1547 {
1548         DRW_hair_init();
1549
1550         DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob, DRW_iterator_mode_get())
1551         {
1552                 DST.ob_state = NULL;
1553                 callback(vedata, ob, engine, depsgraph);
1554         }
1555         DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END
1556
1557         DRW_hair_update();
1558 }
1559
1560 static struct DRWSelectBuffer {
1561         struct GPUFrameBuffer *framebuffer;
1562         struct GPUTexture *texture_depth;
1563 } g_select_buffer = {NULL};
1564
1565 static void draw_select_framebuffer_setup(const rcti *rect)
1566 {
1567         if (g_select_buffer.framebuffer == NULL) {
1568                 g_select_buffer.framebuffer = GPU_framebuffer_create();
1569         }
1570
1571         /* If size mismatch recreate the texture. */
1572         if ((g_select_buffer.texture_depth != NULL) &&
1573             ((GPU_texture_width(g_select_buffer.texture_depth) != BLI_rcti_size_x(rect)) ||
1574              (GPU_texture_height(g_select_buffer.texture_depth) != BLI_rcti_size_y(rect))))
1575         {
1576                 GPU_texture_free(g_select_buffer.texture_depth);
1577                 g_select_buffer.texture_depth = NULL;
1578         }
1579
1580         if (g_select_buffer.texture_depth == NULL) {
1581                 g_select_buffer.texture_depth = GPU_texture_create_2D(
1582                         BLI_rcti_size_x(rect), BLI_rcti_size_y(rect), GPU_DEPTH_COMPONENT24, NULL, NULL);
1583
1584                 GPU_framebuffer_texture_attach(g_select_buffer.framebuffer, g_select_buffer.texture_depth, 0, 0);
1585
1586                 if (!GPU_framebuffer_check_valid(g_select_buffer.framebuffer, NULL)) {
1587                         printf("Error invalid selection framebuffer\n");
1588                 }
1589         }
1590 }
1591
1592 /* Must run after all instance datas have been added. */
1593 void DRW_render_instance_buffer_finish(void)
1594 {
1595         BLI_assert(!DST.buffer_finish_called && "DRW_render_instance_buffer_finish called twice!");
1596         DST.buffer_finish_called = true;
1597         DRW_instance_buffer_finish(DST.idatalist);
1598 }
1599
1600 /**
1601  * object mode select-loop, see: ED_view3d_draw_select_loop (legacy drawing).
1602  */
1603 void DRW_draw_select_loop(
1604         struct Depsgraph *depsgraph,
1605         ARegion *ar, View3D *v3d,
1606         bool UNUSED(use_obedit_skip), bool UNUSED(use_nearest), const rcti *rect,
1607         DRW_SelectPassFn select_pass_fn, void *select_pass_user_data)
1608 {
1609         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1610         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
1611         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1612         Object *obact = OBACT(view_layer);
1613         Object *obedit = OBEDIT_FROM_OBACT(obact);
1614 #ifndef USE_GPU_SELECT
1615         UNUSED_VARS(vc, scene, view_layer, v3d, ar, rect);
1616 #else
1617         RegionView3D *rv3d = ar->regiondata;
1618
1619         /* Reset before using it. */
1620         drw_state_prepare_clean_for_draw(&DST);
1621
1622         bool use_obedit = false;
1623         int obedit_mode = 0;
1624         if (obedit != NULL) {
1625                 if (obedit->type == OB_MBALL) {
1626                         use_obedit = true;
1627                         obedit_mode = CTX_MODE_EDIT_METABALL;
1628                 }
1629                 else if (obedit->type == OB_ARMATURE) {
1630                         use_obedit = true;
1631                         obedit_mode = CTX_MODE_EDIT_ARMATURE;
1632                 }
1633         }
1634         if (v3d->overlay.flag & V3D_OVERLAY_BONE_SELECTION) {
1635                 if (!(v3d->flag2 & V3D_RENDER_OVERRIDE)) {
1636                         Object *obpose = OBPOSE_FROM_OBACT(obact);
1637                         if (obpose) {
1638                                 use_obedit = true;
1639                                 obedit_mode = CTX_MODE_POSE;
1640                         }
1641                 }
1642         }
1643
1644         struct GPUViewport *viewport = GPU_viewport_create();
1645         GPU_viewport_size_set(viewport, (const int[2]){BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)});
1646
1647         DST.viewport = viewport;
1648         v3d->zbuf = true;
1649
1650         DST.options.is_select = true;
1651
1652         /* Get list of enabled engines */
1653         if (use_obedit) {
1654                 drw_engines_enable_from_mode(obedit_mode);
1655         }
1656         else {
1657                 drw_engines_enable_basic();
1658                 drw_engines_enable_from_object_mode();
1659         }
1660
1661         /* Setup viewport */
1662
1663         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
1664         DST.draw_ctx = (DRWContextState){
1665                 .ar = ar, .rv3d = rv3d, .v3d = v3d,
1666                 .scene = scene, .view_layer = view_layer, .obact = obact,
1667                 .engine_type = engine_type,
1668                 .depsgraph = depsgraph,
1669         };
1670         drw_context_state_init();
1671         drw_viewport_var_init();
1672
1673         /* Update ubos */
1674         DRW_globals_update();
1675
1676         /* Init engines */
1677         drw_engines_init();
1678         DRW_hair_init();
1679
1680         {
1681                 drw_engines_cache_init();
1682
1683                 if (use_obedit) {
1684 #if 0
1685                         drw_engines_cache_populate(obact);
1686 #else
1687                         FOREACH_OBJECT_IN_MODE_BEGIN (view_layer, obact->mode, ob_iter) {
1688                                 drw_engines_cache_populate(ob_iter);
1689                         }
1690                         FOREACH_OBJECT_IN_MODE_END;
1691 #endif
1692                 }
1693                 else {
1694                         DEG_OBJECT_ITER_BEGIN(
1695                                 depsgraph, ob, DRW_iterator_mode_get(),
1696                                 DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
1697                                 DEG_ITER_OBJECT_FLAG_VISIBLE |
1698                                 DEG_ITER_OBJECT_FLAG_DUPLI)
1699                         {
1700                                 if ((ob->base_flag & BASE_SELECTABLED) != 0) {
1701                                         /* This relies on dupli instances being after their instancing object. */
1702                                         if ((ob->base_flag & BASE_FROMDUPLI) == 0) {
1703                                                 Object *ob_orig = DEG_get_original_object(ob);
1704                                                 DRW_select_load_id(ob_orig->select_color);
1705                                         }
1706                                         drw_engines_cache_populate(ob);
1707                                 }
1708                         }
1709                         DEG_OBJECT_ITER_END;
1710                 }
1711
1712                 drw_engines_cache_finish();
1713
1714                 DRW_render_instance_buffer_finish();
1715         }
1716
1717         DRW_hair_update();
1718
1719         /* Setup framebuffer */
1720         draw_select_framebuffer_setup(rect);
1721         GPU_framebuffer_bind(g_select_buffer.framebuffer);
1722         GPU_framebuffer_clear_depth(g_select_buffer.framebuffer, 1.0f);
1723
1724         /* Start Drawing */
1725         DRW_state_reset();
1726         DRW_draw_callbacks_pre_scene();
1727
1728         DRW_state_lock(
1729                 DRW_STATE_WRITE_DEPTH |
1730                 DRW_STATE_DEPTH_ALWAYS |
1731                 DRW_STATE_DEPTH_LESS_EQUAL |
1732                 DRW_STATE_DEPTH_EQUAL |
1733                 DRW_STATE_DEPTH_GREATER |
1734                 DRW_STATE_DEPTH_ALWAYS);
1735
1736         /* Only 1-2 passes. */
1737         while (true) {
1738                 if (!select_pass_fn(DRW_SELECT_PASS_PRE, select_pass_user_data)) {
1739                         break;
1740                 }
1741
1742                 drw_engines_draw_scene();
1743
1744                 if (!select_pass_fn(DRW_SELECT_PASS_POST, select_pass_user_data)) {
1745                         break;
1746                 }
1747         }
1748
1749         DRW_state_lock(0);
1750
1751         DRW_draw_callbacks_post_scene();
1752
1753         DRW_state_reset();
1754         drw_engines_disable();
1755
1756 #ifdef DEBUG
1757         /* Avoid accidental reuse. */
1758         drw_state_ensure_not_reused(&DST);
1759 #endif
1760         GPU_framebuffer_restore();
1761
1762         /* Cleanup for selection state */
1763         GPU_viewport_free(viewport);
1764 #endif  /* USE_GPU_SELECT */
1765 }
1766
1767 static void draw_depth_texture_to_screen(GPUTexture *texture)
1768 {
1769         const float w = (float)GPU_texture_width(texture);
1770         const float h = (float)GPU_texture_height(texture);
1771
1772         Gwn_VertFormat *format = immVertexFormat();
1773         uint texcoord = GWN_vertformat_attr_add(format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1774         uint pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1775
1776         immBindBuiltinProgram(GPU_SHADER_3D_IMAGE_DEPTH_COPY);
1777
1778         GPU_texture_bind(texture, 0);
1779
1780         immUniform1i("image", 0); /* default GL_TEXTURE0 unit */
1781
1782         immBegin(GWN_PRIM_TRI_STRIP, 4);
1783
1784         immAttrib2f(texcoord, 0.0f, 0.0f);
1785         immVertex2f(pos, 0.0f, 0.0f);
1786
1787         immAttrib2f(texcoord, 1.0f, 0.0f);
1788         immVertex2f(pos, w, 0.0f);
1789
1790         immAttrib2f(texcoord, 0.0f, 1.0f);
1791         immVertex2f(pos, 0.0f, h);
1792
1793         immAttrib2f(texcoord, 1.0f, 1.0f);
1794         immVertex2f(pos, w, h);
1795
1796         immEnd();
1797
1798         GPU_texture_unbind(texture);
1799
1800         immUnbindProgram();
1801 }
1802
1803 /**
1804  * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
1805  */
1806 void DRW_draw_depth_loop(
1807         Depsgraph *depsgraph,
1808         ARegion *ar, View3D *v3d)
1809 {
1810         Scene *scene = DEG_get_evaluated_scene(depsgraph);
1811         RenderEngineType *engine_type = ED_view3d_engine_type(scene, v3d->drawtype);
1812         ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph);
1813         RegionView3D *rv3d = ar->regiondata;
1814
1815         DRW_opengl_context_enable();
1816
1817         /* Reset before using it. */
1818         drw_state_prepare_clean_for_draw(&DST);
1819
1820         struct GPUViewport *viewport = GPU_viewport_create();
1821         GPU_viewport_size_set(viewport, (const int[2]){ar->winx, ar->winy});
1822
1823         /* Setup framebuffer */
1824         draw_select_framebuffer_setup(&ar->winrct);
1825         GPU_framebuffer_bind(g_select_buffer.framebuffer);
1826         GPU_framebuffer_clear_depth(g_select_buffer.framebuffer, 1.0f);
1827
1828         bool cache_is_dirty;
1829         DST.viewport = viewport;
1830         v3d->zbuf = true;
1831
1832         DST.options.is_depth = true;
1833
1834         /* Get list of enabled engines */
1835         {
1836                 drw_engines_enable_basic();
1837                 drw_engines_enable_from_object_mode();
1838         }
1839
1840         /* Setup viewport */
1841         cache_is_dirty = true;
1842
1843         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
1844         DST.draw_ctx = (DRWContextState){
1845                 .ar = ar, .rv3d = rv3d, .v3d = v3d,
1846                 .scene = scene, .view_layer = view_layer, .obact = OBACT(view_layer),
1847                 .engine_type = engine_type,
1848                 .depsgraph = depsgraph,
1849         };
1850         drw_context_state_init();
1851         drw_viewport_var_init();
1852
1853         /* Update ubos */
1854         DRW_globals_update();
1855
1856         /* Init engines */
1857         drw_engines_init();
1858         DRW_hair_init();
1859
1860         /* TODO : tag to refresh by the dependency graph */
1861         /* ideally only refresh when objects are added/removed */
1862         /* or render properties / materials change */
1863         if (cache_is_dirty) {
1864                 drw_engines_cache_init();
1865
1866                 DEG_OBJECT_ITER_FOR_RENDER_ENGINE_BEGIN(depsgraph, ob, DRW_iterator_mode_get())
1867                 {
1868                         drw_engines_cache_populate(ob);
1869                 }
1870                 DEG_OBJECT_ITER_FOR_RENDER_ENGINE_END;
1871
1872                 drw_engines_cache_finish();
1873
1874                 DRW_render_instance_buffer_finish();
1875         }
1876
1877         DRW_hair_update();
1878
1879         /* Start Drawing */
1880         DRW_state_reset();
1881         DRW_draw_callbacks_pre_scene();
1882         drw_engines_draw_scene();
1883         DRW_draw_callbacks_post_scene();
1884
1885         DRW_state_reset();
1886         drw_engines_disable();
1887
1888 #ifdef DEBUG
1889         /* Avoid accidental reuse. */
1890         drw_state_ensure_not_reused(&DST);
1891 #endif
1892
1893         /* TODO: Reading depth for operators should be done here. */
1894
1895         GPU_framebuffer_restore();
1896
1897         /* Cleanup for selection state */
1898         GPU_viewport_free(viewport);
1899
1900         /* Changin context */
1901         DRW_opengl_context_disable();
1902
1903         /* XXX Drawing the resulting buffer to the BACK_BUFFER */
1904         gpuPushMatrix();
1905         gpuPushProjectionMatrix();
1906         wmOrtho2_region_pixelspace(ar);
1907         gpuLoadIdentity();
1908
1909         glEnable(GL_DEPTH_TEST); /* Cannot write to depth buffer without testing */
1910         glDepthFunc(GL_ALWAYS);
1911         draw_depth_texture_to_screen(g_select_buffer.texture_depth);
1912         glDepthFunc(GL_LEQUAL);
1913
1914         gpuPopMatrix();
1915         gpuPopProjectionMatrix();
1916 }
1917
1918 /** \} */
1919
1920
1921 /* -------------------------------------------------------------------- */
1922
1923 /** \name Draw Manager State (DRW_state)
1924  * \{ */
1925
1926 void DRW_state_dfdy_factors_get(float dfdyfac[2])
1927 {
1928         GPU_get_dfdy_factors(dfdyfac);
1929 }
1930
1931 /**
1932  * When false, drawing doesn't output to a pixel buffer
1933  * eg: Occlusion queries, or when we have setup a context to draw in already.
1934  */
1935 bool DRW_state_is_fbo(void)
1936 {
1937         return ((DST.default_framebuffer != NULL) || DST.options.is_image_render);
1938 }
1939
1940 /**
1941  * For when engines need to know if this is drawing for selection or not.
1942  */
1943 bool DRW_state_is_select(void)
1944 {
1945         return DST.options.is_select;
1946 }
1947
1948 bool DRW_state_is_depth(void)
1949 {
1950         return DST.options.is_depth;
1951 }
1952
1953 /**
1954  * Whether we are rendering for an image
1955  */
1956 bool DRW_state_is_image_render(void)
1957 {
1958         return DST.options.is_image_render;
1959 }
1960
1961 /**
1962  * Whether we are rendering only the render engine,
1963  * or if we should also render the mode engines.
1964  */
1965 bool DRW_state_is_scene_render(void)
1966 {
1967         BLI_assert(DST.options.is_scene_render ?
1968                    DST.options.is_image_render : true);
1969         return DST.options.is_scene_render;
1970 }
1971
1972 /**
1973 * Whether we are rendering simple opengl render
1974 */
1975 bool DRW_state_is_opengl_render(void)
1976 {
1977         return DST.options.is_image_render && !DST.options.is_scene_render;
1978 }
1979
1980 /**
1981  * Gives you the iterator mode to use for depsgraph.
1982  */
1983 eDepsObjectIteratorMode DRW_iterator_mode_get(void)
1984 {
1985         return DRW_state_is_scene_render() ? DEG_ITER_OBJECT_MODE_RENDER :
1986                                              DEG_ITER_OBJECT_MODE_VIEWPORT;
1987 }
1988
1989 /**
1990  * Should text draw in this mode?
1991  */
1992 bool DRW_state_show_text(void)
1993 {
1994         return (DST.options.is_select) == 0 &&
1995                (DST.options.is_depth) == 0 &&
1996                (DST.options.is_scene_render) == 0 &&
1997                (DST.options.draw_text) == 0;
1998 }
1999
2000 /**
2001  * Should draw support elements
2002  * Objects center, selection outline, probe data, ...
2003  */
2004 bool DRW_state_draw_support(void)
2005 {
2006         View3D *v3d = DST.draw_ctx.v3d;
2007         return (DRW_state_is_scene_render() == false) &&
2008                 (v3d != NULL) &&
2009                 ((v3d->flag2 & V3D_RENDER_OVERRIDE) == 0);
2010 }
2011
2012 /**
2013  * Whether we should render the background
2014  */
2015 bool DRW_state_draw_background(void)
2016 {
2017         if (DRW_state_is_image_render() == false) {
2018                 return true;
2019         }
2020         return DST.options.draw_background;
2021 }
2022
2023 /** \} */
2024
2025
2026 /* -------------------------------------------------------------------- */
2027
2028 /** \name Context State (DRW_context_state)
2029  * \{ */
2030
2031 const DRWContextState *DRW_context_state_get(void)
2032 {
2033         return &DST.draw_ctx;
2034 }
2035
2036 /** \} */
2037
2038
2039 /* -------------------------------------------------------------------- */
2040
2041 /** \name Init/Exit (DRW_engines)
2042  * \{ */
2043
2044 bool DRW_engine_render_support(DrawEngineType *draw_engine_type)
2045 {
2046         return draw_engine_type->render_to_image;
2047 }
2048
2049 void DRW_engine_register(DrawEngineType *draw_engine_type)
2050 {
2051         BLI_addtail(&DRW_engines, draw_engine_type);
2052 }
2053
2054 void DRW_engines_register(void)
2055 {
2056 #ifdef WITH_CLAY_ENGINE
2057         RE_engines_register(&DRW_engine_viewport_clay_type);
2058 #endif
2059         RE_engines_register(&DRW_engine_viewport_eevee_type);
2060         RE_engines_register(&DRW_engine_viewport_workbench_type);
2061
2062         DRW_engine_register(&draw_engine_workbench_solid);
2063         DRW_engine_register(&draw_engine_workbench_transparent);
2064
2065         DRW_engine_register(&draw_engine_object_type);
2066         DRW_engine_register(&draw_engine_edit_armature_type);
2067         DRW_engine_register(&draw_engine_edit_curve_type);
2068         DRW_engine_register(&draw_engine_edit_lattice_type);
2069         DRW_engine_register(&draw_engine_edit_mesh_type);
2070         DRW_engine_register(&draw_engine_edit_metaball_type);
2071         DRW_engine_register(&draw_engine_edit_surface_type);
2072         DRW_engine_register(&draw_engine_edit_text_type);
2073         DRW_engine_register(&draw_engine_motion_path_type);
2074         DRW_engine_register(&draw_engine_overlay_type);
2075         DRW_engine_register(&draw_engine_paint_texture_type);
2076         DRW_engine_register(&draw_engine_paint_vertex_type);
2077         DRW_engine_register(&draw_engine_paint_weight_type);
2078         DRW_engine_register(&draw_engine_particle_type);
2079         DRW_engine_register(&draw_engine_pose_type);
2080         DRW_engine_register(&draw_engine_sculpt_type);
2081
2082         /* setup callbacks */
2083         {
2084                 /* BKE: mball.c */
2085                 extern void *BKE_mball_batch_cache_dirty_cb;
2086                 extern void *BKE_mball_batch_cache_free_cb;
2087                 /* BKE: curve.c */
2088                 extern void *BKE_curve_batch_cache_dirty_cb;
2089                 extern void *BKE_curve_batch_cache_free_cb;
2090                 /* BKE: mesh.c */
2091                 extern void *BKE_mesh_batch_cache_dirty_cb;
2092                 extern void *BKE_mesh_batch_cache_free_cb;
2093                 /* BKE: lattice.c */
2094                 extern void *BKE_lattice_batch_cache_dirty_cb;
2095                 extern void *BKE_lattice_batch_cache_free_cb;
2096                 /* BKE: particle.c */
2097                 extern void *BKE_particle_batch_cache_dirty_cb;
2098                 extern void *BKE_particle_batch_cache_free_cb;
2099
2100                 BKE_mball_batch_cache_dirty_cb = DRW_mball_batch_cache_dirty;
2101                 BKE_mball_batch_cache_free_cb = DRW_mball_batch_cache_free;
2102
2103                 BKE_curve_batch_cache_dirty_cb = DRW_curve_batch_cache_dirty;
2104                 BKE_curve_batch_cache_free_cb = DRW_curve_batch_cache_free;
2105
2106                 BKE_mesh_batch_cache_dirty_cb = DRW_mesh_batch_cache_dirty;
2107                 BKE_mesh_batch_cache_free_cb = DRW_mesh_batch_cache_free;
2108
2109                 BKE_lattice_batch_cache_dirty_cb = DRW_lattice_batch_cache_dirty;
2110                 BKE_lattice_batch_cache_free_cb = DRW_lattice_batch_cache_free;
2111
2112                 BKE_particle_batch_cache_dirty_cb = DRW_particle_batch_cache_dirty;
2113                 BKE_particle_batch_cache_free_cb = DRW_particle_batch_cache_free;
2114         }
2115 }
2116
2117 extern struct Gwn_VertFormat *g_pos_format; /* draw_shgroup.c */
2118 extern struct GPUUniformBuffer *globals_ubo; /* draw_common.c */
2119 extern struct GPUTexture *globals_ramp; /* draw_common.c */
2120 void DRW_engines_free(void)
2121 {
2122         DRW_opengl_context_enable();
2123
2124         DRW_TEXTURE_FREE_SAFE(g_select_buffer.texture_depth);
2125         GPU_FRAMEBUFFER_FREE_SAFE(g_select_buffer.framebuffer);
2126
2127         DRW_hair_free();
2128         DRW_shape_cache_free();
2129         DRW_stats_free();
2130         DRW_globals_free();
2131
2132         DrawEngineType *next;
2133         for (DrawEngineType *type = DRW_engines.first; type; type = next) {
2134                 next = type->next;
2135                 BLI_remlink(&R_engines, type);
2136
2137                 if (type->engine_free) {
2138                         type->engine_free();
2139                 }
2140         }
2141
2142         DRW_UBO_FREE_SAFE(globals_ubo);
2143         DRW_UBO_FREE_SAFE(view_ubo);
2144         DRW_TEXTURE_FREE_SAFE(globals_ramp);
2145         MEM_SAFE_FREE(g_pos_format);
2146
2147         MEM_SAFE_FREE(DST.RST.bound_texs);
2148         MEM_SAFE_FREE(DST.RST.bound_tex_slots);
2149         MEM_SAFE_FREE(DST.RST.bound_ubos);
2150         MEM_SAFE_FREE(DST.RST.bound_ubo_slots);
2151
2152         DRW_opengl_context_disable();
2153
2154 #ifdef WITH_CLAY_ENGINE
2155         BLI_remlink(&R_engines, &DRW_engine_viewport_clay_type);
2156 #endif
2157 }
2158
2159 /** \} */
2160
2161 /** \name Init/Exit (DRW_opengl_ctx)
2162  * \{ */
2163
2164 void DRW_opengl_context_create(void)
2165 {
2166         BLI_assert(DST.ogl_context == NULL); /* Ensure it's called once */
2167
2168         BLI_mutex_init(&DST.ogl_context_mutex);
2169         if (!G.background) {
2170                 immDeactivate();
2171         }
2172         /* This changes the active context. */
2173         DST.ogl_context = WM_opengl_context_create();
2174         /* Be sure to create gawain.context too. */
2175         DST.gwn_context = GWN_context_create();
2176         if (!G.background) {
2177                 immActivate();
2178         }
2179         /* Set default Blender OpenGL state */
2180         GPU_state_init();
2181         /* So we activate the window's one afterwards. */
2182         wm_window_reset_drawable();
2183 }
2184
2185 void DRW_opengl_context_destroy(void)
2186 {
2187         BLI_assert(BLI_thread_is_main());
2188         if (DST.ogl_context != NULL) {
2189                 WM_opengl_context_activate(DST.ogl_context);
2190                 GWN_context_active_set(DST.gwn_context);
2191                 GWN_context_discard(DST.gwn_context);
2192                 WM_opengl_context_dispose(DST.ogl_context);
2193                 BLI_mutex_end(&DST.ogl_context_mutex);
2194         }
2195 }
2196
2197 void DRW_opengl_context_enable(void)
2198 {
2199         if (DST.ogl_context != NULL) {
2200                 /* IMPORTANT: We dont support immediate mode in render mode!
2201                  * This shall remain in effect until immediate mode supports
2202                  * multiple threads. */
2203                 BLI_mutex_lock(&DST.ogl_context_mutex);
2204                 if (BLI_thread_is_main()) {
2205                         if (!G.background) {
2206                                 immDeactivate();
2207                         }
2208                 }
2209                 WM_opengl_context_activate(DST.ogl_context);
2210                 GWN_context_active_set(DST.gwn_context);
2211                 if (BLI_thread_is_main()) {
2212                         if (!G.background) {
2213                                 immActivate();
2214                         }
2215                         BLF_batch_reset();
2216                 }
2217         }
2218 }
2219
2220 void DRW_opengl_context_disable(void)
2221 {
2222         if (DST.ogl_context != NULL) {
2223 #ifdef __APPLE__
2224                 /* Need to flush before disabling draw context, otherwise it does not
2225                  * always finish drawing and viewport can be empty or partially drawn */
2226                 glFlush();
2227 #endif
2228
2229                 if (BLI_thread_is_main()) {
2230                         wm_window_reset_drawable();
2231                 }
2232                 else {
2233                         WM_opengl_context_release(DST.ogl_context);
2234                         GWN_context_active_set(NULL);
2235                 }
2236
2237                 BLI_mutex_unlock(&DST.ogl_context_mutex);
2238         }
2239 }
2240
2241 /** \} */