b5ed450cb0a9f8dcfb87605ff6276458f4188bb3
[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_dynstr.h"
29 #include "BLI_listbase.h"
30 #include "BLI_rect.h"
31 #include "BLI_string.h"
32
33 #include "BIF_glutil.h"
34
35 #include "BKE_global.h"
36
37 #include "BLT_translation.h"
38 #include "BLF_api.h"
39
40 #include "DRW_engine.h"
41 #include "DRW_render.h"
42
43 #include "DNA_view3d_types.h"
44 #include "DNA_screen_types.h"
45
46 #include "ED_space_api.h"
47 #include "ED_screen.h"
48
49 #include "GPU_batch.h"
50 #include "GPU_draw.h"
51 #include "GPU_extensions.h"
52 #include "GPU_framebuffer.h"
53 #include "GPU_lamp.h"
54 #include "GPU_shader.h"
55 #include "GPU_texture.h"
56 #include "GPU_uniformbuffer.h"
57 #include "GPU_viewport.h"
58 #include "GPU_matrix.h"
59
60 #include "PIL_time.h"
61
62 #include "RE_engine.h"
63
64 #include "UI_resources.h"
65
66 #include "draw_mode_engines.h"
67 #include "clay.h"
68 #include "eevee.h"
69
70 #define MAX_ATTRIB_NAME 32
71 #define MAX_PASS_NAME 32
72
73 extern char datatoc_gpu_shader_2D_vert_glsl[];
74 extern char datatoc_gpu_shader_3D_vert_glsl[];
75 extern char datatoc_gpu_shader_fullscreen_vert_glsl[];
76
77 /* Structures */
78 typedef enum {
79         DRW_UNIFORM_BOOL,
80         DRW_UNIFORM_INT,
81         DRW_UNIFORM_FLOAT,
82         DRW_UNIFORM_TEXTURE,
83         DRW_UNIFORM_BUFFER,
84         DRW_UNIFORM_MAT3,
85         DRW_UNIFORM_MAT4,
86         DRW_UNIFORM_BLOCK
87 } DRWUniformType;
88
89 typedef enum {
90         DRW_ATTRIB_INT,
91         DRW_ATTRIB_FLOAT,
92 } DRWAttribType;
93
94 struct DRWUniform {
95         struct DRWUniform *next, *prev;
96         DRWUniformType type;
97         int location;
98         int length;
99         int arraysize;
100         int bindloc;
101         const void *value;
102 };
103
104 typedef struct DRWAttrib {
105         struct DRWAttrib *next, *prev;
106         char name[MAX_ATTRIB_NAME];
107         int location;
108         int format_id;
109         int size; /* number of component */
110         int type;
111 } DRWAttrib;
112
113 struct DRWInterface {
114         ListBase uniforms;   /* DRWUniform */
115         ListBase attribs;    /* DRWAttrib */
116         int attribs_count;
117         int attribs_stride;
118         int attribs_size[16];
119         int attribs_loc[16];
120         /* matrices locations */
121         int model;
122         int modelview;
123         int projection;
124         int view;
125         int modelviewprojection;
126         int viewprojection;
127         int normal;
128         int worldnormal;
129         int eye;
130         /* Dynamic batch */
131         GLuint instance_vbo;
132         int instance_count;
133         VertexFormat vbo_format;
134 };
135
136 struct DRWPass {
137         ListBase shgroups; /* DRWShadingGroup */
138         DRWState state;
139         char name[MAX_PASS_NAME];
140         /* use two query to not stall the cpu waiting for queries to complete */
141         unsigned int timer_queries[2];
142         /* alternate between front and back query */
143         unsigned int front_idx;
144         unsigned int back_idx;
145         bool wasdrawn; /* if it was drawn during this frame */
146 };
147
148 typedef struct DRWCall {
149         struct DRWCall *next, *prev;
150         Batch *geometry;
151         float (*obmat)[4];
152 } DRWCall;
153
154 typedef struct DRWDynamicCall {
155         struct DRWDynamicCall *next, *prev;
156         const void *data[];
157 } DRWDynamicCall;
158
159 struct DRWShadingGroup {
160         struct DRWShadingGroup *next, *prev;
161
162         struct GPUShader *shader;        /* Shader to bind */
163         struct DRWInterface *interface;  /* Uniforms pointers */
164         ListBase calls;                  /* DRWCall or DRWDynamicCall depending of type*/
165         DRWState state;                  /* State changes for this batch only */
166         int type;
167
168         Batch *instance_geom;  /* Geometry to instance */
169         Batch *batch_geom;     /* Result of call batching */
170 };
171
172 /* Used by DRWShadingGroup.type */
173 enum {
174         DRW_SHG_NORMAL,
175         DRW_SHG_POINT_BATCH,
176         DRW_SHG_LINE_BATCH,
177         DRW_SHG_INSTANCE,
178 };
179
180 /* only 16 bits long */
181 enum {
182         STENCIL_SELECT          = (1 << 0),
183         STENCIL_ACTIVE          = (1 << 1),
184 };
185
186 /* Render State */
187 static struct DRWGlobalState {
188         /* Rendering state */
189         GPUShader *shader;
190         ListBase bound_texs;
191         int tex_bind_id;
192
193         /* Per viewport */
194         GPUViewport *viewport;
195         struct GPUFrameBuffer *default_framebuffer;
196         float size[2];
197         float screenvecs[2][3];
198         float pixsize;
199
200         /* Current rendering context */
201         const struct bContext *context;
202         ListBase enabled_engines; /* RenderEngineType */
203 } DST = {NULL};
204
205 ListBase DRW_engines = {NULL, NULL};
206
207 /* ***************************************** TEXTURES ******************************************/
208 static void drw_texture_get_format(DRWTextureFormat format, GPUTextureFormat *data_type, int *channels)
209 {
210         switch (format) {
211                 case DRW_TEX_RGBA_8: *data_type = GPU_RGBA8; break;
212                 case DRW_TEX_RGBA_16: *data_type = GPU_RGBA16F; break;
213                 case DRW_TEX_RG_16: *data_type = GPU_RG16F; break;
214                 case DRW_TEX_RG_32: *data_type = GPU_RG32F; break;
215                 case DRW_TEX_R_8: *data_type = GPU_R8; break;
216                 case DRW_TEX_R_16: *data_type = GPU_R16F; break;
217 #if 0
218                 case DRW_TEX_RGBA_32: *data_type = GPU_RGBA32F; break;
219                 case DRW_TEX_RGB_8: *data_type = GPU_RGB8; break;
220                 case DRW_TEX_RGB_16: *data_type = GPU_RGB16F; break;
221                 case DRW_TEX_RGB_32: *data_type = GPU_RGB32F; break;
222                 case DRW_TEX_RG_8: *data_type = GPU_RG8; break;
223                 case DRW_TEX_R_32: *data_type = GPU_R32F; break;
224 #endif
225                 case DRW_TEX_DEPTH_16: *data_type = GPU_DEPTH_COMPONENT16; break;
226                 case DRW_TEX_DEPTH_24: *data_type = GPU_DEPTH_COMPONENT24; break;
227                 case DRW_TEX_DEPTH_32: *data_type = GPU_DEPTH_COMPONENT32F; break;
228                 default :
229                         /* file type not supported you must uncomment it from above */
230                         BLI_assert(false);
231                         break;
232         }
233
234         switch (format) {
235                 case DRW_TEX_RGBA_8:
236                 case DRW_TEX_RGBA_16:
237                 case DRW_TEX_RGBA_32:
238                         *channels = 4;
239                         break;
240                 case DRW_TEX_RGB_8:
241                 case DRW_TEX_RGB_16:
242                 case DRW_TEX_RGB_32:
243                         *channels = 3;
244                         break;
245                 case DRW_TEX_RG_8:
246                 case DRW_TEX_RG_16:
247                 case DRW_TEX_RG_32:
248                         *channels = 2;
249                         break;
250                 default:
251                         *channels = 1;
252                         break;
253         }
254 }
255
256 static void drw_texture_set_parameters(GPUTexture *tex, DRWTextureFlag flags)
257 {
258         GPU_texture_bind(tex, 0);
259         GPU_texture_filter_mode(tex, flags & DRW_TEX_FILTER);
260         GPU_texture_wrap_mode(tex, flags & DRW_TEX_WRAP);
261         GPU_texture_compare_mode(tex, flags & DRW_TEX_COMPARE);
262         GPU_texture_unbind(tex);
263 }
264
265 GPUTexture *DRW_texture_create_1D(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
266 {
267         GPUTexture *tex;
268         GPUTextureFormat data_type;
269         int channels;
270
271         drw_texture_get_format(format, &data_type, &channels);
272         tex = GPU_texture_create_1D_custom(w, channels, data_type, fpixels, NULL);
273         drw_texture_set_parameters(tex, flags);
274
275         return tex;
276 }
277
278 GPUTexture *DRW_texture_create_2D(int w, int h, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
279 {
280         GPUTexture *tex;
281         GPUTextureFormat data_type;
282         int channels;
283
284         drw_texture_get_format(format, &data_type, &channels);
285         tex = GPU_texture_create_2D_custom(w, h, channels, data_type, fpixels, NULL);
286         drw_texture_set_parameters(tex, flags);
287
288         return tex;
289 }
290
291 GPUTexture *DRW_texture_create_2D_array(int w, int h, int d, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
292 {
293         GPUTexture *tex;
294         GPUTextureFormat data_type;
295         int channels;
296
297         drw_texture_get_format(format, &data_type, &channels);
298         tex = GPU_texture_create_2D_array_custom(w, h, d, channels, data_type, fpixels, NULL);
299         drw_texture_set_parameters(tex, flags);
300
301         return tex;
302 }
303
304 GPUTexture *DRW_texture_create_cube(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
305 {
306         GPUTexture *tex;
307         GPUTextureFormat data_type;
308         int channels;
309
310         drw_texture_get_format(format, &data_type, &channels);
311         tex = GPU_texture_create_cube_custom(w, channels, data_type, fpixels, NULL);
312         drw_texture_set_parameters(tex, flags);
313
314         return tex;
315 }
316
317 void DRW_texture_free(GPUTexture *tex)
318 {
319         GPU_texture_free(tex);
320 }
321
322
323 /* ************************************ UNIFORM BUFFER OBJECT **********************************/
324
325 GPUUniformBuffer *DRW_uniformbuffer_create(int size, const void *data)
326 {
327         return GPU_uniformbuffer_create(size, data, NULL);
328 }
329
330 void DRW_uniformbuffer_update(GPUUniformBuffer *ubo, const void *data)
331 {
332         GPU_uniformbuffer_update(ubo, data);
333 }
334
335 void DRW_uniformbuffer_free(GPUUniformBuffer *ubo)
336 {
337         GPU_uniformbuffer_free(ubo);
338 }
339
340 /* ****************************************** SHADERS ******************************************/
341
342 GPUShader *DRW_shader_create(const char *vert, const char *geom, const char *frag, const char *defines)
343 {
344         return GPU_shader_create(vert, frag, geom, NULL, defines);
345 }
346
347 GPUShader *DRW_shader_create_with_lib(const char *vert, const char *geom, const char *frag, const char *lib, const char *defines)
348 {
349         GPUShader *sh;
350         char *vert_with_lib = NULL;
351         char *frag_with_lib = NULL;
352         char *geom_with_lib = NULL;
353
354         DynStr *ds_vert = BLI_dynstr_new();
355         BLI_dynstr_append(ds_vert, lib);
356         BLI_dynstr_append(ds_vert, vert);
357         vert_with_lib = BLI_dynstr_get_cstring(ds_vert);
358         BLI_dynstr_free(ds_vert);
359
360         DynStr *ds_frag = BLI_dynstr_new();
361         BLI_dynstr_append(ds_frag, lib);
362         BLI_dynstr_append(ds_frag, frag);
363         frag_with_lib = BLI_dynstr_get_cstring(ds_frag);
364         BLI_dynstr_free(ds_frag);
365
366         if (geom) {
367                 DynStr *ds_geom = BLI_dynstr_new();
368                 BLI_dynstr_append(ds_geom, lib);
369                 BLI_dynstr_append(ds_geom, geom);
370                 geom_with_lib = BLI_dynstr_get_cstring(ds_geom);
371                 BLI_dynstr_free(ds_geom);
372         }
373
374         sh = GPU_shader_create(vert_with_lib, frag_with_lib, geom_with_lib, NULL, defines);
375
376         MEM_freeN(vert_with_lib);
377         MEM_freeN(frag_with_lib);
378         if (geom) {
379                 MEM_freeN(geom_with_lib);
380         }
381
382         return sh;
383 }
384
385 GPUShader *DRW_shader_create_2D(const char *frag, const char *defines)
386 {
387         return GPU_shader_create(datatoc_gpu_shader_2D_vert_glsl, frag, NULL, NULL, defines);
388 }
389
390 GPUShader *DRW_shader_create_3D(const char *frag, const char *defines)
391 {
392         return GPU_shader_create(datatoc_gpu_shader_3D_vert_glsl, frag, NULL, NULL, defines);
393 }
394
395 GPUShader *DRW_shader_create_fullscreen(const char *frag, const char *defines)
396 {
397         return GPU_shader_create(datatoc_gpu_shader_fullscreen_vert_glsl, frag, NULL, NULL, defines);
398 }
399
400 GPUShader *DRW_shader_create_3D_depth_only(void)
401 {
402         return GPU_shader_get_builtin_shader(GPU_SHADER_3D_DEPTH_ONLY);
403 }
404
405 void DRW_shader_free(GPUShader *shader)
406 {
407         GPU_shader_free(shader);
408 }
409
410 /* ***************************************** INTERFACE ******************************************/
411
412 static DRWInterface *DRW_interface_create(GPUShader *shader)
413 {
414         DRWInterface *interface = MEM_mallocN(sizeof(DRWInterface), "DRWInterface");
415
416         interface->model = GPU_shader_get_uniform(shader, "ModelMatrix");
417         interface->modelview = GPU_shader_get_uniform(shader, "ModelViewMatrix");
418         interface->projection = GPU_shader_get_uniform(shader, "ProjectionMatrix");
419         interface->view = GPU_shader_get_uniform(shader, "ViewMatrix");
420         interface->viewprojection = GPU_shader_get_uniform(shader, "ViewProjectionMatrix");
421         interface->modelviewprojection = GPU_shader_get_uniform(shader, "ModelViewProjectionMatrix");
422         interface->normal = GPU_shader_get_uniform(shader, "NormalMatrix");
423         interface->worldnormal = GPU_shader_get_uniform(shader, "WorldNormalMatrix");
424         interface->eye = GPU_shader_get_uniform(shader, "eye");
425         interface->instance_count = 0;
426         interface->attribs_count = 0;
427         interface->attribs_stride = 0;
428         interface->instance_vbo = 0;
429
430         memset(&interface->vbo_format, 0, sizeof(VertexFormat));
431
432         BLI_listbase_clear(&interface->uniforms);
433         BLI_listbase_clear(&interface->attribs);
434
435         return interface;
436 }
437
438 static void DRW_interface_uniform(DRWShadingGroup *shgroup, const char *name,
439                                   DRWUniformType type, const void *value, int length, int arraysize, int bindloc)
440 {
441         DRWUniform *uni = MEM_mallocN(sizeof(DRWUniform), "DRWUniform");
442
443         if (type == DRW_UNIFORM_BLOCK) {
444                 uni->location = GPU_shader_get_uniform_block(shgroup->shader, name);
445         }
446         else {
447                 uni->location = GPU_shader_get_uniform(shgroup->shader, name);
448         }
449
450         uni->type = type;
451         uni->value = value;
452         uni->length = length;
453         uni->arraysize = arraysize;
454         uni->bindloc = bindloc; /* for textures */
455
456         if (uni->location == -1) {
457                 if (G.debug & G_DEBUG)
458                         fprintf(stderr, "Uniform '%s' not found!\n", name);
459
460                 MEM_freeN(uni);
461                 return;
462         }
463
464         BLI_addtail(&shgroup->interface->uniforms, uni);
465 }
466
467 static void DRW_interface_attrib(DRWShadingGroup *shgroup, const char *name, DRWAttribType type, int size)
468 {
469         DRWAttrib *attrib = MEM_mallocN(sizeof(DRWAttrib), "DRWAttrib");
470         GLuint program = GPU_shader_get_program(shgroup->shader);
471
472         attrib->location = glGetAttribLocation(program, name);
473         attrib->type = type;
474         attrib->size = size;
475
476         if (attrib->location == -1) {
477                 if (G.debug & G_DEBUG)
478                         fprintf(stderr, "Attribute '%s' not found!\n", name);
479
480                 MEM_freeN(attrib);
481                 return;
482         }
483
484         BLI_assert(BLI_strnlen(name, 32) < 32);
485         BLI_strncpy(attrib->name, name, 32);
486
487         shgroup->interface->attribs_count += 1;
488
489         BLI_addtail(&shgroup->interface->attribs, attrib);
490 }
491
492 void DRW_get_dfdy_factors(float dfdyfac[2])
493 {
494         GPU_get_dfdy_factors(dfdyfac);
495 }
496
497 /* ***************************************** SHADING GROUP ******************************************/
498
499 DRWShadingGroup *DRW_shgroup_create(struct GPUShader *shader, DRWPass *pass)
500 {
501         DRWShadingGroup *shgroup = MEM_mallocN(sizeof(DRWShadingGroup), "DRWShadingGroup");
502
503         shgroup->type = DRW_SHG_NORMAL;
504         shgroup->shader = shader;
505         shgroup->interface = DRW_interface_create(shader);
506         shgroup->state = 0;
507         shgroup->batch_geom = NULL;
508         shgroup->instance_geom = NULL;
509
510         BLI_addtail(&pass->shgroups, shgroup);
511         BLI_listbase_clear(&shgroup->calls);
512
513         return shgroup;
514 }
515
516 DRWShadingGroup *DRW_shgroup_instance_create(struct GPUShader *shader, DRWPass *pass, Batch *geom)
517 {
518         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
519
520         shgroup->type = DRW_SHG_INSTANCE;
521         shgroup->instance_geom = geom;
522
523         return shgroup;
524 }
525
526 DRWShadingGroup *DRW_shgroup_point_batch_create(struct GPUShader *shader, DRWPass *pass)
527 {
528         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
529
530         shgroup->type = DRW_SHG_POINT_BATCH;
531         DRW_shgroup_attrib_float(shgroup, "pos", 3);
532
533         return shgroup;
534 }
535
536 DRWShadingGroup *DRW_shgroup_line_batch_create(struct GPUShader *shader, DRWPass *pass)
537 {
538         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
539
540         shgroup->type = DRW_SHG_LINE_BATCH;
541         DRW_shgroup_attrib_float(shgroup, "pos", 3);
542
543         return shgroup;
544 }
545
546 void DRW_shgroup_free(struct DRWShadingGroup *shgroup)
547 {
548         BLI_freelistN(&shgroup->calls);
549         BLI_freelistN(&shgroup->interface->uniforms);
550         BLI_freelistN(&shgroup->interface->attribs);
551
552         if (shgroup->interface->instance_vbo) {
553                 glDeleteBuffers(1, &shgroup->interface->instance_vbo);
554         }
555
556         MEM_freeN(shgroup->interface);
557
558         if (shgroup->batch_geom) {
559                 Batch_discard_all(shgroup->batch_geom);
560         }
561 }
562
563 void DRW_shgroup_call_add(DRWShadingGroup *shgroup, Batch *geom, float (*obmat)[4])
564 {
565         BLI_assert(geom != NULL);
566
567         DRWCall *call = MEM_callocN(sizeof(DRWCall), "DRWCall");
568
569         call->obmat = obmat;
570         call->geometry = geom;
571
572         BLI_addtail(&shgroup->calls, call);
573 }
574
575 void DRW_shgroup_dynamic_call_add(DRWShadingGroup *shgroup, ...)
576 {
577         va_list params;
578         int i;
579         DRWInterface *interface = shgroup->interface;
580         int size = sizeof(ListBase) + sizeof(void *) * interface->attribs_count;
581
582         DRWDynamicCall *call = MEM_callocN(size, "DRWDynamicCall");
583
584         va_start(params, shgroup);
585         for (i = 0; i < interface->attribs_count; ++i) {
586                 call->data[i] = va_arg(params, void *);
587         }
588         va_end(params);
589
590         interface->instance_count += 1;
591
592         BLI_addtail(&shgroup->calls, call);
593 }
594
595 /* Make sure you know what you do when using this,
596  * State is not revert back at the end of the shgroup */
597 void DRW_shgroup_state_set(DRWShadingGroup *shgroup, DRWState state)
598 {
599         shgroup->state = state;
600 }
601
602 void DRW_shgroup_attrib_float(DRWShadingGroup *shgroup, const char *name, int size)
603 {
604         DRW_interface_attrib(shgroup, name, DRW_ATTRIB_FLOAT, size);
605 }
606
607 void DRW_shgroup_uniform_texture(DRWShadingGroup *shgroup, const char *name, const GPUTexture *tex, int loc)
608 {
609         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_TEXTURE, tex, 0, 0, loc);
610 }
611
612 void DRW_shgroup_uniform_block(DRWShadingGroup *shgroup, const char *name, const GPUUniformBuffer *ubo, int loc)
613 {
614         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BLOCK, ubo, 0, 0, loc);
615 }
616
617 void DRW_shgroup_uniform_buffer(DRWShadingGroup *shgroup, const char *name, GPUTexture **tex, int loc)
618 {
619         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BUFFER, tex, 0, 0, loc);
620 }
621
622 void DRW_shgroup_uniform_bool(DRWShadingGroup *shgroup, const char *name, const bool *value, int arraysize)
623 {
624         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BOOL, value, 1, arraysize, 0);
625 }
626
627 void DRW_shgroup_uniform_float(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
628 {
629         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 1, arraysize, 0);
630 }
631
632 void DRW_shgroup_uniform_vec2(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
633 {
634         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 2, arraysize, 0);
635 }
636
637 void DRW_shgroup_uniform_vec3(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
638 {
639         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 3, arraysize, 0);
640 }
641
642 void DRW_shgroup_uniform_vec4(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
643 {
644         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 4, arraysize, 0);
645 }
646
647 void DRW_shgroup_uniform_int(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
648 {
649         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 1, arraysize, 0);
650 }
651
652 void DRW_shgroup_uniform_ivec2(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
653 {
654         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 2, arraysize, 0);
655 }
656
657 void DRW_shgroup_uniform_ivec3(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
658 {
659         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 3, arraysize, 0);
660 }
661
662 void DRW_shgroup_uniform_mat3(DRWShadingGroup *shgroup, const char *name, const float *value)
663 {
664         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT3, value, 9, 1, 0);
665 }
666
667 void DRW_shgroup_uniform_mat4(DRWShadingGroup *shgroup, const char *name, const float *value)
668 {
669         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT4, value, 16, 1, 0);
670 }
671
672 #ifdef WITH_CLAY_ENGINE
673
674 /* Creates a VBO containing OGL primitives for all DRWDynamicCall */
675 static void shgroup_dynamic_batch(DRWShadingGroup *shgroup)
676 {
677         DRWInterface *interface = shgroup->interface;
678         int nbr = interface->instance_count;
679
680         PrimitiveType type = (shgroup->type == DRW_SHG_POINT_BATCH) ? PRIM_POINTS : PRIM_LINES;
681
682         if (nbr == 0)
683                 return;
684
685         /* Upload Data */
686         if (interface->vbo_format.attrib_ct == 0) {
687                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next) {
688                         BLI_assert(attrib->size <= 4); /* matrices have no place here for now */
689                         if (attrib->type == DRW_ATTRIB_FLOAT) {
690                                 attrib->format_id = VertexFormat_add_attrib(&interface->vbo_format, attrib->name, COMP_F32, attrib->size, KEEP_FLOAT);
691                         }
692                         else if (attrib->type == DRW_ATTRIB_INT) {
693                                 attrib->format_id = VertexFormat_add_attrib(&interface->vbo_format, attrib->name, COMP_I8, attrib->size, KEEP_INT);
694                         }
695                         else {
696                                 BLI_assert(false);
697                         }
698                 }
699         }
700
701         VertexBuffer *vbo = VertexBuffer_create_with_format(&interface->vbo_format);
702         VertexBuffer_allocate_data(vbo, nbr);
703
704         int j = 0;
705         for (DRWDynamicCall *call = shgroup->calls.first; call; call = call->next, j++) {
706                 int i = 0;
707                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
708                         VertexBuffer_set_attrib(vbo, attrib->format_id, j, call->data[i]);
709                 }
710         }
711
712         /* TODO make the batch dynamic instead of freeing it every times */
713         if (shgroup->batch_geom)
714                 Batch_discard_all(shgroup->batch_geom);
715
716         shgroup->batch_geom = Batch_create(type, vbo, NULL);
717 }
718
719 static void shgroup_dynamic_instance(DRWShadingGroup *shgroup)
720 {
721         int i = 0;
722         int offset = 0;
723         DRWInterface *interface = shgroup->interface;
724         int vert_nbr = interface->instance_count;
725         int buffer_size = 0;
726
727         if (vert_nbr == 0) {
728                 if (interface->instance_vbo) {
729                         glDeleteBuffers(1, &interface->instance_vbo);
730                         interface->instance_vbo = 0;
731                 }
732                 return;
733         }
734
735         /* only once */
736         if (interface->attribs_stride == 0) {
737                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
738                         BLI_assert(attrib->type == DRW_ATTRIB_FLOAT); /* Only float for now */
739                         interface->attribs_stride += attrib->size;
740                         interface->attribs_size[i] = attrib->size;
741                         interface->attribs_loc[i] = attrib->location;
742                 }
743         }
744
745         /* Gather Data */
746         buffer_size = sizeof(float) * interface->attribs_stride * vert_nbr;
747         float *data = MEM_mallocN(buffer_size, "Instance VBO data");
748
749         for (DRWDynamicCall *call = shgroup->calls.first; call; call = call->next) {
750                 for (int j = 0; j < interface->attribs_count; ++j) {
751                         memcpy(data + offset, call->data[j], sizeof(float) * interface->attribs_size[j]);
752                         offset += interface->attribs_size[j];
753                 }
754         }
755
756         /* TODO poke mike to add this to gawain */
757         if (interface->instance_vbo) {
758                 glDeleteBuffers(1, &interface->instance_vbo);
759                 interface->instance_vbo = 0;
760         }
761
762         glGenBuffers(1, &interface->instance_vbo);
763         glBindBuffer(GL_ARRAY_BUFFER, interface->instance_vbo);
764         glBufferData(GL_ARRAY_BUFFER, buffer_size, data, GL_STATIC_DRAW);
765
766         MEM_freeN(data);
767 }
768
769 static void shgroup_dynamic_batch_from_calls(DRWShadingGroup *shgroup)
770 {
771         if ((shgroup->interface->instance_vbo || shgroup->batch_geom) &&
772             (G.debug_value == 667))
773         {
774                 return;
775         }
776
777         if (shgroup->type == DRW_SHG_INSTANCE) {
778                 shgroup_dynamic_instance(shgroup);
779         }
780         else {
781                 shgroup_dynamic_batch(shgroup);
782         }
783 }
784 #endif  /* WITH_CLAY_ENGINE */
785
786 /* ***************************************** PASSES ******************************************/
787
788 DRWPass *DRW_pass_create(const char *name, DRWState state)
789 {
790         DRWPass *pass = MEM_callocN(sizeof(DRWPass), name);
791         pass->state = state;
792         BLI_strncpy(pass->name, name, MAX_PASS_NAME);
793
794         BLI_listbase_clear(&pass->shgroups);
795
796         return pass;
797 }
798
799 void DRW_pass_free(DRWPass *pass)
800 {
801         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
802                 DRW_shgroup_free(shgroup);
803         }
804
805         glDeleteQueries(2, pass->timer_queries);
806         BLI_freelistN(&pass->shgroups);
807 }
808
809 /* ****************************************** DRAW ******************************************/
810
811 #ifdef WITH_CLAY_ENGINE
812 static void set_state(DRWState flag, const bool reset)
813 {
814         /* TODO Keep track of the state and only revert what is needed */
815
816         if (reset) {
817                 /* Depth Write */
818                 if (flag & DRW_STATE_WRITE_DEPTH)
819                         glDepthMask(GL_TRUE);
820                 else
821                         glDepthMask(GL_FALSE);
822
823                 /* Color Write */
824                 if (flag & DRW_STATE_WRITE_COLOR)
825                         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
826                 else
827                         glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
828
829                 /* Backface Culling */
830                 if (flag & DRW_STATE_CULL_BACK ||
831                     flag & DRW_STATE_CULL_FRONT)
832                 {
833                         glEnable(GL_CULL_FACE);
834
835                         if (flag & DRW_STATE_CULL_BACK)
836                                 glCullFace(GL_BACK);
837                         else if (flag & DRW_STATE_CULL_FRONT)
838                                 glCullFace(GL_FRONT);
839                 }
840                 else {
841                         glDisable(GL_CULL_FACE);
842                 }
843
844                 /* Depht Test */
845                 if (flag & (DRW_STATE_DEPTH_LESS | DRW_STATE_DEPTH_EQUAL | DRW_STATE_DEPTH_GREATER))
846                 {
847                         glEnable(GL_DEPTH_TEST);
848
849                         if (flag & DRW_STATE_DEPTH_LESS)
850                                 glDepthFunc(GL_LEQUAL);
851                         else if (flag & DRW_STATE_DEPTH_EQUAL)
852                                 glDepthFunc(GL_EQUAL);
853                         else if (flag & DRW_STATE_DEPTH_GREATER)
854                                 glDepthFunc(GL_GREATER);
855                 }
856                 else {
857                         glDisable(GL_DEPTH_TEST);
858                 }
859         }
860
861         /* Wire Width */
862         if (flag & DRW_STATE_WIRE) {
863                 glLineWidth(1.0f);
864         }
865         else if (flag & DRW_STATE_WIRE_LARGE) {
866                 glLineWidth(UI_GetThemeValuef(TH_OUTLINE_WIDTH) * 2.0f);
867         }
868
869         /* Points Size */
870         if (flag & DRW_STATE_POINT) {
871                 GPU_enable_program_point_size();
872                 glPointSize(5.0f);
873         }
874         else if (reset) {
875                 GPU_disable_program_point_size();
876         }
877
878         /* Blending (all buffer) */
879         if (flag & DRW_STATE_BLEND) {
880                 glEnable(GL_BLEND);
881                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
882         }
883         else if (reset) {
884                 glDisable(GL_BLEND);
885         }
886
887         /* Line Stipple */
888         if (flag & DRW_STATE_STIPPLE_2) {
889                 setlinestyle(2);
890         }
891         else if (flag & DRW_STATE_STIPPLE_3) {
892                 setlinestyle(3);
893         }
894         else if (flag & DRW_STATE_STIPPLE_4) {
895                 setlinestyle(4);
896         }
897         else if (reset) {
898                 setlinestyle(0);
899         }
900
901         /* Stencil */
902         if (flag & (DRW_STATE_WRITE_STENCIL_SELECT | DRW_STATE_WRITE_STENCIL_ACTIVE |
903                     DRW_STATE_TEST_STENCIL_SELECT | DRW_STATE_TEST_STENCIL_ACTIVE))
904         {
905                 glEnable(GL_STENCIL_TEST);
906
907                 /* Stencil Write */
908                 if (flag & DRW_STATE_WRITE_STENCIL_SELECT) {
909                         glStencilMask(STENCIL_SELECT);
910                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
911                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_SELECT);
912                 }
913                 else if (flag & DRW_STATE_WRITE_STENCIL_ACTIVE) {
914                         glStencilMask(STENCIL_ACTIVE);
915                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
916                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_ACTIVE);
917                 }
918                 /* Stencil Test */
919                 else if (flag & DRW_STATE_TEST_STENCIL_SELECT) {
920                         glStencilMask(0x00); /* disable write */
921                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_SELECT);
922                 }
923                 else if (flag & DRW_STATE_TEST_STENCIL_ACTIVE) {
924                         glStencilMask(0x00); /* disable write */
925                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_ACTIVE);
926                 }
927         }
928         else if (reset) {
929                 /* disable write & test */
930                 glStencilMask(0x00);
931                 glStencilFunc(GL_ALWAYS, 1, 0xFF);
932                 glDisable(GL_STENCIL_TEST);
933         }
934 }
935
936 typedef struct DRWBoundTexture {
937         struct DRWBoundTexture *next, *prev;
938         GPUTexture *tex;
939 } DRWBoundTexture;
940
941 static void draw_geometry(DRWShadingGroup *shgroup, Batch *geom, const float (*obmat)[4])
942 {
943         RegionView3D *rv3d = CTX_wm_region_view3d(DST.context);
944         DRWInterface *interface = shgroup->interface;
945
946         float mvp[4][4], mv[4][4], n[3][3], wn[3][3];
947         float eye[3] = { 0.0f, 0.0f, 1.0f }; /* looking into the screen */
948
949         bool do_mvp = (interface->modelviewprojection != -1);
950         bool do_mv = (interface->modelview != -1);
951         bool do_n = (interface->normal != -1);
952         bool do_wn = (interface->worldnormal != -1);
953         bool do_eye = (interface->eye != -1);
954
955         if (do_mvp) {
956                 mul_m4_m4m4(mvp, rv3d->persmat, obmat);
957         }
958         if (do_mv || do_n || do_eye) {
959                 mul_m4_m4m4(mv, rv3d->viewmat, obmat);
960         }
961         if (do_n || do_eye) {
962                 copy_m3_m4(n, mv);
963                 invert_m3(n);
964                 transpose_m3(n);
965         }
966         if (do_wn) {
967                 copy_m3_m4(wn, obmat);
968                 invert_m3(wn);
969                 transpose_m3(wn);
970         }
971         if (do_eye) {
972                 /* Used by orthographic wires */
973                 float tmp[3][3];
974                 invert_m3_m3(tmp, n);
975                 /* set eye vector, transformed to object coords */
976                 mul_m3_v3(tmp, eye);
977         }
978
979         /* Should be really simple */
980         /* step 1 : bind object dependent matrices */
981         if (interface->model != -1) {
982                 GPU_shader_uniform_vector(shgroup->shader, interface->model, 16, 1, (float *)obmat);
983         }
984         if (interface->modelviewprojection != -1) {
985                 GPU_shader_uniform_vector(shgroup->shader, interface->modelviewprojection, 16, 1, (float *)mvp);
986         }
987         if (interface->viewprojection != -1) {
988                 GPU_shader_uniform_vector(shgroup->shader, interface->viewprojection, 16, 1, (float *)rv3d->persmat);
989         }
990         if (interface->projection != -1) {
991                 GPU_shader_uniform_vector(shgroup->shader, interface->projection, 16, 1, (float *)rv3d->winmat);
992         }
993         if (interface->view != -1) {
994                 GPU_shader_uniform_vector(shgroup->shader, interface->view, 16, 1, (float *)rv3d->viewmat);
995         }
996         if (interface->modelview != -1) {
997                 GPU_shader_uniform_vector(shgroup->shader, interface->modelview, 16, 1, (float *)mv);
998         }
999         if (interface->normal != -1) {
1000                 GPU_shader_uniform_vector(shgroup->shader, interface->normal, 9, 1, (float *)n);
1001         }
1002         if (interface->worldnormal != -1) {
1003                 GPU_shader_uniform_vector(shgroup->shader, interface->worldnormal, 9, 1, (float *)wn);
1004         }
1005         if (interface->eye != -1) {
1006                 GPU_shader_uniform_vector(shgroup->shader, interface->eye, 3, 1, (float *)eye);
1007         }
1008
1009         /* step 2 : bind vertex array & draw */
1010         Batch_set_program(geom, GPU_shader_get_program(shgroup->shader));
1011         if (interface->instance_vbo) {
1012                 Batch_draw_stupid_instanced(geom, interface->instance_vbo, interface->instance_count, interface->attribs_count,
1013                                             interface->attribs_stride, interface->attribs_size, interface->attribs_loc);
1014         }
1015         else {
1016                 Batch_draw_stupid(geom);
1017         }
1018 }
1019
1020 static void draw_shgroup(DRWShadingGroup *shgroup)
1021 {
1022         BLI_assert(shgroup->shader);
1023         BLI_assert(shgroup->interface);
1024
1025         DRWInterface *interface = shgroup->interface;
1026         GPUTexture *tex;
1027
1028         if (DST.shader != shgroup->shader) {
1029                 if (DST.shader) GPU_shader_unbind();
1030                 GPU_shader_bind(shgroup->shader);
1031                 DST.shader = shgroup->shader;
1032         }
1033
1034         if (shgroup->type != DRW_SHG_NORMAL) {
1035                 shgroup_dynamic_batch_from_calls(shgroup);
1036         }
1037
1038         if (shgroup->state != 0) {
1039                 set_state(shgroup->state, false);
1040         }
1041
1042         /* Binding Uniform */
1043         /* Don't check anything, Interface should already contain the least uniform as possible */
1044         for (DRWUniform *uni = interface->uniforms.first; uni; uni = uni->next) {
1045                 DRWBoundTexture *bound_tex;
1046
1047                 switch (uni->type) {
1048                         case DRW_UNIFORM_BOOL:
1049                         case DRW_UNIFORM_INT:
1050                                 GPU_shader_uniform_vector_int(shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)uni->value);
1051                                 break;
1052                         case DRW_UNIFORM_FLOAT:
1053                         case DRW_UNIFORM_MAT3:
1054                         case DRW_UNIFORM_MAT4:
1055                                 GPU_shader_uniform_vector(shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)uni->value);
1056                                 break;
1057                         case DRW_UNIFORM_TEXTURE:
1058                                 tex = (GPUTexture *)uni->value;
1059                                 GPU_texture_bind(tex, uni->bindloc);
1060
1061                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1062                                 bound_tex->tex = tex;
1063                                 BLI_addtail(&DST.bound_texs, bound_tex);
1064
1065                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1066                                 break;
1067                         case DRW_UNIFORM_BUFFER:
1068                                 tex = *((GPUTexture **)uni->value);
1069                                 GPU_texture_bind(tex, uni->bindloc);
1070                                 GPU_texture_compare_mode(tex, false);
1071                                 GPU_texture_filter_mode(tex, false);
1072
1073                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1074                                 bound_tex->tex = tex;
1075                                 BLI_addtail(&DST.bound_texs, bound_tex);
1076
1077                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1078                                 break;
1079                         case DRW_UNIFORM_BLOCK:
1080                                 GPU_uniformbuffer_bind((GPUUniformBuffer *)uni->value, uni->bindloc);
1081                                 GPU_shader_uniform_buffer(shgroup->shader, uni->location, (GPUUniformBuffer *)uni->value);
1082                                 break;
1083                 }
1084         }
1085
1086         /* Rendering Calls */
1087         if (shgroup->type != DRW_SHG_NORMAL) {
1088                 /* Replacing multiple calls with only one */
1089                 float obmat[4][4];
1090                 unit_m4(obmat);
1091
1092                 if (shgroup->type == DRW_SHG_INSTANCE && interface->instance_count > 0) {
1093                         draw_geometry(shgroup, shgroup->instance_geom, obmat);
1094                 }
1095                 else {
1096                         /* Some dynamic batch can have no geom (no call to aggregate) */
1097                         if (shgroup->batch_geom) {
1098                                 draw_geometry(shgroup, shgroup->batch_geom, obmat);
1099                         }
1100                 }
1101         }
1102         else {
1103                 for (DRWCall *call = shgroup->calls.first; call; call = call->next) {
1104                         draw_geometry(shgroup, call->geometry, call->obmat);
1105                 }
1106         }
1107 }
1108
1109 void DRW_draw_pass(DRWPass *pass)
1110 {
1111         /* Start fresh */
1112         DST.shader = NULL;
1113         DST.tex_bind_id = 0;
1114
1115         set_state(pass->state, true);
1116         BLI_listbase_clear(&DST.bound_texs);
1117
1118         pass->wasdrawn = true;
1119
1120         /* Init Timer queries */
1121         if (pass->timer_queries[0] == 0) {
1122                 pass->front_idx = 0;
1123                 pass->back_idx = 1;
1124
1125                 glGenQueries(2, pass->timer_queries);
1126
1127                 /* dummy query, avoid gl error */
1128                 glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->front_idx]);
1129                 glEndQuery(GL_TIME_ELAPSED);
1130         }
1131         else {
1132                 /* swap indices */
1133                 unsigned int tmp = pass->back_idx;
1134                 pass->back_idx = pass->front_idx;
1135                 pass->front_idx = tmp;
1136         }
1137
1138         /* issue query for the next frame */
1139         glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->back_idx]);
1140
1141         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
1142                 draw_shgroup(shgroup);
1143         }
1144
1145         /* Clear Bound textures */
1146         for (DRWBoundTexture *bound_tex = DST.bound_texs.first; bound_tex; bound_tex = bound_tex->next) {
1147                 GPU_texture_unbind(bound_tex->tex);
1148         }
1149         DST.tex_bind_id = 0;
1150         BLI_freelistN(&DST.bound_texs);
1151
1152         if (DST.shader) {
1153                 GPU_shader_unbind();
1154                 DST.shader = NULL;
1155         }
1156
1157         glEndQuery(GL_TIME_ELAPSED);
1158 }
1159
1160 void DRW_draw_callbacks_pre_scene(void)
1161 {
1162         struct ARegion *ar = CTX_wm_region(DST.context);
1163         RegionView3D *rv3d = CTX_wm_region_view3d(DST.context);
1164
1165         gpuLoadProjectionMatrix3D(rv3d->winmat);
1166         gpuLoadMatrix3D(rv3d->viewmat);
1167
1168         ED_region_draw_cb_draw(DST.context, ar, REGION_DRAW_PRE_VIEW);
1169 }
1170
1171 void DRW_draw_callbacks_post_scene(void)
1172 {
1173         struct ARegion *ar = CTX_wm_region(DST.context);
1174         RegionView3D *rv3d = CTX_wm_region_view3d(DST.context);
1175
1176         gpuLoadProjectionMatrix3D(rv3d->winmat);
1177         gpuLoadMatrix3D(rv3d->viewmat);
1178
1179         ED_region_draw_cb_draw(DST.context, ar, REGION_DRAW_POST_VIEW);
1180 }
1181
1182 /* Reset state to not interfer with other UI drawcall */
1183 void DRW_state_reset(void)
1184 {
1185         DRWState state = 0;
1186         state |= DRW_STATE_WRITE_DEPTH;
1187         state |= DRW_STATE_WRITE_COLOR;
1188         state |= DRW_STATE_DEPTH_LESS;
1189         set_state(state, true);
1190 }
1191
1192 #else  /* !WITH_CLAY_ENGINE */
1193
1194 void DRW_draw_pass(DRWPass *UNUSED(pass)) {}
1195 void DRW_draw_callbacks_pre_scene(void) {}
1196 void DRW_draw_callbacks_post_scene(void) {}
1197 void DRW_state_reset(void) {}
1198
1199 #endif  /* WITH_CLAY_ENGINE */
1200
1201
1202 /* ****************************************** Settings ******************************************/
1203
1204 bool DRW_is_object_renderable(Object *ob)
1205 {
1206         Scene *scene = CTX_data_scene(DST.context);
1207         Object *obedit = scene->obedit;
1208
1209         if (ob->type == OB_MESH) {
1210                 if (ob == obedit) {
1211                         IDProperty *props = BKE_object_collection_engine_get(ob, COLLECTION_MODE_EDIT, "");
1212                         bool do_occlude_wire = BKE_collection_engine_property_value_get_bool(props, "show_occlude_wire");
1213
1214                         if (do_occlude_wire)
1215                                 return false;
1216                 }
1217         }
1218
1219         return true;
1220 }
1221
1222 /* ****************************************** Framebuffers ******************************************/
1223
1224 static GPUTextureFormat convert_tex_format(int fbo_format, int *channels, bool *is_depth)
1225 {
1226         *is_depth = ((fbo_format == DRW_BUF_DEPTH_16) ||
1227                      (fbo_format == DRW_BUF_DEPTH_24));
1228
1229         switch (fbo_format) {
1230                 case DRW_BUF_RGBA_8:   *channels = 4; return GPU_RGBA8;
1231                 case DRW_BUF_RGBA_16:  *channels = 4; return GPU_RGBA16F;
1232                 case DRW_BUF_DEPTH_24: *channels = 1; return GPU_DEPTH_COMPONENT24;
1233                 default:
1234                         BLI_assert(false);
1235                         *channels = 4; return GPU_RGBA8;
1236         }
1237 }
1238
1239 void DRW_framebuffer_init(struct GPUFrameBuffer **fb, int width, int height, DRWFboTexture textures[MAX_FBO_TEX],
1240                           int texnbr)
1241 {
1242         BLI_assert(texnbr <= MAX_FBO_TEX);
1243
1244         if (!*fb) {
1245                 int color_attachment = -1;
1246                 *fb = GPU_framebuffer_create();
1247
1248                 for (int i = 0; i < texnbr; ++i) {
1249                         DRWFboTexture fbotex = textures[i];
1250
1251                         if (!*fbotex.tex) {
1252                                 int channels;
1253                                 bool is_depth;
1254                                 GPUTextureFormat gpu_format = convert_tex_format(fbotex.format, &channels, &is_depth);
1255
1256                                 *fbotex.tex = GPU_texture_create_2D_custom(width, height, channels, gpu_format, NULL, NULL);
1257                                 drw_texture_set_parameters(*fbotex.tex, fbotex.flag);
1258
1259                                 if (!is_depth) {
1260                                         ++color_attachment;
1261                                 }
1262                         }
1263
1264                         GPU_framebuffer_texture_attach(*fb, *fbotex.tex, color_attachment);
1265                 }
1266
1267                 if (!GPU_framebuffer_check_valid(*fb, NULL)) {
1268                         printf("Error invalid framebuffer\n");
1269                 }
1270
1271                 GPU_framebuffer_bind(DST.default_framebuffer);
1272         }
1273 }
1274
1275 void DRW_framebuffer_bind(struct GPUFrameBuffer *fb)
1276 {
1277         GPU_framebuffer_bind(fb);
1278 }
1279
1280 void DRW_framebuffer_clear(bool color, bool depth, bool stencil, float clear_col[4], float clear_depth)
1281 {
1282         if (color) {
1283                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1284                 glClearColor(clear_col[0], clear_col[1], clear_col[2], clear_col[3]);
1285         }
1286         if (depth) {
1287                 glDepthMask(GL_TRUE);
1288                 glClearDepth(clear_depth);
1289         }
1290         if (stencil) {
1291                 glStencilMask(0xFF);
1292         }
1293         glClear(((color) ? GL_COLOR_BUFFER_BIT : 0) |
1294                 ((depth) ? GL_DEPTH_BUFFER_BIT : 0) |
1295                 ((stencil) ? GL_STENCIL_BUFFER_BIT : 0));
1296 }
1297
1298 void DRW_framebuffer_texture_attach(struct GPUFrameBuffer *fb, GPUTexture *tex, int slot)
1299 {
1300         GPU_framebuffer_texture_attach(fb, tex, slot);
1301 }
1302
1303 void DRW_framebuffer_texture_detach(GPUTexture *tex)
1304 {
1305         GPU_framebuffer_texture_detach(tex);
1306 }
1307
1308 void DRW_framebuffer_blit(struct GPUFrameBuffer *fb_read, struct GPUFrameBuffer *fb_write, bool depth)
1309 {
1310         GPU_framebuffer_blit(fb_read, 0, fb_write, 0, depth);
1311 }
1312
1313 /* ****************************************** Viewport ******************************************/
1314 static void *DRW_viewport_engine_data_get(void *engine_type)
1315 {
1316         void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
1317
1318         if (data == NULL) {
1319                 data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
1320         }
1321         return data;
1322 }
1323
1324 float *DRW_viewport_size_get(void)
1325 {
1326         return &DST.size[0];
1327 }
1328
1329 float *DRW_viewport_screenvecs_get(void)
1330 {
1331         return &DST.screenvecs[0][0];
1332 }
1333
1334 float *DRW_viewport_pixelsize_get(void)
1335 {
1336         return &DST.pixsize;
1337 }
1338
1339 /* It also stores viewport variable to an immutable place: DST
1340  * This is because a cache uniform only store reference
1341  * to its value. And we don't want to invalidate the cache
1342  * if this value change per viewport */
1343 static void DRW_viewport_var_init(const bContext *C)
1344 {
1345         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1346
1347         /* Refresh DST.size */
1348         int size[2];
1349         GPU_viewport_size_get(DST.viewport, size);
1350         DST.size[0] = size[0];
1351         DST.size[1] = size[1];
1352
1353         DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
1354         DST.default_framebuffer = fbl->default_fb;
1355
1356         /* Refresh DST.screenvecs */
1357         copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
1358         copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
1359         normalize_v3(DST.screenvecs[0]);
1360         normalize_v3(DST.screenvecs[1]);
1361
1362         /* Refresh DST.pixelsize */
1363         DST.pixsize = rv3d->pixsize;
1364
1365         /* Save context for all later needs */
1366         DST.context = C;
1367 }
1368
1369 void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
1370 {
1371         RegionView3D *rv3d = CTX_wm_region_view3d(DST.context);
1372
1373         if (type == DRW_MAT_PERS)
1374                 copy_m4_m4(mat, rv3d->persmat);
1375         else if (type == DRW_MAT_VIEW)
1376                 copy_m4_m4(mat, rv3d->viewmat);
1377         else if (type == DRW_MAT_VIEWINV)
1378                 copy_m4_m4(mat, rv3d->viewinv);
1379         else if (type == DRW_MAT_WIN)
1380                 copy_m4_m4(mat, rv3d->winmat);
1381 }
1382
1383 bool DRW_viewport_is_persp_get(void)
1384 {
1385         RegionView3D *rv3d = CTX_wm_region_view3d(DST.context);
1386         return rv3d->is_persp;
1387 }
1388
1389 DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
1390 {
1391         return GPU_viewport_framebuffer_list_get(DST.viewport);
1392 }
1393
1394 DefaultTextureList *DRW_viewport_texture_list_get(void)
1395 {
1396         return GPU_viewport_texture_list_get(DST.viewport);
1397 }
1398
1399 /* **************************************** OBJECTS *************************************** */
1400
1401 typedef struct ObjectEngineData {
1402         struct ObjectEngineData *next, *prev;
1403         DrawEngineType *engine_type;
1404         void *storage;
1405 } ObjectEngineData;
1406
1407 void **DRW_object_engine_data_get(Object *ob, DrawEngineType *engine_type)
1408 {
1409         ObjectEngineData *oed;
1410
1411         for (oed = ob->drawdata.first; oed; oed = oed->next) {
1412                 if (oed->engine_type == engine_type) {
1413                         return &oed->storage;
1414                 }
1415         }
1416
1417         oed = MEM_callocN(sizeof(ObjectEngineData), "ObjectEngineData");
1418         oed->engine_type = engine_type;
1419         BLI_addtail(&ob->drawdata, oed);
1420
1421         return &oed->storage;
1422 }
1423
1424 void DRW_object_engine_data_free(Object *ob)
1425 {
1426         for (ObjectEngineData *oed = ob->drawdata.first; oed; oed = oed->next) {
1427                 if (oed->storage) {
1428                         MEM_freeN(oed->storage);
1429                 }
1430         }
1431
1432         BLI_freelistN(&ob->drawdata);
1433 }
1434
1435 LampEngineData *DRW_lamp_engine_data_get(Object *ob, RenderEngineType *engine_type)
1436 {
1437         BLI_assert(ob->type == OB_LAMP);
1438
1439         Scene *scene = CTX_data_scene(DST.context);
1440
1441         /* TODO Dupliobjects */
1442         return GPU_lamp_engine_data_get(scene, ob, NULL, engine_type);
1443 }
1444
1445 void DRW_lamp_engine_data_free(LampEngineData *led)
1446 {
1447         return GPU_lamp_engine_data_free(led);
1448 }
1449
1450 /* **************************************** RENDERING ************************************** */
1451
1452 #define TIMER_FALLOFF 0.1f
1453
1454 static void DRW_engines_init(void)
1455 {
1456         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1457                 DrawEngineType *engine = link->data;
1458                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1459                 double stime = PIL_check_seconds_timer();
1460
1461                 if (engine->engine_init) {
1462                         engine->engine_init(data);
1463                 }
1464
1465                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
1466                 data->init_time = data->init_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
1467         }
1468 }
1469
1470 static void DRW_engines_cache_init(void)
1471 {
1472         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1473                 DrawEngineType *engine = link->data;
1474                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1475                 double stime = PIL_check_seconds_timer();
1476                 data->cache_time = 0.0;
1477
1478                 if (engine->cache_init) {
1479                         engine->cache_init(data);
1480                 }
1481
1482                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
1483         }
1484 }
1485
1486 static void DRW_engines_cache_populate(Object *ob)
1487 {
1488         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1489                 DrawEngineType *engine = link->data;
1490                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1491                 double stime = PIL_check_seconds_timer();
1492
1493                 if (engine->cache_populate) {
1494                         engine->cache_populate(data, ob);
1495                 }
1496
1497                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
1498         }
1499 }
1500
1501 static void DRW_engines_cache_finish(void)
1502 {
1503         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1504                 DrawEngineType *engine = link->data;
1505                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1506                 double stime = PIL_check_seconds_timer();
1507
1508                 if (engine->cache_finish) {
1509                         engine->cache_finish(data);
1510                 }
1511
1512                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
1513         }
1514 }
1515
1516 static void DRW_engines_draw_background(void)
1517 {
1518         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1519                 DrawEngineType *engine = link->data;
1520                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1521                 double stime = PIL_check_seconds_timer();
1522
1523                 if (engine->draw_background) {
1524                         engine->draw_background(data);
1525                         return;
1526                 }
1527
1528                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
1529                 data->background_time = data->background_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
1530         }
1531
1532         /* No draw_background found, doing default background */
1533         DRW_draw_background();
1534 }
1535
1536 static void DRW_engines_draw_scene(void)
1537 {
1538         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1539                 DrawEngineType *engine = link->data;
1540                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1541                 double stime = PIL_check_seconds_timer();
1542
1543                 if (engine->draw_scene) {
1544                         engine->draw_scene(data);
1545                 }
1546
1547                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
1548                 data->render_time = data->render_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
1549         }
1550 }
1551
1552 static void use_drw_engine(DrawEngineType *engine)
1553 {
1554         LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
1555         ld->data = engine;
1556         BLI_addtail(&DST.enabled_engines, ld);
1557 }
1558
1559 /* TODO revisit this when proper layering is implemented */
1560 /* Gather all draw engines needed and store them in DST.enabled_engines
1561  * That also define the rendering order of engines */
1562 static void DRW_engines_enable(const bContext *C)
1563 {
1564         /* TODO layers */
1565         Scene *scene = CTX_data_scene(C);
1566         RenderEngineType *type = RE_engines_find(scene->r.engine);
1567         use_drw_engine(type->draw_engine);
1568
1569         /* TODO Refine the folowing logic based on objects states
1570          * not on global state.
1571          * Order is important */
1572         use_drw_engine(&draw_engine_object_type);
1573
1574         switch (CTX_data_mode_enum(C)) {
1575                 case CTX_MODE_EDIT_MESH:
1576                         use_drw_engine(&draw_engine_edit_mesh_type);
1577                         break;
1578                 case CTX_MODE_EDIT_CURVE:
1579                         use_drw_engine(&draw_engine_edit_curve_type);
1580                         break;
1581                 case CTX_MODE_EDIT_SURFACE:
1582                         use_drw_engine(&draw_engine_edit_surface_type);
1583                         break;
1584                 case CTX_MODE_EDIT_TEXT:
1585                         use_drw_engine(&draw_engine_edit_text_type);
1586                         break;
1587                 case CTX_MODE_EDIT_ARMATURE:
1588                         use_drw_engine(&draw_engine_edit_armature_type);
1589                         break;
1590                 case CTX_MODE_EDIT_METABALL:
1591                         use_drw_engine(&draw_engine_edit_metaball_type);
1592                         break;
1593                 case CTX_MODE_EDIT_LATTICE:
1594                         use_drw_engine(&draw_engine_edit_lattice_type);
1595                         break;
1596                 case CTX_MODE_POSE:
1597                         use_drw_engine(&draw_engine_pose_type);
1598                         break;
1599                 case CTX_MODE_SCULPT:
1600                         use_drw_engine(&draw_engine_sculpt_type);
1601                         break;
1602                 case CTX_MODE_PAINT_WEIGHT:
1603                         use_drw_engine(&draw_engine_paint_weight_type);
1604                         break;
1605                 case CTX_MODE_PAINT_VERTEX:
1606                         use_drw_engine(&draw_engine_paint_vertex_type);
1607                         break;
1608                 case CTX_MODE_PAINT_TEXTURE:
1609                         use_drw_engine(&draw_engine_paint_texture_type);
1610                         break;
1611                 case CTX_MODE_PARTICLE:
1612                         use_drw_engine(&draw_engine_particle_type);
1613                         break;
1614                 case CTX_MODE_OBJECT:
1615                         break;
1616         }
1617 }
1618
1619 static void DRW_engines_disable(void)
1620 {
1621         BLI_freelistN(&DST.enabled_engines);
1622 }
1623
1624 static unsigned int DRW_engines_get_hash(void)
1625 {
1626         unsigned int hash = 0;
1627         /* The cache depends on enabled engines */
1628         /* FIXME : if collision occurs ... segfault */
1629         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1630                 DrawEngineType *engine = link->data;
1631                 hash += BLI_ghashutil_strhash_p(engine->idname);
1632         }
1633
1634         return hash;
1635 }
1636
1637 static void draw_stat(rcti *rect, int u, int v, const char *txt, const int size)
1638 {
1639         BLF_draw_default_ascii(rect->xmin + (1 + u * 5) * U.widget_unit,
1640                                rect->ymax - (3 + v++) * U.widget_unit, 0.0f,
1641                                txt, size);
1642 }
1643
1644 /* CPU stats */
1645 static void DRW_debug_cpu_stats(void)
1646 {
1647         int u, v;
1648         double cache_tot_time = 0.0, init_tot_time = 0.0, background_tot_time = 0.0, render_tot_time = 0.0, tot_time = 0.0;
1649         /* local coordinate visible rect inside region, to accomodate overlapping ui */
1650         rcti rect;
1651         struct ARegion *ar = CTX_wm_region(DST.context);
1652         ED_region_visible_rect(ar, &rect);
1653
1654         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1655
1656         /* row by row */
1657         v = 0; u = 0;
1658         /* Label row */
1659         char col_label[32];
1660         sprintf(col_label, "Engine");
1661         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1662         sprintf(col_label, "Cache");
1663         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1664         sprintf(col_label, "Init");
1665         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1666         sprintf(col_label, "Background");
1667         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1668         sprintf(col_label, "Render");
1669         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1670         sprintf(col_label, "Total (w/o cache)");
1671         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1672         v++;
1673
1674         /* Engines rows */
1675         char time_to_txt[16];
1676         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1677                 u = 0;
1678                 DrawEngineType *engine = link->data;
1679                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1680
1681                 draw_stat(&rect, u++, v, engine->idname, sizeof(engine->idname));
1682
1683                 cache_tot_time += data->cache_time;
1684                 sprintf(time_to_txt, "%.2fms", data->cache_time);
1685                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1686
1687                 init_tot_time += data->init_time;
1688                 sprintf(time_to_txt, "%.2fms", data->init_time);
1689                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1690
1691                 background_tot_time += data->background_time;
1692                 sprintf(time_to_txt, "%.2fms", data->background_time);
1693                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1694
1695                 render_tot_time += data->render_time;
1696                 sprintf(time_to_txt, "%.2fms", data->render_time);
1697                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1698
1699                 tot_time += data->init_time + data->background_time + data->render_time;
1700                 sprintf(time_to_txt, "%.2fms", data->init_time + data->background_time + data->render_time);
1701                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1702                 v++;
1703         }
1704
1705         /* Totals row */
1706         u = 0;
1707         sprintf(col_label, "Sub Total");
1708         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
1709         sprintf(time_to_txt, "%.2fms", cache_tot_time);
1710         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1711         sprintf(time_to_txt, "%.2fms", init_tot_time);
1712         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1713         sprintf(time_to_txt, "%.2fms", background_tot_time);
1714         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1715         sprintf(time_to_txt, "%.2fms", render_tot_time);
1716         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1717         sprintf(time_to_txt, "%.2fms", tot_time);
1718         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
1719 }
1720
1721 /* Display GPU time for each passes */
1722 static void DRW_debug_gpu_stats(void)
1723 {
1724         /* local coordinate visible rect inside region, to accomodate overlapping ui */
1725         rcti rect;
1726         struct ARegion *ar = CTX_wm_region(DST.context);
1727         ED_region_visible_rect(ar, &rect);
1728
1729         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
1730
1731         char time_to_txt[16];
1732         char pass_name[MAX_PASS_NAME + 8];
1733         int v = BLI_listbase_count(&DST.enabled_engines) + 3;
1734         GLuint64 tot_time = 0;
1735
1736         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
1737                 GLuint64 engine_time = 0;
1738                 DrawEngineType *engine = link->data;
1739                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
1740                 int vsta = v;
1741
1742                 draw_stat(&rect, 0, v, engine->idname, sizeof(engine->idname));
1743                 v++;
1744
1745                 for (int i = 0; i < MAX_PASSES; ++i) {
1746                         DRWPass *pass = data->psl->passes[i];
1747                         if (pass != NULL) {
1748                                 GLuint64 time;
1749                                 glGetQueryObjectui64v(pass->timer_queries[pass->front_idx], GL_QUERY_RESULT, &time);
1750                                 tot_time += time;
1751                                 engine_time += time;
1752
1753                                 sprintf(pass_name, "   |--> %s", pass->name);
1754                                 draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
1755
1756                                 if (pass->wasdrawn)
1757                                         sprintf(time_to_txt, "%.2fms", time / 1000000.0);
1758                                 else
1759                                         sprintf(time_to_txt, "Not drawn");
1760                                 draw_stat(&rect, 2, v++, time_to_txt, sizeof(time_to_txt));
1761
1762                                 pass->wasdrawn = false;
1763                         }
1764                 }
1765                 /* engine total time */
1766                 sprintf(time_to_txt, "%.2fms", engine_time / 1000000.0);
1767                 draw_stat(&rect, 2, vsta, time_to_txt, sizeof(time_to_txt));
1768                 v++;
1769         }
1770
1771         sprintf(pass_name, "Total GPU time %.2fms (%.1f fps)", tot_time / 1000000.0, 1000000000.0 / tot_time);
1772         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
1773 }
1774
1775 /* Everything starts here.
1776  * This function takes care of calling all cache and rendering functions
1777  * for each relevant engine / mode engine. */
1778 void DRW_draw_view(const bContext *C)
1779 {
1780         bool cache_is_dirty;
1781         RegionView3D *rv3d = CTX_wm_region_view3d(C);
1782         View3D *v3d = CTX_wm_view3d(C);
1783         DST.viewport = rv3d->viewport;
1784         v3d->zbuf = true;
1785
1786         /* Get list of enabled engines */
1787         DRW_engines_enable(C);
1788
1789         /* Setup viewport */
1790         cache_is_dirty = GPU_viewport_cache_validate(DST.viewport, DRW_engines_get_hash());
1791         DRW_viewport_var_init(C);
1792
1793         /* Update ubos */
1794         DRW_globals_update();
1795
1796         /* Init engines */
1797         DRW_engines_init();
1798
1799         /* TODO : tag to refresh by the deps graph */
1800         /* ideally only refresh when objects are added/removed */
1801         /* or render properties / materials change */
1802         if (cache_is_dirty) {
1803                 SceneLayer *sl = CTX_data_scene_layer(C);
1804
1805                 DRW_engines_cache_init();
1806                 DEG_OBJECT_ITER(sl, ob);
1807                 {
1808                         DRW_engines_cache_populate(ob);
1809                 }
1810                 DEG_OBJECT_ITER_END
1811                 DRW_engines_cache_finish();
1812         }
1813
1814         /* Start Drawing */
1815         DRW_engines_draw_background();
1816
1817         DRW_draw_callbacks_pre_scene();
1818         // DRW_draw_grid();
1819         DRW_engines_draw_scene();
1820         DRW_draw_callbacks_post_scene();
1821
1822         DRW_draw_manipulator();
1823
1824         DRW_draw_region_info();
1825
1826         if (G.debug_value > 20) {
1827                 DRW_debug_cpu_stats();
1828                 DRW_debug_gpu_stats();
1829         }
1830
1831         DRW_state_reset();
1832         DRW_engines_disable();
1833 }
1834
1835 /* ****************************************** OTHER ***************************************** */
1836
1837 const bContext *DRW_get_context(void)
1838 {
1839         return DST.context;
1840 }
1841
1842 /* ****************************************** INIT ***************************************** */
1843
1844 void DRW_engine_register(DrawEngineType *draw_engine_type)
1845 {
1846         BLI_addtail(&DRW_engines, draw_engine_type);
1847 }
1848
1849 void DRW_engines_register(void)
1850 {
1851 #ifdef WITH_CLAY_ENGINE
1852         RE_engines_register(NULL, &viewport_clay_type);
1853         RE_engines_register(NULL, &viewport_eevee_type);
1854
1855         DRW_engine_register(&draw_engine_object_type);
1856         DRW_engine_register(&draw_engine_edit_armature_type);
1857         DRW_engine_register(&draw_engine_edit_curve_type);
1858         DRW_engine_register(&draw_engine_edit_lattice_type);
1859         DRW_engine_register(&draw_engine_edit_mesh_type);
1860         DRW_engine_register(&draw_engine_edit_metaball_type);
1861         DRW_engine_register(&draw_engine_edit_surface_type);
1862         DRW_engine_register(&draw_engine_edit_text_type);
1863         DRW_engine_register(&draw_engine_paint_texture_type);
1864         DRW_engine_register(&draw_engine_paint_vertex_type);
1865         DRW_engine_register(&draw_engine_paint_weight_type);
1866         DRW_engine_register(&draw_engine_particle_type);
1867         DRW_engine_register(&draw_engine_pose_type);
1868         DRW_engine_register(&draw_engine_sculpt_type);
1869 #endif
1870 }
1871
1872 extern struct GPUUniformBuffer *globals_ubo; /* draw_common.c */
1873 void DRW_engines_free(void)
1874 {
1875 #ifdef WITH_CLAY_ENGINE
1876         DRW_shape_cache_free();
1877
1878         DrawEngineType *next;
1879         for (DrawEngineType *type = DRW_engines.first; type; type = next) {
1880                 next = type->next;
1881                 BLI_remlink(&R_engines, type);
1882
1883                 if (type->engine_free) {
1884                         type->engine_free();
1885                 }
1886         }
1887
1888         if (globals_ubo)
1889                 GPU_uniformbuffer_free(globals_ubo);
1890
1891         BLI_remlink(&R_engines, &viewport_clay_type);
1892 #endif
1893 }