Eevee: Transparency: Add hide backside option.
[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 #include "BKE_mesh.h"
37 #include "BKE_object.h"
38 #include "BKE_pbvh.h"
39 #include "BKE_paint.h"
40
41 #include "BLT_translation.h"
42 #include "BLF_api.h"
43
44 #include "DRW_engine.h"
45 #include "DRW_render.h"
46
47 #include "DNA_camera_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_screen_types.h"
50 #include "DNA_mesh_types.h"
51 #include "DNA_meshdata_types.h"
52
53 #include "ED_space_api.h"
54 #include "ED_screen.h"
55
56 #include "intern/gpu_codegen.h"
57 #include "GPU_batch.h"
58 #include "GPU_draw.h"
59 #include "GPU_extensions.h"
60 #include "GPU_framebuffer.h"
61 #include "GPU_immediate.h"
62 #include "GPU_lamp.h"
63 #include "GPU_material.h"
64 #include "GPU_shader.h"
65 #include "GPU_texture.h"
66 #include "GPU_uniformbuffer.h"
67 #include "GPU_viewport.h"
68 #include "GPU_matrix.h"
69
70 #include "IMB_colormanagement.h"
71
72 #include "PIL_time.h"
73
74 #include "RE_engine.h"
75
76 #include "UI_interface.h"
77 #include "UI_resources.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 #include "draw_manager_text.h"
83
84 /* only for callbacks */
85 #include "draw_cache_impl.h"
86
87 #include "draw_mode_engines.h"
88 #include "engines/clay/clay_engine.h"
89 #include "engines/eevee/eevee_engine.h"
90 #include "engines/basic/basic_engine.h"
91 #include "engines/external/external_engine.h"
92
93 #include "DEG_depsgraph.h"
94 #include "DEG_depsgraph_query.h"
95
96 #define MAX_ATTRIB_NAME 32
97 #define MAX_PASS_NAME 32
98 #define MAX_CLIP_PLANES 6 /* GL_MAX_CLIP_PLANES is at least 6 */
99
100 /* Use draw manager to call GPU_select, see: DRW_draw_select_loop */
101 #define USE_GPU_SELECT
102
103 #ifdef USE_GPU_SELECT
104 #  include "ED_view3d.h"
105 #  include "ED_armature.h"
106 #  include "GPU_select.h"
107 #endif
108
109 extern char datatoc_gpu_shader_2D_vert_glsl[];
110 extern char datatoc_gpu_shader_3D_vert_glsl[];
111 extern char datatoc_gpu_shader_fullscreen_vert_glsl[];
112
113 /* Prototypes. */
114 static void DRW_engines_enable_external(void);
115
116 /* Structures */
117 typedef enum {
118         DRW_UNIFORM_BOOL,
119         DRW_UNIFORM_SHORT_TO_INT,
120         DRW_UNIFORM_SHORT_TO_FLOAT,
121         DRW_UNIFORM_INT,
122         DRW_UNIFORM_FLOAT,
123         DRW_UNIFORM_TEXTURE,
124         DRW_UNIFORM_BUFFER,
125         DRW_UNIFORM_MAT3,
126         DRW_UNIFORM_MAT4,
127         DRW_UNIFORM_BLOCK
128 } DRWUniformType;
129
130 typedef enum {
131         DRW_ATTRIB_INT,
132         DRW_ATTRIB_FLOAT,
133 } DRWAttribType;
134
135 struct DRWUniform {
136         struct DRWUniform *next, *prev;
137         DRWUniformType type;
138         int location;
139         int length;
140         int arraysize;
141         int bindloc;
142         const void *value;
143 };
144
145 typedef struct DRWAttrib {
146         struct DRWAttrib *next, *prev;
147         char name[MAX_ATTRIB_NAME];
148         int location;
149         int format_id;
150         int size; /* number of component */
151         int type;
152 } DRWAttrib;
153
154 struct DRWInterface {
155         ListBase uniforms;   /* DRWUniform */
156         ListBase attribs;    /* DRWAttrib */
157         int attribs_count;
158         int attribs_stride;
159         int attribs_size[16];
160         int attribs_loc[16];
161         /* matrices locations */
162         int model;
163         int modelinverse;
164         int modelview;
165         int modelviewinverse;
166         int projection;
167         int projectioninverse;
168         int view;
169         int viewinverse;
170         int modelviewprojection;
171         int viewprojection;
172         int viewprojectioninverse;
173         int normal;
174         int worldnormal;
175         int camtexfac;
176         int orcotexfac;
177         int eye;
178         int clipplanes;
179         /* Textures */
180         int tex_bind; /* next texture binding point */
181         /* UBO */
182         int ubo_bind; /* next ubo binding point */
183         /* Dynamic batch */
184         Gwn_Batch *instance_batch; /* contains instances attributes */
185         GLuint instance_vbo; /* same as instance_batch but generated from DRWCalls */
186         int instance_count;
187         Gwn_VertFormat vbo_format;
188 };
189
190 struct DRWPass {
191         ListBase shgroups; /* DRWShadingGroup */
192         DRWState state;
193         char name[MAX_PASS_NAME];
194         /* use two query to not stall the cpu waiting for queries to complete */
195         unsigned int timer_queries[2];
196         /* alternate between front and back query */
197         unsigned int front_idx;
198         unsigned int back_idx;
199         bool wasdrawn; /* if it was drawn during this frame */
200 };
201
202 typedef struct DRWCallHeader {
203         void *next, *prev;
204 #ifdef USE_GPU_SELECT
205         int select_id;
206 #endif
207         uchar type;
208 } DRWCallHeader;
209
210 typedef struct DRWCall {
211         DRWCallHeader head;
212
213         float obmat[4][4];
214         Gwn_Batch *geometry;
215
216         Object *ob; /* Optional */
217         ID *ob_data; /* Optional. */
218 } DRWCall;
219
220 typedef struct DRWCallGenerate {
221         DRWCallHeader head;
222
223         float obmat[4][4];
224
225         DRWCallGenerateFn *geometry_fn;
226         void *user_data;
227 } DRWCallGenerate;
228
229 typedef struct DRWCallDynamic {
230         DRWCallHeader head;
231
232         const void *data[];
233 } DRWCallDynamic;
234
235 struct DRWShadingGroup {
236         struct DRWShadingGroup *next, *prev;
237
238         GPUShader *shader;               /* Shader to bind */
239         DRWInterface *interface;         /* Uniforms pointers */
240         ListBase calls;                  /* DRWCall or DRWCallDynamic depending of type */
241         DRWState state_extra;            /* State changes for this batch only (or'd with the pass's state) */
242         DRWState state_extra_disable;    /* State changes for this batch only (and'd with the pass's state) */
243         int type;
244
245         Gwn_Batch *instance_geom;  /* Geometry to instance */
246         Gwn_Batch *batch_geom;     /* Result of call batching */
247
248 #ifdef USE_GPU_SELECT
249         /* backlink to pass we're in */
250         DRWPass *pass_parent;
251 #endif
252 };
253
254 /* Used by DRWShadingGroup.type */
255 enum {
256         DRW_SHG_NORMAL,
257         DRW_SHG_POINT_BATCH,
258         DRW_SHG_LINE_BATCH,
259         DRW_SHG_TRIANGLE_BATCH,
260         DRW_SHG_INSTANCE,
261 };
262
263 /* Used by DRWCall.type */
264 enum {
265         /* A single batch */
266         DRW_CALL_SINGLE,
267         /* Uses a callback to draw with any number of batches. */
268         DRW_CALL_GENERATE,
269         /* Arbitrary number of multiple args. */
270         DRW_CALL_DYNAMIC,
271 };
272
273 /* only 16 bits long */
274 enum {
275         STENCIL_SELECT          = (1 << 0),
276         STENCIL_ACTIVE          = (1 << 1),
277 };
278
279 /* Render State */
280 static struct DRWGlobalState {
281         /* Rendering state */
282         GPUShader *shader;
283         ListBase bound_texs;
284         int tex_bind_id;
285
286         /* Managed by `DRW_state_set`, `DRW_state_reset` */
287         DRWState state;
288
289         /* Per viewport */
290         GPUViewport *viewport;
291         struct GPUFrameBuffer *default_framebuffer;
292         float size[2];
293         float screenvecs[2][3];
294         float pixsize;
295
296         GLenum backface, frontface;
297
298         /* Clip planes */
299         int num_clip_planes;
300         float clip_planes_eq[MAX_CLIP_PLANES][4];
301
302         struct {
303                 unsigned int is_select : 1;
304                 unsigned int is_depth : 1;
305                 unsigned int is_image_render : 1;
306                 unsigned int is_scene_render : 1;
307         } options;
308
309         /* Current rendering context */
310         DRWContextState draw_ctx;
311
312         /* Convenience pointer to text_store owned by the viewport */
313         struct DRWTextStore **text_store_p;
314
315         ListBase enabled_engines; /* RenderEngineType */
316 } DST = {NULL};
317
318 static struct DRWMatrixOveride {
319         float mat[6][4][4];
320         bool override[6];
321 } viewport_matrix_override = {{{{0}}}};
322
323 ListBase DRW_engines = {NULL, NULL};
324
325 #ifdef USE_GPU_SELECT
326 static unsigned int g_DRW_select_id = (unsigned int)-1;
327
328 void DRW_select_load_id(unsigned int id)
329 {
330         BLI_assert(G.f & G_PICKSEL);
331         g_DRW_select_id = id;
332 }
333 #endif
334
335
336 /* -------------------------------------------------------------------- */
337
338 /** \name Textures (DRW_texture)
339  * \{ */
340
341 static void drw_texture_get_format(DRWTextureFormat format, GPUTextureFormat *data_type, int *channels)
342 {
343         switch (format) {
344                 case DRW_TEX_RGBA_8: *data_type = GPU_RGBA8; break;
345                 case DRW_TEX_RGBA_16: *data_type = GPU_RGBA16F; break;
346                 case DRW_TEX_RGB_16: *data_type = GPU_RGB16F; break;
347                 case DRW_TEX_RGB_11_11_10: *data_type = GPU_R11F_G11F_B10F; break;
348                 case DRW_TEX_RG_16: *data_type = GPU_RG16F; break;
349                 case DRW_TEX_RG_32: *data_type = GPU_RG32F; break;
350                 case DRW_TEX_R_8: *data_type = GPU_R8; break;
351                 case DRW_TEX_R_16: *data_type = GPU_R16F; break;
352                 case DRW_TEX_R_32: *data_type = GPU_R32F; break;
353 #if 0
354                 case DRW_TEX_RGBA_32: *data_type = GPU_RGBA32F; break;
355                 case DRW_TEX_RGB_8: *data_type = GPU_RGB8; break;
356                 case DRW_TEX_RGB_32: *data_type = GPU_RGB32F; break;
357                 case DRW_TEX_RG_8: *data_type = GPU_RG8; break;
358 #endif
359                 case DRW_TEX_DEPTH_16: *data_type = GPU_DEPTH_COMPONENT16; break;
360                 case DRW_TEX_DEPTH_24: *data_type = GPU_DEPTH_COMPONENT24; break;
361                 case DRW_TEX_DEPTH_32: *data_type = GPU_DEPTH_COMPONENT32F; break;
362                 default :
363                         /* file type not supported you must uncomment it from above */
364                         BLI_assert(false);
365                         break;
366         }
367
368         switch (format) {
369                 case DRW_TEX_RGBA_8:
370                 case DRW_TEX_RGBA_16:
371                 case DRW_TEX_RGBA_32:
372                         *channels = 4;
373                         break;
374                 case DRW_TEX_RGB_8:
375                 case DRW_TEX_RGB_16:
376                 case DRW_TEX_RGB_32:
377                 case DRW_TEX_RGB_11_11_10:
378                         *channels = 3;
379                         break;
380                 case DRW_TEX_RG_8:
381                 case DRW_TEX_RG_16:
382                 case DRW_TEX_RG_32:
383                         *channels = 2;
384                         break;
385                 default:
386                         *channels = 1;
387                         break;
388         }
389 }
390
391 static void drw_texture_set_parameters(GPUTexture *tex, DRWTextureFlag flags)
392 {
393         GPU_texture_bind(tex, 0);
394         if (flags & DRW_TEX_MIPMAP) {
395                 GPU_texture_mipmap_mode(tex, true, flags & DRW_TEX_FILTER);
396                 DRW_texture_generate_mipmaps(tex);
397         }
398         else {
399                 GPU_texture_filter_mode(tex, flags & DRW_TEX_FILTER);
400         }
401         GPU_texture_wrap_mode(tex, flags & DRW_TEX_WRAP);
402         GPU_texture_compare_mode(tex, flags & DRW_TEX_COMPARE);
403         GPU_texture_unbind(tex);
404 }
405
406 GPUTexture *DRW_texture_create_1D(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
407 {
408         GPUTexture *tex;
409         GPUTextureFormat data_type;
410         int channels;
411
412         drw_texture_get_format(format, &data_type, &channels);
413         tex = GPU_texture_create_1D_custom(w, channels, data_type, fpixels, NULL);
414         drw_texture_set_parameters(tex, flags);
415
416         return tex;
417 }
418
419 GPUTexture *DRW_texture_create_2D(int w, int h, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
420 {
421         GPUTexture *tex;
422         GPUTextureFormat data_type;
423         int channels;
424
425         drw_texture_get_format(format, &data_type, &channels);
426         tex = GPU_texture_create_2D_custom(w, h, channels, data_type, fpixels, NULL);
427         drw_texture_set_parameters(tex, flags);
428
429         return tex;
430 }
431
432 GPUTexture *DRW_texture_create_2D_array(
433         int w, int h, int d, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
434 {
435         GPUTexture *tex;
436         GPUTextureFormat data_type;
437         int channels;
438
439         drw_texture_get_format(format, &data_type, &channels);
440         tex = GPU_texture_create_2D_array_custom(w, h, d, channels, data_type, fpixels, NULL);
441         drw_texture_set_parameters(tex, flags);
442
443         return tex;
444 }
445
446 GPUTexture *DRW_texture_create_cube(int w, DRWTextureFormat format, DRWTextureFlag flags, const float *fpixels)
447 {
448         GPUTexture *tex;
449         GPUTextureFormat data_type;
450         int channels;
451
452         drw_texture_get_format(format, &data_type, &channels);
453         tex = GPU_texture_create_cube_custom(w, channels, data_type, fpixels, NULL);
454         drw_texture_set_parameters(tex, flags);
455
456         return tex;
457 }
458
459 void DRW_texture_generate_mipmaps(GPUTexture *tex)
460 {
461         GPU_texture_bind(tex, 0);
462         GPU_texture_generate_mipmap(tex);
463         GPU_texture_unbind(tex);
464 }
465
466 void DRW_texture_free(GPUTexture *tex)
467 {
468         GPU_texture_free(tex);
469 }
470
471 /** \} */
472
473
474 /* -------------------------------------------------------------------- */
475
476 /** \name Uniform Buffer Object (DRW_uniformbuffer)
477  * \{ */
478
479 GPUUniformBuffer *DRW_uniformbuffer_create(int size, const void *data)
480 {
481         return GPU_uniformbuffer_create(size, data, NULL);
482 }
483
484 void DRW_uniformbuffer_update(GPUUniformBuffer *ubo, const void *data)
485 {
486         GPU_uniformbuffer_update(ubo, data);
487 }
488
489 void DRW_uniformbuffer_free(GPUUniformBuffer *ubo)
490 {
491         GPU_uniformbuffer_free(ubo);
492 }
493
494 /** \} */
495
496
497 /* -------------------------------------------------------------------- */
498
499 /** \name Shaders (DRW_shader)
500  * \{ */
501
502 GPUShader *DRW_shader_create(const char *vert, const char *geom, const char *frag, const char *defines)
503 {
504         return GPU_shader_create(vert, frag, geom, NULL, defines);
505 }
506
507 GPUShader *DRW_shader_create_with_lib(
508         const char *vert, const char *geom, const char *frag, const char *lib, const char *defines)
509 {
510         GPUShader *sh;
511         char *vert_with_lib = NULL;
512         char *frag_with_lib = NULL;
513         char *geom_with_lib = NULL;
514
515         DynStr *ds_vert = BLI_dynstr_new();
516         BLI_dynstr_append(ds_vert, lib);
517         BLI_dynstr_append(ds_vert, vert);
518         vert_with_lib = BLI_dynstr_get_cstring(ds_vert);
519         BLI_dynstr_free(ds_vert);
520
521         DynStr *ds_frag = BLI_dynstr_new();
522         BLI_dynstr_append(ds_frag, lib);
523         BLI_dynstr_append(ds_frag, frag);
524         frag_with_lib = BLI_dynstr_get_cstring(ds_frag);
525         BLI_dynstr_free(ds_frag);
526
527         if (geom) {
528                 DynStr *ds_geom = BLI_dynstr_new();
529                 BLI_dynstr_append(ds_geom, lib);
530                 BLI_dynstr_append(ds_geom, geom);
531                 geom_with_lib = BLI_dynstr_get_cstring(ds_geom);
532                 BLI_dynstr_free(ds_geom);
533         }
534
535         sh = GPU_shader_create(vert_with_lib, frag_with_lib, geom_with_lib, NULL, defines);
536
537         MEM_freeN(vert_with_lib);
538         MEM_freeN(frag_with_lib);
539         if (geom) {
540                 MEM_freeN(geom_with_lib);
541         }
542
543         return sh;
544 }
545
546 GPUShader *DRW_shader_create_2D(const char *frag, const char *defines)
547 {
548         return GPU_shader_create(datatoc_gpu_shader_2D_vert_glsl, frag, NULL, NULL, defines);
549 }
550
551 GPUShader *DRW_shader_create_3D(const char *frag, const char *defines)
552 {
553         return GPU_shader_create(datatoc_gpu_shader_3D_vert_glsl, frag, NULL, NULL, defines);
554 }
555
556 GPUShader *DRW_shader_create_fullscreen(const char *frag, const char *defines)
557 {
558         return GPU_shader_create(datatoc_gpu_shader_fullscreen_vert_glsl, frag, NULL, NULL, defines);
559 }
560
561 GPUShader *DRW_shader_create_3D_depth_only(void)
562 {
563         return GPU_shader_get_builtin_shader(GPU_SHADER_3D_DEPTH_ONLY);
564 }
565
566 void DRW_shader_free(GPUShader *shader)
567 {
568         GPU_shader_free(shader);
569 }
570
571 /** \} */
572
573
574 /* -------------------------------------------------------------------- */
575
576 /** \name Interface (DRW_interface)
577  * \{ */
578
579 static DRWInterface *DRW_interface_create(GPUShader *shader)
580 {
581         DRWInterface *interface = MEM_mallocN(sizeof(DRWInterface), "DRWInterface");
582
583         interface->model = GPU_shader_get_uniform(shader, "ModelMatrix");
584         interface->modelinverse = GPU_shader_get_uniform(shader, "ModelMatrixInverse");
585         interface->modelview = GPU_shader_get_uniform(shader, "ModelViewMatrix");
586         interface->modelviewinverse = GPU_shader_get_uniform(shader, "ModelViewMatrixInverse");
587         interface->projection = GPU_shader_get_uniform(shader, "ProjectionMatrix");
588         interface->projectioninverse = GPU_shader_get_uniform(shader, "ProjectionMatrixInverse");
589         interface->view = GPU_shader_get_uniform(shader, "ViewMatrix");
590         interface->viewinverse = GPU_shader_get_uniform(shader, "ViewMatrixInverse");
591         interface->viewprojection = GPU_shader_get_uniform(shader, "ViewProjectionMatrix");
592         interface->viewprojectioninverse = GPU_shader_get_uniform(shader, "ViewProjectionMatrixInverse");
593         interface->modelviewprojection = GPU_shader_get_uniform(shader, "ModelViewProjectionMatrix");
594         interface->normal = GPU_shader_get_uniform(shader, "NormalMatrix");
595         interface->worldnormal = GPU_shader_get_uniform(shader, "WorldNormalMatrix");
596         interface->camtexfac = GPU_shader_get_uniform(shader, "CameraTexCoFactors");
597         interface->orcotexfac = GPU_shader_get_uniform(shader, "OrcoTexCoFactors[0]");
598         interface->eye = GPU_shader_get_uniform(shader, "eye");
599         interface->clipplanes = GPU_shader_get_uniform(shader, "ClipPlanes[0]");
600         interface->instance_count = 0;
601         interface->attribs_count = 0;
602         interface->attribs_stride = 0;
603         interface->instance_vbo = 0;
604         interface->instance_batch = NULL;
605         interface->tex_bind = GPU_max_textures() - 1;
606         interface->ubo_bind = GPU_max_ubo_binds() - 1;
607
608         memset(&interface->vbo_format, 0, sizeof(Gwn_VertFormat));
609
610         BLI_listbase_clear(&interface->uniforms);
611         BLI_listbase_clear(&interface->attribs);
612
613         return interface;
614 }
615
616 #ifdef USE_GPU_SELECT
617 static DRWInterface *DRW_interface_duplicate(DRWInterface *interface_src)
618 {
619         DRWInterface *interface_dst = MEM_dupallocN(interface_src);
620         BLI_duplicatelist(&interface_dst->uniforms, &interface_src->uniforms);
621         BLI_duplicatelist(&interface_dst->attribs, &interface_src->attribs);
622         return interface_dst;
623 }
624 #endif
625
626 static void DRW_interface_uniform(DRWShadingGroup *shgroup, const char *name,
627                                   DRWUniformType type, const void *value, int length, int arraysize, int bindloc)
628 {
629         DRWUniform *uni = MEM_mallocN(sizeof(DRWUniform), "DRWUniform");
630
631         if (type == DRW_UNIFORM_BLOCK) {
632                 uni->location = GPU_shader_get_uniform_block(shgroup->shader, name);
633         }
634         else {
635                 uni->location = GPU_shader_get_uniform(shgroup->shader, name);
636         }
637
638         BLI_assert(arraysize > 0);
639
640         uni->type = type;
641         uni->value = value;
642         uni->length = length;
643         uni->arraysize = arraysize;
644         uni->bindloc = bindloc; /* for textures */
645
646         if (uni->location == -1) {
647                 if (G.debug & G_DEBUG)
648                         fprintf(stderr, "Uniform '%s' not found!\n", name);
649                 /* Nice to enable eventually, for now eevee uses uniforms that might not exist. */
650                 // BLI_assert(0);
651                 MEM_freeN(uni);
652                 return;
653         }
654
655         BLI_addtail(&shgroup->interface->uniforms, uni);
656 }
657
658 static void DRW_interface_attrib(DRWShadingGroup *shgroup, const char *name, DRWAttribType type, int size, bool dummy)
659 {
660         DRWAttrib *attrib = MEM_mallocN(sizeof(DRWAttrib), "DRWAttrib");
661         GLuint program = GPU_shader_get_program(shgroup->shader);
662
663         attrib->location = glGetAttribLocation(program, name);
664         attrib->type = type;
665         attrib->size = size;
666
667 /* Adding attribute even if not found for now (to keep memory alignment).
668  * Should ideally take vertex format automatically from batch eventually */
669 #if 0
670         if (attrib->location == -1 && !dummy) {
671                 if (G.debug & G_DEBUG)
672                         fprintf(stderr, "Attribute '%s' not found!\n", name);
673                 BLI_assert(0);
674                 MEM_freeN(attrib);
675                 return;
676         }
677 #else
678         UNUSED_VARS(dummy);
679 #endif
680
681         BLI_assert(BLI_strnlen(name, 32) < 32);
682         BLI_strncpy(attrib->name, name, 32);
683
684         shgroup->interface->attribs_count += 1;
685
686         BLI_addtail(&shgroup->interface->attribs, attrib);
687 }
688
689 /** \} */
690
691
692 /* -------------------------------------------------------------------- */
693
694 /** \name Shading Group (DRW_shgroup)
695  * \{ */
696
697 DRWShadingGroup *DRW_shgroup_create(struct GPUShader *shader, DRWPass *pass)
698 {
699         DRWShadingGroup *shgroup = MEM_mallocN(sizeof(DRWShadingGroup), "DRWShadingGroup");
700
701         shgroup->type = DRW_SHG_NORMAL;
702         shgroup->shader = shader;
703         shgroup->interface = DRW_interface_create(shader);
704         shgroup->state_extra = 0;
705         shgroup->state_extra_disable = ~0x0;
706         shgroup->batch_geom = NULL;
707         shgroup->instance_geom = NULL;
708
709         BLI_addtail(&pass->shgroups, shgroup);
710         BLI_listbase_clear(&shgroup->calls);
711
712 #ifdef USE_GPU_SELECT
713         shgroup->pass_parent = pass;
714 #endif
715
716         return shgroup;
717 }
718
719 DRWShadingGroup *DRW_shgroup_material_create(struct GPUMaterial *material, DRWPass *pass)
720 {
721         double time = 0.0; /* TODO make time variable */
722
723         /* TODO : Ideally we should not convert. But since the whole codegen
724          * is relying on GPUPass we keep it as is for now. */
725         GPUPass *gpupass = GPU_material_get_pass(material);
726
727         if (!gpupass) {
728                 /* Shader compilation error */
729                 return NULL;
730         }
731
732         struct GPUShader *shader = GPU_pass_shader(gpupass);
733
734         DRWShadingGroup *grp = DRW_shgroup_create(shader, pass);
735
736         /* Converting dynamic GPUInput to DRWUniform */
737         ListBase *inputs = &gpupass->inputs;
738
739         for (GPUInput *input = inputs->first; input; input = input->next) {
740                 /* Textures */
741                 if (input->ima) {
742                         GPUTexture *tex = GPU_texture_from_blender(input->ima, input->iuser, input->textarget, input->image_isdata, time, 1);
743
744                         if (input->bindtex) {
745                                 DRW_shgroup_uniform_texture(grp, input->shadername, tex);
746                         }
747                 }
748                 /* Color Ramps */
749                 else if (input->tex) {
750                         DRW_shgroup_uniform_texture(grp, input->shadername, input->tex);
751                 }
752                 /* Floats */
753                 else {
754                         switch (input->type) {
755                                 case GPU_FLOAT:
756                                         DRW_shgroup_uniform_float(grp, input->shadername, (float *)input->dynamicvec, 1);
757                                         break;
758                                 case GPU_VEC2:
759                                         DRW_shgroup_uniform_vec2(grp, input->shadername, (float *)input->dynamicvec, 1);
760                                         break;
761                                 case GPU_VEC3:
762                                         DRW_shgroup_uniform_vec3(grp, input->shadername, (float *)input->dynamicvec, 1);
763                                         break;
764                                 case GPU_VEC4:
765                                         DRW_shgroup_uniform_vec4(grp, input->shadername, (float *)input->dynamicvec, 1);
766                                         break;
767                                 case GPU_MAT3:
768                                         DRW_shgroup_uniform_mat3(grp, input->shadername, (float *)input->dynamicvec);
769                                         break;
770                                 case GPU_MAT4:
771                                         DRW_shgroup_uniform_mat4(grp, input->shadername, (float *)input->dynamicvec);
772                                         break;
773                                 default:
774                                         break;
775                         }
776                 }
777         }
778
779         return grp;
780 }
781
782 DRWShadingGroup *DRW_shgroup_material_instance_create(struct GPUMaterial *material, DRWPass *pass, Gwn_Batch *geom)
783 {
784         DRWShadingGroup *shgroup = DRW_shgroup_material_create(material, pass);
785
786         if (shgroup) {
787                 shgroup->type = DRW_SHG_INSTANCE;
788                 shgroup->instance_geom = geom;
789         }
790
791         return shgroup;
792 }
793
794 DRWShadingGroup *DRW_shgroup_instance_create(struct GPUShader *shader, DRWPass *pass, Gwn_Batch *geom)
795 {
796         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
797
798         shgroup->type = DRW_SHG_INSTANCE;
799         shgroup->instance_geom = geom;
800
801         return shgroup;
802 }
803
804 DRWShadingGroup *DRW_shgroup_point_batch_create(struct GPUShader *shader, DRWPass *pass)
805 {
806         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
807
808         shgroup->type = DRW_SHG_POINT_BATCH;
809         DRW_shgroup_attrib_float(shgroup, "pos", 3);
810
811         return shgroup;
812 }
813
814 DRWShadingGroup *DRW_shgroup_line_batch_create(struct GPUShader *shader, DRWPass *pass)
815 {
816         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
817
818         shgroup->type = DRW_SHG_LINE_BATCH;
819         DRW_shgroup_attrib_float(shgroup, "pos", 3);
820
821         return shgroup;
822 }
823
824 /* Very special batch. Use this if you position
825  * your vertices with the vertex shader
826  * and dont need any VBO attrib */
827 DRWShadingGroup *DRW_shgroup_empty_tri_batch_create(struct GPUShader *shader, DRWPass *pass, int size)
828 {
829         DRWShadingGroup *shgroup = DRW_shgroup_create(shader, pass);
830
831         shgroup->type = DRW_SHG_TRIANGLE_BATCH;
832         shgroup->interface->instance_count = size * 3;
833         DRW_interface_attrib(shgroup, "dummy", DRW_ATTRIB_FLOAT, 1, true);
834
835         return shgroup;
836 }
837
838 void DRW_shgroup_free(struct DRWShadingGroup *shgroup)
839 {
840         BLI_freelistN(&shgroup->calls);
841         BLI_freelistN(&shgroup->interface->uniforms);
842         BLI_freelistN(&shgroup->interface->attribs);
843
844         if (shgroup->interface->instance_vbo &&
845                 (shgroup->interface->instance_batch == 0))
846         {
847                 glDeleteBuffers(1, &shgroup->interface->instance_vbo);
848         }
849
850         MEM_freeN(shgroup->interface);
851
852         BATCH_DISCARD_ALL_SAFE(shgroup->batch_geom);
853 }
854
855 void DRW_shgroup_instance_batch(DRWShadingGroup *shgroup, struct Gwn_Batch *instances)
856 {
857         BLI_assert(shgroup->type == DRW_SHG_INSTANCE);
858         BLI_assert(shgroup->interface->instance_batch == NULL);
859
860         shgroup->interface->instance_batch = instances;
861 }
862
863 void DRW_shgroup_call_add(DRWShadingGroup *shgroup, Gwn_Batch *geom, float (*obmat)[4])
864 {
865         BLI_assert(geom != NULL);
866
867         DRWCall *call = MEM_callocN(sizeof(DRWCall), "DRWCall");
868
869         call->head.type = DRW_CALL_SINGLE;
870 #ifdef USE_GPU_SELECT
871         call->head.select_id = g_DRW_select_id;
872 #endif
873
874         if (obmat != NULL) {
875                 copy_m4_m4(call->obmat, obmat);
876         }
877
878         call->geometry = geom;
879
880         BLI_addtail(&shgroup->calls, call);
881 }
882
883 void DRW_shgroup_call_object_add(DRWShadingGroup *shgroup, Gwn_Batch *geom, Object *ob)
884 {
885         BLI_assert(geom != NULL);
886
887         DRWCall *call = MEM_callocN(sizeof(DRWCall), "DRWCall");
888
889         call->head.type = DRW_CALL_SINGLE;
890 #ifdef USE_GPU_SELECT
891         call->head.select_id = g_DRW_select_id;
892 #endif
893
894         copy_m4_m4(call->obmat, ob->obmat);
895         call->geometry = geom;
896         call->ob_data = ob->data;
897
898         BLI_addtail(&shgroup->calls, call);
899 }
900
901 void DRW_shgroup_call_generate_add(
902         DRWShadingGroup *shgroup,
903         DRWCallGenerateFn *geometry_fn, void *user_data,
904         float (*obmat)[4])
905 {
906         BLI_assert(geometry_fn != NULL);
907
908         DRWCallGenerate *call = MEM_callocN(sizeof(DRWCallGenerate), "DRWCallGenerate");
909
910         call->head.type = DRW_CALL_GENERATE;
911 #ifdef USE_GPU_SELECT
912         call->head.select_id = g_DRW_select_id;
913 #endif
914
915         if (obmat != NULL) {
916                 copy_m4_m4(call->obmat, obmat);
917         }
918
919         call->geometry_fn = geometry_fn;
920         call->user_data = user_data;
921
922         BLI_addtail(&shgroup->calls, call);
923 }
924
925 static void sculpt_draw_cb(
926         DRWShadingGroup *shgroup,
927         void (*draw_fn)(DRWShadingGroup *shgroup, Gwn_Batch *geom),
928         void *user_data)
929 {
930         Object *ob = user_data;
931         PBVH *pbvh = ob->sculpt->pbvh;
932
933         if (pbvh) {
934                 BKE_pbvh_draw_cb(
935                         pbvh, NULL, NULL, false,
936                         (void (*)(void *, Gwn_Batch *))draw_fn, shgroup);
937         }
938 }
939
940 void DRW_shgroup_call_sculpt_add(DRWShadingGroup *shgroup, Object *ob, float (*obmat)[4])
941 {
942         DRW_shgroup_call_generate_add(shgroup, sculpt_draw_cb, ob, obmat);
943 }
944
945 void DRW_shgroup_call_dynamic_add_array(DRWShadingGroup *shgroup, const void *attr[], unsigned int attr_len)
946 {
947         DRWInterface *interface = shgroup->interface;
948
949 #ifdef USE_GPU_SELECT
950         if ((G.f & G_PICKSEL) && (interface->instance_count > 0)) {
951                 shgroup = MEM_dupallocN(shgroup);
952                 BLI_listbase_clear(&shgroup->calls);
953
954                 shgroup->interface = interface = DRW_interface_duplicate(interface);
955                 interface->instance_count = 0;
956
957                 BLI_addtail(&shgroup->pass_parent->shgroups, shgroup);
958         }
959 #endif
960
961         unsigned int data_size = sizeof(void *) * interface->attribs_count;
962         int size = sizeof(DRWCallDynamic) + data_size;
963
964         DRWCallDynamic *call = MEM_callocN(size, "DRWCallDynamic");
965
966         BLI_assert(attr_len == interface->attribs_count);
967         UNUSED_VARS_NDEBUG(attr_len);
968
969         call->head.type = DRW_CALL_DYNAMIC;
970 #ifdef USE_GPU_SELECT
971         call->head.select_id = g_DRW_select_id;
972 #endif
973
974         if (data_size != 0) {
975                 memcpy((void *)call->data, attr, data_size);
976         }
977
978         interface->instance_count += 1;
979
980         BLI_addtail(&shgroup->calls, call);
981 }
982
983 /* Used for instancing with no attributes */
984 void DRW_shgroup_set_instance_count(DRWShadingGroup *shgroup, int count)
985 {
986         DRWInterface *interface = shgroup->interface;
987
988         BLI_assert(interface->attribs_count == 0);
989
990         interface->instance_count = count;
991 }
992
993 /**
994  * State is added to #Pass.state while drawing.
995  * Use to temporarily enable draw options.
996  */
997 void DRW_shgroup_state_enable(DRWShadingGroup *shgroup, DRWState state)
998 {
999         shgroup->state_extra |= state;
1000 }
1001
1002 void DRW_shgroup_state_disable(DRWShadingGroup *shgroup, DRWState state)
1003 {
1004         shgroup->state_extra_disable &= ~state;
1005 }
1006
1007 void DRW_shgroup_attrib_float(DRWShadingGroup *shgroup, const char *name, int size)
1008 {
1009         DRW_interface_attrib(shgroup, name, DRW_ATTRIB_FLOAT, size, false);
1010 }
1011
1012 void DRW_shgroup_uniform_texture(DRWShadingGroup *shgroup, const char *name, const GPUTexture *tex)
1013 {
1014         DRWInterface *interface = shgroup->interface;
1015
1016         if (interface->tex_bind < 0) {
1017                 /* TODO alert user */
1018                 printf("Not enough texture slot for %s\n", name);
1019                 return;
1020         }
1021
1022         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_TEXTURE, tex, 0, 1, interface->tex_bind--);
1023 }
1024
1025 void DRW_shgroup_uniform_block(DRWShadingGroup *shgroup, const char *name, const GPUUniformBuffer *ubo)
1026 {
1027         DRWInterface *interface = shgroup->interface;
1028
1029         /* Be carefull: there is also a limit per shader stage. Usually 1/3 of normal limit. */
1030         if (interface->ubo_bind < 0) {
1031                 /* TODO alert user */
1032                 printf("Not enough ubo slots for %s\n", name);
1033                 return;
1034         }
1035
1036         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BLOCK, ubo, 0, 1, interface->ubo_bind--);
1037 }
1038
1039 void DRW_shgroup_uniform_buffer(DRWShadingGroup *shgroup, const char *name, GPUTexture **tex)
1040 {
1041         DRWInterface *interface = shgroup->interface;
1042
1043         if (interface->tex_bind < 0) {
1044                 /* TODO alert user */
1045                 printf("Not enough texture slot for %s\n", name);
1046                 return;
1047         }
1048
1049         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BUFFER, tex, 0, 1, interface->tex_bind--);
1050 }
1051
1052 void DRW_shgroup_uniform_bool(DRWShadingGroup *shgroup, const char *name, const bool *value, int arraysize)
1053 {
1054         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_BOOL, value, 1, arraysize, 0);
1055 }
1056
1057 void DRW_shgroup_uniform_float(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1058 {
1059         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 1, arraysize, 0);
1060 }
1061
1062 void DRW_shgroup_uniform_vec2(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1063 {
1064         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 2, arraysize, 0);
1065 }
1066
1067 void DRW_shgroup_uniform_vec3(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1068 {
1069         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 3, arraysize, 0);
1070 }
1071
1072 void DRW_shgroup_uniform_vec4(DRWShadingGroup *shgroup, const char *name, const float *value, int arraysize)
1073 {
1074         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_FLOAT, value, 4, arraysize, 0);
1075 }
1076
1077 void DRW_shgroup_uniform_short_to_int(DRWShadingGroup *shgroup, const char *name, const short *value, int arraysize)
1078 {
1079         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_SHORT_TO_INT, value, 1, arraysize, 0);
1080 }
1081
1082 void DRW_shgroup_uniform_short_to_float(DRWShadingGroup *shgroup, const char *name, const short *value, int arraysize)
1083 {
1084         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_SHORT_TO_FLOAT, value, 1, arraysize, 0);
1085 }
1086
1087 void DRW_shgroup_uniform_int(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1088 {
1089         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 1, arraysize, 0);
1090 }
1091
1092 void DRW_shgroup_uniform_ivec2(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1093 {
1094         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 2, arraysize, 0);
1095 }
1096
1097 void DRW_shgroup_uniform_ivec3(DRWShadingGroup *shgroup, const char *name, const int *value, int arraysize)
1098 {
1099         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_INT, value, 3, arraysize, 0);
1100 }
1101
1102 void DRW_shgroup_uniform_mat3(DRWShadingGroup *shgroup, const char *name, const float *value)
1103 {
1104         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT3, value, 9, 1, 0);
1105 }
1106
1107 void DRW_shgroup_uniform_mat4(DRWShadingGroup *shgroup, const char *name, const float *value)
1108 {
1109         DRW_interface_uniform(shgroup, name, DRW_UNIFORM_MAT4, value, 16, 1, 0);
1110 }
1111
1112 /* Creates a VBO containing OGL primitives for all DRWCallDynamic */
1113 static void shgroup_dynamic_batch(DRWShadingGroup *shgroup)
1114 {
1115         DRWInterface *interface = shgroup->interface;
1116         int nbr = interface->instance_count;
1117
1118         Gwn_PrimType type = (shgroup->type == DRW_SHG_POINT_BATCH) ? GWN_PRIM_POINTS :
1119                              (shgroup->type == DRW_SHG_TRIANGLE_BATCH) ? GWN_PRIM_TRIS : GWN_PRIM_LINES;
1120
1121         if (nbr == 0)
1122                 return;
1123
1124         /* Upload Data */
1125         if (interface->vbo_format.attrib_ct == 0) {
1126                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next) {
1127                         BLI_assert(attrib->size <= 4); /* matrices have no place here for now */
1128                         if (attrib->type == DRW_ATTRIB_FLOAT) {
1129                                 attrib->format_id = GWN_vertformat_attr_add(
1130                                         &interface->vbo_format, attrib->name, GWN_COMP_F32, attrib->size, GWN_FETCH_FLOAT);
1131                         }
1132                         else if (attrib->type == DRW_ATTRIB_INT) {
1133                                 attrib->format_id = GWN_vertformat_attr_add(
1134                                         &interface->vbo_format, attrib->name, GWN_COMP_I8, attrib->size, GWN_FETCH_INT);
1135                         }
1136                         else {
1137                                 BLI_assert(false);
1138                         }
1139                 }
1140         }
1141
1142         Gwn_VertBuf *vbo = GWN_vertbuf_create_with_format(&interface->vbo_format);
1143         GWN_vertbuf_data_alloc(vbo, nbr);
1144
1145         int j = 0;
1146         for (DRWCallDynamic *call = shgroup->calls.first; call; call = call->head.next, j++) {
1147                 int i = 0;
1148                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
1149                         GWN_vertbuf_attr_set(vbo, attrib->format_id, j, call->data[i]);
1150                 }
1151         }
1152
1153         /* TODO make the batch dynamic instead of freeing it every times */
1154         if (shgroup->batch_geom)
1155                 GWN_batch_discard_all(shgroup->batch_geom);
1156
1157         shgroup->batch_geom = GWN_batch_create(type, vbo, NULL);
1158 }
1159
1160 static void shgroup_dynamic_instance(DRWShadingGroup *shgroup)
1161 {
1162         int i = 0;
1163         int offset = 0;
1164         DRWInterface *interface = shgroup->interface;
1165         int buffer_size = 0;
1166
1167         if (interface->instance_batch != NULL) {
1168                 return;
1169         }
1170
1171         /* TODO We still need this because gawain does not support Matrix attribs. */
1172         if (interface->instance_count == 0) {
1173                 if (interface->instance_vbo) {
1174                         glDeleteBuffers(1, &interface->instance_vbo);
1175                         interface->instance_vbo = 0;
1176                 }
1177                 return;
1178         }
1179
1180         /* only once */
1181         if (interface->attribs_stride == 0) {
1182                 for (DRWAttrib *attrib = interface->attribs.first; attrib; attrib = attrib->next, i++) {
1183                         BLI_assert(attrib->type == DRW_ATTRIB_FLOAT); /* Only float for now */
1184                         interface->attribs_stride += attrib->size;
1185                         interface->attribs_size[i] = attrib->size;
1186                         interface->attribs_loc[i] = attrib->location;
1187                 }
1188         }
1189
1190         /* Gather Data */
1191         buffer_size = sizeof(float) * interface->attribs_stride * interface->instance_count;
1192         float *data = MEM_mallocN(buffer_size, "Instance VBO data");
1193
1194         for (DRWCallDynamic *call = shgroup->calls.first; call; call = call->head.next) {
1195                 for (int j = 0; j < interface->attribs_count; ++j) {
1196                         memcpy(data + offset, call->data[j], sizeof(float) * interface->attribs_size[j]);
1197                         offset += interface->attribs_size[j];
1198                 }
1199         }
1200
1201         /* TODO poke mike to add this to gawain */
1202         if (interface->instance_vbo) {
1203                 glDeleteBuffers(1, &interface->instance_vbo);
1204                 interface->instance_vbo = 0;
1205         }
1206
1207         glGenBuffers(1, &interface->instance_vbo);
1208         glBindBuffer(GL_ARRAY_BUFFER, interface->instance_vbo);
1209         glBufferData(GL_ARRAY_BUFFER, buffer_size, data, GL_STATIC_DRAW);
1210
1211         MEM_freeN(data);
1212 }
1213
1214 static void shgroup_dynamic_batch_from_calls(DRWShadingGroup *shgroup)
1215 {
1216         if ((shgroup->interface->instance_vbo || shgroup->batch_geom) &&
1217             (G.debug_value == 667))
1218         {
1219                 return;
1220         }
1221
1222         if (shgroup->type == DRW_SHG_INSTANCE) {
1223                 shgroup_dynamic_instance(shgroup);
1224         }
1225         else {
1226                 shgroup_dynamic_batch(shgroup);
1227         }
1228 }
1229
1230 /** \} */
1231
1232
1233 /* -------------------------------------------------------------------- */
1234
1235 /** \name Passes (DRW_pass)
1236  * \{ */
1237
1238 DRWPass *DRW_pass_create(const char *name, DRWState state)
1239 {
1240         DRWPass *pass = MEM_callocN(sizeof(DRWPass), name);
1241         pass->state = state;
1242         BLI_strncpy(pass->name, name, MAX_PASS_NAME);
1243
1244         BLI_listbase_clear(&pass->shgroups);
1245
1246         return pass;
1247 }
1248
1249 void DRW_pass_free(DRWPass *pass)
1250 {
1251         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
1252                 DRW_shgroup_free(shgroup);
1253         }
1254
1255         glDeleteQueries(2, pass->timer_queries);
1256         BLI_freelistN(&pass->shgroups);
1257 }
1258
1259 void DRW_pass_foreach_shgroup(DRWPass *pass, void (*callback)(void *userData, DRWShadingGroup *shgrp), void *userData)
1260 {
1261         for (DRWShadingGroup *shgroup = pass->shgroups.first; shgroup; shgroup = shgroup->next) {
1262                 callback(userData, shgroup);
1263         }
1264 }
1265
1266 typedef struct ZSortData {
1267         float *axis;
1268         float *origin;
1269 } ZSortData;
1270
1271 static int pass_shgroup_dist_sort(void *thunk, const void *a, const void *b)
1272 {
1273         const DRWShadingGroup *shgrp_a = (const DRWShadingGroup *)a;
1274         const DRWShadingGroup *shgrp_b = (const DRWShadingGroup *)b;
1275         const DRWCall *call_a = (DRWCall *)(shgrp_a)->calls.first;
1276         const DRWCall *call_b = (DRWCall *)(shgrp_b)->calls.first;
1277         const ZSortData *zsortdata = (ZSortData *)thunk;
1278
1279         float tmp[3];
1280         sub_v3_v3v3(tmp, zsortdata->origin, call_a->obmat[3]);
1281         const float a_sq = dot_v3v3(zsortdata->axis, tmp);
1282         sub_v3_v3v3(tmp, zsortdata->origin, call_b->obmat[3]);
1283         const float b_sq = dot_v3v3(zsortdata->axis, tmp);
1284
1285         if      (a_sq < b_sq) return  1;
1286         else if (a_sq > b_sq) return -1;
1287         else {
1288                 /* If there is a depth prepass put it before */
1289                 if ((shgrp_a->state_extra & DRW_STATE_WRITE_DEPTH) != 0) {
1290                         return -1;
1291                 }
1292                 else if ((shgrp_b->state_extra & DRW_STATE_WRITE_DEPTH) != 0) {
1293                         return  1;
1294                 }
1295                 else return  0;
1296         }
1297 }
1298
1299 /**
1300  * Sort Shading groups by decreasing Z of their first draw call.
1301  * This is usefull for order dependant effect such as transparency.
1302  **/
1303 void DRW_pass_sort_shgroup_z(DRWPass *pass)
1304 {
1305         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1306
1307         float (*viewinv)[4];
1308         viewinv = (viewport_matrix_override.override[DRW_MAT_VIEWINV])
1309                   ? viewport_matrix_override.mat[DRW_MAT_VIEWINV] : rv3d->viewinv;
1310
1311         ZSortData zsortdata = {viewinv[2], viewinv[3]};
1312         BLI_listbase_sort_r(&pass->shgroups, pass_shgroup_dist_sort, &zsortdata);
1313 }
1314
1315 /** \} */
1316
1317
1318 /* -------------------------------------------------------------------- */
1319
1320 /** \name Draw (DRW_draw)
1321  * \{ */
1322
1323 static void DRW_state_set(DRWState state)
1324 {
1325         if (DST.state == state) {
1326                 return;
1327         }
1328
1329
1330 #define CHANGED_TO(f) \
1331         ((DST.state & (f)) ? \
1332                 ((state & (f)) ?  0 : -1) : \
1333                 ((state & (f)) ?  1 :  0))
1334
1335 #define CHANGED_ANY(f) \
1336         ((DST.state & (f)) != (state & (f)))
1337
1338 #define CHANGED_ANY_STORE_VAR(f, enabled) \
1339         ((DST.state & (f)) != (enabled = (state & (f))))
1340
1341         /* Depth Write */
1342         {
1343                 int test;
1344                 if ((test = CHANGED_TO(DRW_STATE_WRITE_DEPTH))) {
1345                         if (test == 1) {
1346                                 glDepthMask(GL_TRUE);
1347                         }
1348                         else {
1349                                 glDepthMask(GL_FALSE);
1350                         }
1351                 }
1352         }
1353
1354         /* Color Write */
1355         {
1356                 int test;
1357                 if ((test = CHANGED_TO(DRW_STATE_WRITE_COLOR))) {
1358                         if (test == 1) {
1359                                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1360                         }
1361                         else {
1362                                 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1363                         }
1364                 }
1365         }
1366
1367         /* Cull */
1368         {
1369                 DRWState test;
1370                 if (CHANGED_ANY_STORE_VAR(
1371                         DRW_STATE_CULL_BACK | DRW_STATE_CULL_FRONT,
1372                         test))
1373                 {
1374                         if (test) {
1375                                 glEnable(GL_CULL_FACE);
1376
1377                                 if ((state & DRW_STATE_CULL_BACK) != 0) {
1378                                         glCullFace(GL_BACK);
1379                                 }
1380                                 else if ((state & DRW_STATE_CULL_FRONT) != 0) {
1381                                         glCullFace(GL_FRONT);
1382                                 }
1383                                 else {
1384                                         BLI_assert(0);
1385                                 }
1386                         }
1387                         else {
1388                                 glDisable(GL_CULL_FACE);
1389                         }
1390                 }
1391         }
1392
1393         /* Depth Test */
1394         {
1395                 DRWState test;
1396                 if (CHANGED_ANY_STORE_VAR(
1397                         DRW_STATE_DEPTH_LESS | DRW_STATE_DEPTH_EQUAL | DRW_STATE_DEPTH_GREATER | DRW_STATE_DEPTH_ALWAYS,
1398                         test))
1399                 {
1400                         if (test) {
1401                                 glEnable(GL_DEPTH_TEST);
1402
1403                                 if (state & DRW_STATE_DEPTH_LESS) {
1404                                         glDepthFunc(GL_LEQUAL);
1405                                 }
1406                                 else if (state & DRW_STATE_DEPTH_EQUAL) {
1407                                         glDepthFunc(GL_EQUAL);
1408                                 }
1409                                 else if (state & DRW_STATE_DEPTH_GREATER) {
1410                                         glDepthFunc(GL_GREATER);
1411                                 }
1412                                 else if (state & DRW_STATE_DEPTH_ALWAYS) {
1413                                         glDepthFunc(GL_ALWAYS);
1414                                 }
1415                                 else {
1416                                         BLI_assert(0);
1417                                 }
1418                         }
1419                         else {
1420                                 glDisable(GL_DEPTH_TEST);
1421                         }
1422                 }
1423         }
1424
1425         /* Wire Width */
1426         {
1427                 if (CHANGED_ANY(DRW_STATE_WIRE | DRW_STATE_WIRE_LARGE)) {
1428                         if ((state & DRW_STATE_WIRE) != 0) {
1429                                 glLineWidth(1.0f);
1430                         }
1431                         else if ((state & DRW_STATE_WIRE_LARGE) != 0) {
1432                                 glLineWidth(UI_GetThemeValuef(TH_OUTLINE_WIDTH) * 2.0f);
1433                         }
1434                         else {
1435                                 /* do nothing */
1436                         }
1437                 }
1438         }
1439
1440         /* Points Size */
1441         {
1442                 int test;
1443                 if ((test = CHANGED_TO(DRW_STATE_POINT))) {
1444                         if (test == 1) {
1445                                 GPU_enable_program_point_size();
1446                                 glPointSize(5.0f);
1447                         }
1448                         else {
1449                                 GPU_disable_program_point_size();
1450                         }
1451                 }
1452         }
1453
1454         /* Blending (all buffer) */
1455         {
1456                 int test;
1457                 if (CHANGED_ANY_STORE_VAR(
1458                         DRW_STATE_BLEND | DRW_STATE_ADDITIVE | DRW_STATE_MULTIPLY | DRW_STATE_TRANSMISSION,
1459                         test))
1460                 {
1461                         if (test) {
1462                                 glEnable(GL_BLEND);
1463
1464                                 if ((state & DRW_STATE_BLEND) != 0) {
1465                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1466                                 }
1467                                 else if ((state & DRW_STATE_MULTIPLY) != 0) {
1468                                         glBlendFunc(GL_DST_COLOR, GL_ZERO);
1469                                 }
1470                                 else if ((state & DRW_STATE_TRANSMISSION) != 0) {
1471                                         glBlendFunc(GL_ONE, GL_SRC_ALPHA);
1472                                 }
1473                                 else if ((state & DRW_STATE_ADDITIVE) != 0) {
1474                                         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1475                                 }
1476                                 else {
1477                                         BLI_assert(0);
1478                                 }
1479                         }
1480                         else {
1481                                 glDisable(GL_BLEND);
1482                         }
1483                 }
1484         }
1485
1486         /* Clip Planes */
1487         {
1488                 int test;
1489                 if ((test = CHANGED_TO(DRW_STATE_CLIP_PLANES))) {
1490                         if (test == 1) {
1491                                 for (int i = 0; i < DST.num_clip_planes; ++i) {
1492                                         glEnable(GL_CLIP_DISTANCE0 + i);
1493                                 }
1494                         }
1495                         else {
1496                                 for (int i = 0; i < MAX_CLIP_PLANES; ++i) {
1497                                         glDisable(GL_CLIP_DISTANCE0 + i);
1498                                 }
1499                         }
1500                 }
1501         }
1502
1503         /* Line Stipple */
1504         {
1505                 int test;
1506                 if (CHANGED_ANY_STORE_VAR(
1507                         DRW_STATE_STIPPLE_2 | DRW_STATE_STIPPLE_3 | DRW_STATE_STIPPLE_4,
1508                         test))
1509                 {
1510                         if (test) {
1511                                 if ((state & DRW_STATE_STIPPLE_2) != 0) {
1512                                         setlinestyle(2);
1513                                 }
1514                                 else if ((state & DRW_STATE_STIPPLE_3) != 0) {
1515                                         setlinestyle(3);
1516                                 }
1517                                 else if ((state & DRW_STATE_STIPPLE_4) != 0) {
1518                                         setlinestyle(4);
1519                                 }
1520                                 else {
1521                                         BLI_assert(0);
1522                                 }
1523                         }
1524                         else {
1525                                 setlinestyle(0);
1526                         }
1527                 }
1528         }
1529
1530         /* Stencil */
1531         {
1532                 DRWState test;
1533                 if (CHANGED_ANY_STORE_VAR(
1534                         DRW_STATE_WRITE_STENCIL_SELECT |
1535                         DRW_STATE_WRITE_STENCIL_ACTIVE |
1536                         DRW_STATE_TEST_STENCIL_SELECT |
1537                         DRW_STATE_TEST_STENCIL_ACTIVE,
1538                         test))
1539                 {
1540                         if (test) {
1541                                 glEnable(GL_STENCIL_TEST);
1542
1543                                 /* Stencil Write */
1544                                 if ((state & DRW_STATE_WRITE_STENCIL_SELECT) != 0) {
1545                                         glStencilMask(STENCIL_SELECT);
1546                                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1547                                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_SELECT);
1548                                 }
1549                                 else if ((state & DRW_STATE_WRITE_STENCIL_ACTIVE) != 0) {
1550                                         glStencilMask(STENCIL_ACTIVE);
1551                                         glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1552                                         glStencilFunc(GL_ALWAYS, 0xFF, STENCIL_ACTIVE);
1553                                 }
1554                                 /* Stencil Test */
1555                                 else if ((state & DRW_STATE_TEST_STENCIL_SELECT) != 0) {
1556                                         glStencilMask(0x00); /* disable write */
1557                                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_SELECT);
1558                                 }
1559                                 else if ((state & DRW_STATE_TEST_STENCIL_ACTIVE) != 0) {
1560                                         glStencilMask(0x00); /* disable write */
1561                                         glStencilFunc(GL_NOTEQUAL, 0xFF, STENCIL_ACTIVE);
1562                                 }
1563                                 else {
1564                                         BLI_assert(0);
1565                                 }
1566                         }
1567                         else {
1568                                 /* disable write & test */
1569                                 glStencilMask(0x00);
1570                                 glStencilFunc(GL_ALWAYS, 1, 0xFF);
1571                                 glDisable(GL_STENCIL_TEST);
1572                         }
1573                 }
1574         }
1575
1576 #undef CHANGED_TO
1577 #undef CHANGED_ANY
1578 #undef CHANGED_ANY_STORE_VAR
1579
1580         DST.state = state;
1581 }
1582
1583 typedef struct DRWBoundTexture {
1584         struct DRWBoundTexture *next, *prev;
1585         GPUTexture *tex;
1586 } DRWBoundTexture;
1587
1588 static void draw_geometry_prepare(
1589         DRWShadingGroup *shgroup, const float (*obmat)[4], const float *texcoloc, const float *texcosize)
1590 {
1591         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1592         DRWInterface *interface = shgroup->interface;
1593
1594         float mvp[4][4], mv[4][4], mi[4][4], mvi[4][4], pi[4][4], n[3][3], wn[3][3];
1595         float orcofacs[2][3] = {{0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f}};
1596         float eye[3] = { 0.0f, 0.0f, 1.0f }; /* looking into the screen */
1597
1598         bool do_pi = (interface->projectioninverse != -1);
1599         bool do_mvp = (interface->modelviewprojection != -1);
1600         bool do_mi = (interface->modelinverse != -1);
1601         bool do_mv = (interface->modelview != -1);
1602         bool do_mvi = (interface->modelviewinverse != -1);
1603         bool do_n = (interface->normal != -1);
1604         bool do_wn = (interface->worldnormal != -1);
1605         bool do_eye = (interface->eye != -1);
1606         bool do_orco = (interface->orcotexfac != -1) && (texcoloc != NULL) && (texcosize != NULL);
1607
1608         /* Matrix override */
1609         float (*persmat)[4];
1610         float (*persinv)[4];
1611         float (*viewmat)[4];
1612         float (*viewinv)[4];
1613         float (*winmat)[4];
1614         float (*wininv)[4];
1615
1616         persmat = (viewport_matrix_override.override[DRW_MAT_PERS])
1617                   ? viewport_matrix_override.mat[DRW_MAT_PERS] : rv3d->persmat;
1618         persinv = (viewport_matrix_override.override[DRW_MAT_PERSINV])
1619                   ? viewport_matrix_override.mat[DRW_MAT_PERSINV] : rv3d->persinv;
1620         viewmat = (viewport_matrix_override.override[DRW_MAT_VIEW])
1621                   ? viewport_matrix_override.mat[DRW_MAT_VIEW] : rv3d->viewmat;
1622         viewinv = (viewport_matrix_override.override[DRW_MAT_VIEWINV])
1623                   ? viewport_matrix_override.mat[DRW_MAT_VIEWINV] : rv3d->viewinv;
1624         winmat = (viewport_matrix_override.override[DRW_MAT_WIN])
1625                   ? viewport_matrix_override.mat[DRW_MAT_WIN] : rv3d->winmat;
1626
1627         if (do_pi) {
1628                 if (viewport_matrix_override.override[DRW_MAT_WININV]) {
1629                         wininv = viewport_matrix_override.mat[DRW_MAT_WININV];
1630                 }
1631                 else {
1632                         invert_m4_m4(pi, winmat);
1633                         wininv = pi;
1634                 }
1635         }
1636         if (do_mi) {
1637                 invert_m4_m4(mi, obmat);
1638         }
1639         if (do_mvp) {
1640                 mul_m4_m4m4(mvp, persmat, obmat);
1641         }
1642         if (do_mv || do_mvi || do_n || do_eye) {
1643                 mul_m4_m4m4(mv, viewmat, obmat);
1644         }
1645         if (do_mvi) {
1646                 invert_m4_m4(mvi, mv);
1647         }
1648         if (do_n || do_eye) {
1649                 copy_m3_m4(n, mv);
1650                 invert_m3(n);
1651                 transpose_m3(n);
1652         }
1653         if (do_wn) {
1654                 copy_m3_m4(wn, obmat);
1655                 invert_m3(wn);
1656                 transpose_m3(wn);
1657         }
1658         if (do_eye) {
1659                 /* Used by orthographic wires */
1660                 float tmp[3][3];
1661                 invert_m3_m3(tmp, n);
1662                 /* set eye vector, transformed to object coords */
1663                 mul_m3_v3(tmp, eye);
1664         }
1665         if (do_orco) {
1666                 mul_v3_v3fl(orcofacs[1], texcosize, 2.0f);
1667                 invert_v3(orcofacs[1]);
1668                 sub_v3_v3v3(orcofacs[0], texcoloc, texcosize);
1669                 negate_v3(orcofacs[0]);
1670                 mul_v3_v3(orcofacs[0], orcofacs[1]); /* result in a nice MADD in the shader */
1671         }
1672
1673         /* Should be really simple */
1674         /* step 1 : bind object dependent matrices */
1675         /* TODO : Some of these are not object dependant.
1676          * They should be grouped inside a UBO updated once per redraw.
1677          * The rest can also go into a UBO to reduce API calls. */
1678         GPU_shader_uniform_vector(shgroup->shader, interface->model, 16, 1, (float *)obmat);
1679         GPU_shader_uniform_vector(shgroup->shader, interface->modelinverse, 16, 1, (float *)mi);
1680         GPU_shader_uniform_vector(shgroup->shader, interface->modelviewprojection, 16, 1, (float *)mvp);
1681         GPU_shader_uniform_vector(shgroup->shader, interface->viewinverse, 16, 1, (float *)viewinv);
1682         GPU_shader_uniform_vector(shgroup->shader, interface->viewprojection, 16, 1, (float *)persmat);
1683         GPU_shader_uniform_vector(shgroup->shader, interface->viewprojectioninverse, 16, 1, (float *)persinv);
1684         GPU_shader_uniform_vector(shgroup->shader, interface->projection, 16, 1, (float *)winmat);
1685         GPU_shader_uniform_vector(shgroup->shader, interface->projectioninverse, 16, 1, (float *)wininv);
1686         GPU_shader_uniform_vector(shgroup->shader, interface->view, 16, 1, (float *)viewmat);
1687         GPU_shader_uniform_vector(shgroup->shader, interface->modelview, 16, 1, (float *)mv);
1688         GPU_shader_uniform_vector(shgroup->shader, interface->modelviewinverse, 16, 1, (float *)mvi);
1689         GPU_shader_uniform_vector(shgroup->shader, interface->normal, 9, 1, (float *)n);
1690         GPU_shader_uniform_vector(shgroup->shader, interface->worldnormal, 9, 1, (float *)wn);
1691         GPU_shader_uniform_vector(shgroup->shader, interface->camtexfac, 4, 1, (float *)rv3d->viewcamtexcofac);
1692         GPU_shader_uniform_vector(shgroup->shader, interface->orcotexfac, 3, 2, (float *)orcofacs);
1693         GPU_shader_uniform_vector(shgroup->shader, interface->eye, 3, 1, (float *)eye);
1694         GPU_shader_uniform_vector(shgroup->shader, interface->clipplanes, 4, DST.num_clip_planes, (float *)DST.clip_planes_eq);
1695 }
1696
1697 static void draw_geometry_execute(DRWShadingGroup *shgroup, Gwn_Batch *geom)
1698 {
1699         DRWInterface *interface = shgroup->interface;
1700         /* step 2 : bind vertex array & draw */
1701         GWN_batch_program_set(geom, GPU_shader_get_program(shgroup->shader), GPU_shader_get_interface(shgroup->shader));
1702         if (interface->instance_batch) {
1703                 GWN_batch_draw_stupid_instanced_with_batch(geom, interface->instance_batch);
1704         }
1705         else if (interface->instance_vbo) {
1706                 GWN_batch_draw_stupid_instanced(geom, interface->instance_vbo, interface->instance_count, interface->attribs_count,
1707                                             interface->attribs_stride, interface->attribs_size, interface->attribs_loc);
1708         }
1709         else {
1710                 GWN_batch_draw_stupid(geom);
1711         }
1712 }
1713
1714 static void draw_geometry(DRWShadingGroup *shgroup, Gwn_Batch *geom, const float (*obmat)[4], ID *ob_data)
1715 {
1716         float *texcoloc = NULL;
1717         float *texcosize = NULL;
1718
1719         if (ob_data != NULL) {
1720                 switch (GS(ob_data->name)) {
1721                         case OB_MESH:
1722                                 BKE_mesh_texspace_get_reference((Mesh *)ob_data, NULL, &texcoloc, NULL, &texcosize);
1723                                 /* TODO, curve, metaball? */
1724                         default:
1725                                 break;
1726                 }
1727         }
1728
1729         draw_geometry_prepare(shgroup, obmat, texcoloc, texcosize);
1730
1731         draw_geometry_execute(shgroup, geom);
1732 }
1733
1734 static void draw_shgroup(DRWShadingGroup *shgroup, DRWState pass_state)
1735 {
1736         BLI_assert(shgroup->shader);
1737         BLI_assert(shgroup->interface);
1738
1739         DRWInterface *interface = shgroup->interface;
1740         GPUTexture *tex;
1741         int val;
1742         float fval;
1743
1744         if (DST.shader != shgroup->shader) {
1745                 if (DST.shader) GPU_shader_unbind();
1746                 GPU_shader_bind(shgroup->shader);
1747                 DST.shader = shgroup->shader;
1748         }
1749
1750         const bool is_normal = ELEM(shgroup->type, DRW_SHG_NORMAL);
1751
1752         if (!is_normal) {
1753                 shgroup_dynamic_batch_from_calls(shgroup);
1754         }
1755
1756         DRW_state_set((pass_state & shgroup->state_extra_disable) | shgroup->state_extra);
1757
1758         /* Binding Uniform */
1759         /* Don't check anything, Interface should already contain the least uniform as possible */
1760         for (DRWUniform *uni = interface->uniforms.first; uni; uni = uni->next) {
1761                 DRWBoundTexture *bound_tex;
1762
1763                 switch (uni->type) {
1764                         case DRW_UNIFORM_SHORT_TO_INT:
1765                                 val = (int)*((short *)uni->value);
1766                                 GPU_shader_uniform_vector_int(
1767                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)&val);
1768                                 break;
1769                         case DRW_UNIFORM_SHORT_TO_FLOAT:
1770                                 fval = (float)*((short *)uni->value);
1771                                 GPU_shader_uniform_vector(
1772                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)&fval);
1773                                 break;
1774                         case DRW_UNIFORM_BOOL:
1775                         case DRW_UNIFORM_INT:
1776                                 GPU_shader_uniform_vector_int(
1777                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (int *)uni->value);
1778                                 break;
1779                         case DRW_UNIFORM_FLOAT:
1780                         case DRW_UNIFORM_MAT3:
1781                         case DRW_UNIFORM_MAT4:
1782                                 GPU_shader_uniform_vector(
1783                                         shgroup->shader, uni->location, uni->length, uni->arraysize, (float *)uni->value);
1784                                 break;
1785                         case DRW_UNIFORM_TEXTURE:
1786                                 tex = (GPUTexture *)uni->value;
1787                                 BLI_assert(tex);
1788                                 GPU_texture_bind(tex, uni->bindloc);
1789
1790                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1791                                 bound_tex->tex = tex;
1792                                 BLI_addtail(&DST.bound_texs, bound_tex);
1793
1794                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1795                                 break;
1796                         case DRW_UNIFORM_BUFFER:
1797                                 if (!DRW_state_is_fbo()) {
1798                                         break;
1799                                 }
1800                                 tex = *((GPUTexture **)uni->value);
1801                                 BLI_assert(tex);
1802                                 GPU_texture_bind(tex, uni->bindloc);
1803
1804                                 bound_tex = MEM_callocN(sizeof(DRWBoundTexture), "DRWBoundTexture");
1805                                 bound_tex->tex = tex;
1806                                 BLI_addtail(&DST.bound_texs, bound_tex);
1807
1808                                 GPU_shader_uniform_texture(shgroup->shader, uni->location, tex);
1809                                 break;
1810                         case DRW_UNIFORM_BLOCK:
1811                                 GPU_uniformbuffer_bind((GPUUniformBuffer *)uni->value, uni->bindloc);
1812                                 GPU_shader_uniform_buffer(shgroup->shader, uni->location, (GPUUniformBuffer *)uni->value);
1813                                 break;
1814                 }
1815         }
1816
1817 #ifdef USE_GPU_SELECT
1818         /* use the first item because of selection we only ever add one */
1819 #  define GPU_SELECT_LOAD_IF_PICKSEL(_call) \
1820         if ((G.f & G_PICKSEL) && (_call)) { \
1821                 GPU_select_load_id((_call)->head.select_id); \
1822         } ((void)0)
1823 #  define GPU_SELECT_LOAD_IF_PICKSEL_LIST(_call_ls) \
1824         if ((G.f & G_PICKSEL) && (_call_ls)->first) { \
1825                 BLI_assert(BLI_listbase_is_single(_call_ls)); \
1826                 GPU_select_load_id(((DRWCall *)(_call_ls)->first)->head.select_id); \
1827         } ((void)0)
1828 #else
1829 #  define GPU_SELECT_LOAD_IF_PICKSEL(call)
1830 #  define GPU_SELECT_LOAD_IF_PICKSEL_LIST(call)
1831 #endif
1832
1833         /* Rendering Calls */
1834         if (!is_normal) {
1835                 /* Replacing multiple calls with only one */
1836                 float obmat[4][4];
1837                 unit_m4(obmat);
1838
1839                 if (shgroup->type == DRW_SHG_INSTANCE &&
1840                         (interface->instance_count > 0 || interface->instance_batch != NULL))
1841                 {
1842                         GPU_SELECT_LOAD_IF_PICKSEL_LIST(&shgroup->calls);
1843                         draw_geometry(shgroup, shgroup->instance_geom, obmat, NULL);
1844                 }
1845                 else {
1846                         /* Some dynamic batch can have no geom (no call to aggregate) */
1847                         if (shgroup->batch_geom) {
1848                                 GPU_SELECT_LOAD_IF_PICKSEL_LIST(&shgroup->calls);
1849                                 draw_geometry(shgroup, shgroup->batch_geom, obmat, NULL);
1850                         }
1851                 }
1852         }
1853         else {
1854                 for (DRWCall *call = shgroup->calls.first; call; call = call->head.next) {
1855                         bool neg_scale = is_negative_m4(call->obmat);
1856
1857                         /* Negative scale objects */
1858                         if (neg_scale) {
1859                                 glFrontFace(DST.backface);
1860                         }
1861
1862                         GPU_SELECT_LOAD_IF_PICKSEL(call);
1863
1864                         if (call->head.type == DRW_CALL_SINGLE) {
1865                                 draw_geometry(shgroup, call->geometry, call->obmat, call->ob_data);
1866                         }
1867                         else {
1868                                 BLI_assert(call->head.type == DRW_CALL_GENERATE);
1869                                 DRWCallGenerate *callgen = ((DRWCallGenerate *)call);
1870                                 draw_geometry_prepare(shgroup, callgen->obmat, NULL, NULL);
1871                                 callgen->geometry_fn(shgroup, draw_geometry_execute, callgen->user_data);
1872                         }
1873
1874                         /* Reset state */
1875                         if (neg_scale) {
1876                                 glFrontFace(DST.frontface);
1877                         }
1878                 }
1879         }
1880
1881         /* TODO: remove, (currently causes alpha issue with sculpt, need to investigate) */
1882         DRW_state_reset();
1883 }
1884
1885 static void DRW_draw_pass_ex(DRWPass *pass, DRWShadingGroup *start_group, DRWShadingGroup *end_group)
1886 {
1887         /* Start fresh */
1888         DST.shader = NULL;
1889         DST.tex_bind_id = 0;
1890
1891         DRW_state_set(pass->state);
1892         BLI_listbase_clear(&DST.bound_texs);
1893
1894         /* Init Timer queries */
1895         if (pass->timer_queries[0] == 0) {
1896                 pass->front_idx = 0;
1897                 pass->back_idx = 1;
1898
1899                 glGenQueries(2, pass->timer_queries);
1900
1901                 /* dummy query, avoid gl error */
1902                 glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->front_idx]);
1903                 glEndQuery(GL_TIME_ELAPSED);
1904         }
1905         else {
1906                 /* swap indices */
1907                 unsigned int tmp = pass->back_idx;
1908                 pass->back_idx = pass->front_idx;
1909                 pass->front_idx = tmp;
1910         }
1911
1912         if (!pass->wasdrawn) {
1913                 /* issue query for the next frame */
1914                 glBeginQuery(GL_TIME_ELAPSED, pass->timer_queries[pass->back_idx]);
1915         }
1916
1917         for (DRWShadingGroup *shgroup = start_group; shgroup; shgroup = shgroup->next) {
1918                 draw_shgroup(shgroup, pass->state);
1919                 /* break if upper limit */
1920                 if (shgroup == end_group) {
1921                         break;
1922                 }
1923         }
1924
1925         /* Clear Bound textures */
1926         for (DRWBoundTexture *bound_tex = DST.bound_texs.first; bound_tex; bound_tex = bound_tex->next) {
1927                 GPU_texture_unbind(bound_tex->tex);
1928         }
1929         DST.tex_bind_id = 0;
1930         BLI_freelistN(&DST.bound_texs);
1931
1932         if (DST.shader) {
1933                 GPU_shader_unbind();
1934                 DST.shader = NULL;
1935         }
1936
1937         if (!pass->wasdrawn) {
1938                 glEndQuery(GL_TIME_ELAPSED);
1939         }
1940
1941         pass->wasdrawn = true;
1942 }
1943
1944 void DRW_draw_pass(DRWPass *pass)
1945 {
1946         DRW_draw_pass_ex(pass, pass->shgroups.first, pass->shgroups.last);
1947 }
1948
1949 /* Draw only a subset of shgroups. Used in special situations as grease pencil strokes */
1950 void DRW_draw_pass_subset(DRWPass *pass, DRWShadingGroup *start_group, DRWShadingGroup *end_group)
1951 {
1952         DRW_draw_pass_ex(pass, start_group, end_group);
1953 }
1954
1955 void DRW_draw_callbacks_pre_scene(void)
1956 {
1957         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1958
1959         gpuLoadProjectionMatrix(rv3d->winmat);
1960         gpuLoadMatrix(rv3d->viewmat);
1961 }
1962
1963 void DRW_draw_callbacks_post_scene(void)
1964 {
1965         RegionView3D *rv3d = DST.draw_ctx.rv3d;
1966
1967         gpuLoadProjectionMatrix(rv3d->winmat);
1968         gpuLoadMatrix(rv3d->viewmat);
1969 }
1970
1971 /* Reset state to not interfer with other UI drawcall */
1972 void DRW_state_reset_ex(DRWState state)
1973 {
1974         DST.state = ~state;
1975         DRW_state_set(state);
1976 }
1977
1978 void DRW_state_reset(void)
1979 {
1980         /* Reset blending function */
1981         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1982
1983         DRW_state_reset_ex(DRW_STATE_DEFAULT);
1984 }
1985
1986 /* NOTE : Make sure to reset after use! */
1987 void DRW_state_invert_facing(void)
1988 {
1989         SWAP(GLenum, DST.backface, DST.frontface);
1990         glFrontFace(DST.frontface);
1991 }
1992
1993 /**
1994  * This only works if DRWPasses have been tagged with DRW_STATE_CLIP_PLANES,
1995  * and if the shaders have support for it (see usage of gl_ClipDistance).
1996  * Be sure to call DRW_state_clip_planes_reset() after you finish drawing.
1997  **/
1998 void DRW_state_clip_planes_add(float plane_eq[4])
1999 {
2000         copy_v4_v4(DST.clip_planes_eq[DST.num_clip_planes++], plane_eq);
2001 }
2002
2003 void DRW_state_clip_planes_reset(void)
2004 {
2005         DST.num_clip_planes = 0;
2006 }
2007
2008 /** \} */
2009
2010
2011 struct DRWTextStore *DRW_text_cache_ensure(void)
2012 {
2013         BLI_assert(DST.text_store_p);
2014         if (*DST.text_store_p == NULL) {
2015                 *DST.text_store_p = DRW_text_cache_create();
2016         }
2017         return *DST.text_store_p;
2018 }
2019
2020
2021 /* -------------------------------------------------------------------- */
2022
2023 /** \name Settings
2024  * \{ */
2025
2026 bool DRW_object_is_renderable(Object *ob)
2027 {
2028         Scene *scene = DST.draw_ctx.scene;
2029         Object *obedit = scene->obedit;
2030
2031         if (ob->type == OB_MESH) {
2032                 if (ob == obedit) {
2033                         IDProperty *props = BKE_layer_collection_engine_evaluated_get(ob, COLLECTION_MODE_EDIT, "");
2034                         bool do_show_occlude_wire = BKE_collection_engine_property_value_get_bool(props, "show_occlude_wire");
2035                         if (do_show_occlude_wire) {
2036                                 return false;
2037                         }
2038                         bool do_show_weight = BKE_collection_engine_property_value_get_bool(props, "show_weight");
2039                         if (do_show_weight) {
2040                                 return false;
2041                         }
2042                 }
2043         }
2044
2045         return true;
2046 }
2047
2048
2049 bool DRW_object_is_flat_normal(Object *ob)
2050 {
2051         if (ob->type == OB_MESH) {
2052                 Mesh *me = ob->data;
2053                 if (me->mpoly && me->mpoly[0].flag & ME_SMOOTH) {
2054                         return false;
2055                 }
2056         }
2057         return true;
2058 }
2059
2060 /** \} */
2061
2062
2063 /* -------------------------------------------------------------------- */
2064
2065 /** \name Framebuffers (DRW_framebuffer)
2066  * \{ */
2067
2068 static GPUTextureFormat convert_tex_format(int fbo_format, int *channels, bool *is_depth)
2069 {
2070         *is_depth = ELEM(fbo_format, DRW_TEX_DEPTH_16, DRW_TEX_DEPTH_24);
2071
2072         switch (fbo_format) {
2073                 case DRW_TEX_R_16:     *channels = 1; return GPU_R16F;
2074                 case DRW_TEX_R_32:     *channels = 1; return GPU_R32F;
2075                 case DRW_TEX_RG_16:    *channels = 2; return GPU_RG16F;
2076                 case DRW_TEX_RG_32:    *channels = 2; return GPU_RG32F;
2077                 case DRW_TEX_RGBA_8:   *channels = 4; return GPU_RGBA8;
2078                 case DRW_TEX_RGBA_16:  *channels = 4; return GPU_RGBA16F;
2079                 case DRW_TEX_RGBA_32:  *channels = 4; return GPU_RGBA32F;
2080                 case DRW_TEX_DEPTH_24: *channels = 1; return GPU_DEPTH_COMPONENT24;
2081                 case DRW_TEX_RGB_11_11_10: *channels = 3; return GPU_R11F_G11F_B10F;
2082                 default:
2083                         BLI_assert(false && "Texture format unsupported as render target!");
2084                         *channels = 4; return GPU_RGBA8;
2085         }
2086 }
2087
2088 void DRW_framebuffer_init(
2089         struct GPUFrameBuffer **fb, void *engine_type, int width, int height,
2090         DRWFboTexture textures[MAX_FBO_TEX], int textures_len)
2091 {
2092         BLI_assert(textures_len <= MAX_FBO_TEX);
2093
2094         bool create_fb = false;
2095         int color_attachment = -1;
2096
2097         if (!*fb) {
2098                 *fb = GPU_framebuffer_create();
2099                 create_fb = true;
2100         }
2101
2102         for (int i = 0; i < textures_len; ++i) {
2103                 int channels;
2104                 bool is_depth;
2105
2106                 DRWFboTexture fbotex = textures[i];
2107                 bool is_temp = (fbotex.flag & DRW_TEX_TEMP) != 0;
2108
2109                 GPUTextureFormat gpu_format = convert_tex_format(fbotex.format, &channels, &is_depth);
2110
2111                 if (!*fbotex.tex || is_temp) {
2112                         /* Temp textures need to be queried each frame, others not. */
2113                         if (is_temp) {
2114                                 *fbotex.tex = GPU_viewport_texture_pool_query(DST.viewport, engine_type, width, height, channels, gpu_format);
2115                         }
2116                         else if (create_fb) {
2117                                 *fbotex.tex = GPU_texture_create_2D_custom(width, height, channels, gpu_format, NULL, NULL);
2118                         }
2119                 }
2120
2121                 if (create_fb) {
2122                         if (!is_depth) {
2123                                 ++color_attachment;
2124                         }
2125                         drw_texture_set_parameters(*fbotex.tex, fbotex.flag);
2126                         GPU_framebuffer_texture_attach(*fb, *fbotex.tex, color_attachment, 0);
2127                 }
2128         }
2129
2130         if (create_fb) {
2131                 if (!GPU_framebuffer_check_valid(*fb, NULL)) {
2132                         printf("Error invalid framebuffer\n");
2133                 }
2134
2135                 /* Detach temp textures */
2136                 for (int i = 0; i < textures_len; ++i) {
2137                         DRWFboTexture fbotex = textures[i];
2138
2139                         if ((fbotex.flag & DRW_TEX_TEMP) != 0) {
2140                                 GPU_framebuffer_texture_detach(*fbotex.tex);
2141                         }
2142                 }
2143
2144                 GPU_framebuffer_bind(DST.default_framebuffer);
2145         }
2146 }
2147
2148 void DRW_framebuffer_free(struct GPUFrameBuffer *fb)
2149 {
2150         GPU_framebuffer_free(fb);
2151 }
2152
2153 void DRW_framebuffer_bind(struct GPUFrameBuffer *fb)
2154 {
2155         GPU_framebuffer_bind(fb);
2156 }
2157
2158 void DRW_framebuffer_clear(bool color, bool depth, bool stencil, float clear_col[4], float clear_depth)
2159 {
2160         if (color) {
2161                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
2162                 glClearColor(clear_col[0], clear_col[1], clear_col[2], clear_col[3]);
2163         }
2164         if (depth) {
2165                 glDepthMask(GL_TRUE);
2166                 glClearDepth(clear_depth);
2167         }
2168         if (stencil) {
2169                 glStencilMask(0xFF);
2170         }
2171         glClear(((color) ? GL_COLOR_BUFFER_BIT : 0) |
2172                 ((depth) ? GL_DEPTH_BUFFER_BIT : 0) |
2173                 ((stencil) ? GL_STENCIL_BUFFER_BIT : 0));
2174 }
2175
2176 void DRW_framebuffer_read_data(int x, int y, int w, int h, int channels, int slot, float *data)
2177 {
2178         GLenum type;
2179         switch (channels) {
2180                 case 1: type = GL_RED; break;
2181                 case 2: type = GL_RG; break;
2182                 case 3: type = GL_RGB; break;
2183                 case 4: type = GL_RGBA; break;
2184                 default:
2185                         BLI_assert(false && "wrong number of read channels");
2186                         return;
2187         }
2188         glReadBuffer(GL_COLOR_ATTACHMENT0 + slot);
2189         glReadPixels(x, y, w, h, type, GL_FLOAT, data);
2190 }
2191
2192 void DRW_framebuffer_texture_attach(struct GPUFrameBuffer *fb, GPUTexture *tex, int slot, int mip)
2193 {
2194         GPU_framebuffer_texture_attach(fb, tex, slot, mip);
2195 }
2196
2197 void DRW_framebuffer_texture_layer_attach(struct GPUFrameBuffer *fb, struct GPUTexture *tex, int slot, int layer, int mip)
2198 {
2199         GPU_framebuffer_texture_layer_attach(fb, tex, slot, layer, mip);
2200 }
2201
2202 void DRW_framebuffer_cubeface_attach(struct GPUFrameBuffer *fb, GPUTexture *tex, int slot, int face, int mip)
2203 {
2204         GPU_framebuffer_texture_cubeface_attach(fb, tex, slot, face, mip);
2205 }
2206
2207 void DRW_framebuffer_texture_detach(GPUTexture *tex)
2208 {
2209         GPU_framebuffer_texture_detach(tex);
2210 }
2211
2212 void DRW_framebuffer_blit(struct GPUFrameBuffer *fb_read, struct GPUFrameBuffer *fb_write, bool depth)
2213 {
2214         GPU_framebuffer_blit(fb_read, 0, fb_write, 0, depth);
2215 }
2216
2217 void DRW_framebuffer_recursive_downsample(
2218         struct GPUFrameBuffer *fb, struct GPUTexture *tex, int num_iter,
2219         void (*callback)(void *userData, int level), void *userData)
2220 {
2221         GPU_framebuffer_recursive_downsample(fb, tex, num_iter, callback, userData);
2222 }
2223
2224 void DRW_framebuffer_viewport_size(struct GPUFrameBuffer *UNUSED(fb_read), int x, int y, int w, int h)
2225 {
2226         glViewport(x, y, w, h);
2227 }
2228
2229 /* Use color management profile to draw texture to framebuffer */
2230 void DRW_transform_to_display(GPUTexture *tex)
2231 {
2232         DRW_state_set(DRW_STATE_WRITE_COLOR);
2233
2234         Gwn_VertFormat *vert_format = immVertexFormat();
2235         unsigned int pos = GWN_vertformat_attr_add(vert_format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2236         unsigned int texco = GWN_vertformat_attr_add(vert_format, "texCoord", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
2237
2238         const float dither = 1.0f;
2239
2240         bool use_ocio = false;
2241
2242         if (DST.draw_ctx.evil_C != NULL) {
2243                 use_ocio = IMB_colormanagement_setup_glsl_draw_from_space_ctx(DST.draw_ctx.evil_C, NULL, dither, false);
2244         }
2245
2246         if (!use_ocio) {
2247                 immBindBuiltinProgram(GPU_SHADER_2D_IMAGE_LINEAR_TO_SRGB);
2248                 immUniform1i("image", 0);
2249         }
2250
2251         GPU_texture_bind(tex, 0); /* OCIO texture bind point is 0 */
2252
2253         float mat[4][4];
2254         unit_m4(mat);
2255         immUniformMatrix4fv("ModelViewProjectionMatrix", mat);
2256
2257         /* Full screen triangle */
2258         immBegin(GWN_PRIM_TRIS, 3);
2259         immAttrib2f(texco, 0.0f, 0.0f);
2260         immVertex2f(pos, -1.0f, -1.0f);
2261
2262         immAttrib2f(texco, 2.0f, 0.0f);
2263         immVertex2f(pos, 3.0f, -1.0f);
2264
2265         immAttrib2f(texco, 0.0f, 2.0f);
2266         immVertex2f(pos, -1.0f, 3.0f);
2267         immEnd();
2268
2269         GPU_texture_unbind(tex);
2270
2271         if (use_ocio) {
2272                 IMB_colormanagement_finish_glsl_draw();
2273         }
2274         else {
2275                 immUnbindProgram();
2276         }
2277 }
2278
2279 /** \} */
2280
2281
2282 /* -------------------------------------------------------------------- */
2283
2284 /** \name Viewport (DRW_viewport)
2285  * \{ */
2286
2287 static void *DRW_viewport_engine_data_get(void *engine_type)
2288 {
2289         void *data = GPU_viewport_engine_data_get(DST.viewport, engine_type);
2290
2291         if (data == NULL) {
2292                 data = GPU_viewport_engine_data_create(DST.viewport, engine_type);
2293         }
2294         return data;
2295 }
2296
2297 void DRW_engine_viewport_data_size_get(
2298         const void *engine_type_v,
2299         int *r_fbl_len, int *r_txl_len, int *r_psl_len, int *r_stl_len)
2300 {
2301         const DrawEngineType *engine_type = engine_type_v;
2302
2303         if (r_fbl_len) {
2304                 *r_fbl_len = engine_type->vedata_size->fbl_len;
2305         }
2306         if (r_txl_len) {
2307                 *r_txl_len = engine_type->vedata_size->txl_len;
2308         }
2309         if (r_psl_len) {
2310                 *r_psl_len = engine_type->vedata_size->psl_len;
2311         }
2312         if (r_stl_len) {
2313                 *r_stl_len = engine_type->vedata_size->stl_len;
2314         }
2315 }
2316
2317 const float *DRW_viewport_size_get(void)
2318 {
2319         return &DST.size[0];
2320 }
2321
2322 const float *DRW_viewport_screenvecs_get(void)
2323 {
2324         return &DST.screenvecs[0][0];
2325 }
2326
2327 const float *DRW_viewport_pixelsize_get(void)
2328 {
2329         return &DST.pixsize;
2330 }
2331
2332 /* It also stores viewport variable to an immutable place: DST
2333  * This is because a cache uniform only store reference
2334  * to its value. And we don't want to invalidate the cache
2335  * if this value change per viewport */
2336 static void DRW_viewport_var_init(void)
2337 {
2338         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2339
2340         /* Refresh DST.size */
2341         if (DST.viewport) {
2342                 int size[2];
2343                 GPU_viewport_size_get(DST.viewport, size);
2344                 DST.size[0] = size[0];
2345                 DST.size[1] = size[1];
2346
2347                 DefaultFramebufferList *fbl = (DefaultFramebufferList *)GPU_viewport_framebuffer_list_get(DST.viewport);
2348                 DST.default_framebuffer = fbl->default_fb;
2349         }
2350         else {
2351                 DST.size[0] = 0;
2352                 DST.size[1] = 0;
2353
2354                 DST.default_framebuffer = NULL;
2355         }
2356         /* Refresh DST.screenvecs */
2357         copy_v3_v3(DST.screenvecs[0], rv3d->viewinv[0]);
2358         copy_v3_v3(DST.screenvecs[1], rv3d->viewinv[1]);
2359         normalize_v3(DST.screenvecs[0]);
2360         normalize_v3(DST.screenvecs[1]);
2361
2362         /* Refresh DST.pixelsize */
2363         DST.pixsize = rv3d->pixsize;
2364
2365         /* Reset facing */
2366         DST.frontface = GL_CCW;
2367         DST.backface = GL_CW;
2368         glFrontFace(DST.frontface);
2369 }
2370
2371 void DRW_viewport_matrix_get(float mat[4][4], DRWViewportMatrixType type)
2372 {
2373         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2374
2375         switch (type) {
2376                 case DRW_MAT_PERS:
2377                         copy_m4_m4(mat, rv3d->persmat);
2378                         break;
2379                 case DRW_MAT_PERSINV:
2380                         copy_m4_m4(mat, rv3d->persinv);
2381                         break;
2382                 case DRW_MAT_VIEW:
2383                         copy_m4_m4(mat, rv3d->viewmat);
2384                         break;
2385                 case DRW_MAT_VIEWINV:
2386                         copy_m4_m4(mat, rv3d->viewinv);
2387                         break;
2388                 case DRW_MAT_WIN:
2389                         copy_m4_m4(mat, rv3d->winmat);
2390                         break;
2391                 case DRW_MAT_WININV:
2392                         invert_m4_m4(mat, rv3d->winmat);
2393                         break;
2394                 default:
2395                         BLI_assert(!"Matrix type invalid");
2396                         break;
2397         }
2398 }
2399
2400 void DRW_viewport_matrix_override_set(float mat[4][4], DRWViewportMatrixType type)
2401 {
2402         copy_m4_m4(viewport_matrix_override.mat[type], mat);
2403         viewport_matrix_override.override[type] = true;
2404 }
2405
2406 void DRW_viewport_matrix_override_unset(DRWViewportMatrixType type)
2407 {
2408         viewport_matrix_override.override[type] = false;
2409 }
2410
2411 bool DRW_viewport_is_persp_get(void)
2412 {
2413         RegionView3D *rv3d = DST.draw_ctx.rv3d;
2414         return rv3d->is_persp;
2415 }
2416
2417 DefaultFramebufferList *DRW_viewport_framebuffer_list_get(void)
2418 {
2419         return GPU_viewport_framebuffer_list_get(DST.viewport);
2420 }
2421
2422 DefaultTextureList *DRW_viewport_texture_list_get(void)
2423 {
2424         return GPU_viewport_texture_list_get(DST.viewport);
2425 }
2426
2427 void DRW_viewport_request_redraw(void)
2428 {
2429         /* XXXXXXXXXXX HAAAAAAAACKKKK */
2430         WM_main_add_notifier(NC_MATERIAL | ND_SHADING_DRAW, NULL);
2431 }
2432
2433 /** \} */
2434
2435
2436 /* -------------------------------------------------------------------- */
2437 /** \name SceneLayers (DRW_scenelayer)
2438  * \{ */
2439
2440 void **DRW_scene_layer_engine_data_get(DrawEngineType *engine_type, void (*callback)(void *storage))
2441 {
2442         SceneLayerEngineData *sled;
2443
2444         for (sled = DST.draw_ctx.sl->drawdata.first; sled; sled = sled->next) {
2445                 if (sled->engine_type == engine_type) {
2446                         return &sled->storage;
2447                 }
2448         }
2449
2450         sled = MEM_callocN(sizeof(SceneLayerEngineData), "SceneLayerEngineData");
2451         sled->engine_type = engine_type;
2452         sled->free = callback;
2453         BLI_addtail(&DST.draw_ctx.sl->drawdata, sled);
2454
2455         return &sled->storage;
2456 }
2457
2458 /** \} */
2459
2460
2461 /* -------------------------------------------------------------------- */
2462
2463 /** \name Objects (DRW_object)
2464  * \{ */
2465
2466 void **DRW_object_engine_data_get(
2467         Object *ob, DrawEngineType *engine_type, void (*callback)(void *storage))
2468 {
2469         ObjectEngineData *oed;
2470
2471         for (oed = ob->drawdata.first; oed; oed = oed->next) {
2472                 if (oed->engine_type == engine_type) {
2473                         return &oed->storage;
2474                 }
2475         }
2476
2477         oed = MEM_callocN(sizeof(ObjectEngineData), "ObjectEngineData");
2478         oed->engine_type = engine_type;
2479         oed->free = callback;
2480         BLI_addtail(&ob->drawdata, oed);
2481
2482         return &oed->storage;
2483 }
2484
2485 /* XXX There is definitly some overlap between this and DRW_object_engine_data_get.
2486  * We should get rid of one of the two. */
2487 LampEngineData *DRW_lamp_engine_data_get(Object *ob, RenderEngineType *engine_type)
2488 {
2489         BLI_assert(ob->type == OB_LAMP);
2490
2491         Scene *scene = DST.draw_ctx.scene;
2492
2493         /* TODO Dupliobjects */
2494         /* TODO Should be per scenelayer */
2495         return GPU_lamp_engine_data_get(scene, ob, NULL, engine_type);
2496 }
2497
2498 void DRW_lamp_engine_data_free(LampEngineData *led)
2499 {
2500         GPU_lamp_engine_data_free(led);
2501 }
2502
2503 /** \} */
2504
2505
2506 /* -------------------------------------------------------------------- */
2507
2508 /** \name Rendering (DRW_engines)
2509  * \{ */
2510
2511 #define TIMER_FALLOFF 0.1f
2512
2513 static void DRW_engines_init(void)
2514 {
2515         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2516                 DrawEngineType *engine = link->data;
2517                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2518                 double stime = PIL_check_seconds_timer();
2519
2520                 if (engine->engine_init) {
2521                         engine->engine_init(data);
2522                 }
2523
2524                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2525                 data->init_time = data->init_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2526         }
2527 }
2528
2529 static void DRW_engines_cache_init(void)
2530 {
2531         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2532                 DrawEngineType *engine = link->data;
2533                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2534
2535                 if (data->text_draw_cache) {
2536                         DRW_text_cache_destroy(data->text_draw_cache);
2537                         data->text_draw_cache = NULL;
2538                 }
2539                 if (DST.text_store_p == NULL) {
2540                         DST.text_store_p = &data->text_draw_cache;
2541                 }
2542
2543                 double stime = PIL_check_seconds_timer();
2544                 data->cache_time = 0.0;
2545
2546                 if (engine->cache_init) {
2547                         engine->cache_init(data);
2548                 }
2549
2550                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2551         }
2552 }
2553
2554 static void DRW_engines_cache_populate(Object *ob)
2555 {
2556         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2557                 DrawEngineType *engine = link->data;
2558                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2559                 double stime = PIL_check_seconds_timer();
2560
2561                 if (engine->cache_populate) {
2562                         engine->cache_populate(data, ob);
2563                 }
2564
2565                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2566         }
2567 }
2568
2569 static void DRW_engines_cache_finish(void)
2570 {
2571         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2572                 DrawEngineType *engine = link->data;
2573                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2574                 double stime = PIL_check_seconds_timer();
2575
2576                 if (engine->cache_finish) {
2577                         engine->cache_finish(data);
2578                 }
2579
2580                 data->cache_time += (PIL_check_seconds_timer() - stime) * 1e3;
2581         }
2582 }
2583
2584 static void DRW_engines_draw_background(void)
2585 {
2586         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2587                 DrawEngineType *engine = link->data;
2588                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2589                 double stime = PIL_check_seconds_timer();
2590
2591                 if (engine->draw_background) {
2592                         engine->draw_background(data);
2593                         return;
2594                 }
2595
2596                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2597                 data->background_time = data->background_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2598         }
2599
2600         /* No draw_background found, doing default background */
2601         DRW_draw_background();
2602 }
2603
2604 static void DRW_engines_draw_scene(void)
2605 {
2606         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2607                 DrawEngineType *engine = link->data;
2608                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2609                 double stime = PIL_check_seconds_timer();
2610
2611                 if (engine->draw_scene) {
2612                         engine->draw_scene(data);
2613                 }
2614
2615                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2616                 data->render_time = data->render_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2617         }
2618 }
2619
2620 static void DRW_engines_draw_text(void)
2621 {
2622         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2623                 DrawEngineType *engine = link->data;
2624                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2625                 double stime = PIL_check_seconds_timer();
2626
2627                 if (data->text_draw_cache) {
2628                         DRW_text_cache_draw(data->text_draw_cache, DST.draw_ctx.v3d, DST.draw_ctx.ar, false);
2629                 }
2630
2631                 double ftime = (PIL_check_seconds_timer() - stime) * 1e3;
2632                 data->render_time = data->render_time * (1.0f - TIMER_FALLOFF) + ftime * TIMER_FALLOFF; /* exp average */
2633         }
2634 }
2635
2636 #define MAX_INFO_LINES 10
2637
2638 /**
2639  * Returns the offset required for the drawing of engines info.
2640  */
2641 int DRW_draw_region_engine_info_offset(void)
2642 {
2643         int lines = 0;
2644         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2645                 DrawEngineType *engine = link->data;
2646                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2647
2648                 /* Count the number of lines. */
2649                 if (data->info[0] != '\0') {
2650                         lines++;
2651                         char *c = data->info;
2652                         while (*c++ != '\0') {
2653                                 if (*c == '\n') {
2654                                         lines++;
2655                                 }
2656                         }
2657                 }
2658         }
2659         return MIN2(MAX_INFO_LINES, lines) * UI_UNIT_Y;
2660 }
2661
2662 /**
2663  * Actual drawing;
2664  */
2665 void DRW_draw_region_engine_info(void)
2666 {
2667         const char *info_array_final[MAX_INFO_LINES + 1];
2668         char info_array[MAX_INFO_LINES][GPU_INFO_SIZE]; /* This should be maxium number of engines running at the same time. */
2669         int i = 0;
2670
2671         const DRWContextState *draw_ctx = DRW_context_state_get();
2672         ARegion *ar = draw_ctx->ar;
2673         float fill_color[4] = {0.0f, 0.0f, 0.0f, 0.25f};
2674
2675         UI_GetThemeColor3fv(TH_HIGH_GRAD, fill_color);
2676         mul_v3_fl(fill_color, fill_color[3]);
2677
2678         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2679                 DrawEngineType *engine = link->data;
2680                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2681
2682                 if (data->info[0] != '\0') {
2683                         char *chr_current = data->info;
2684                         char *chr_start = chr_current;
2685                         int line_len = 0;
2686
2687                         while (*chr_current++ != '\0') {
2688                                 line_len++;
2689                                 if (*chr_current == '\n') {
2690                                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
2691                                         /* Re-start counting. */
2692                                         chr_start = chr_current + 1;
2693                                         line_len = -1;
2694                                 }
2695                         }
2696
2697                         BLI_strncpy(info_array[i++], chr_start, line_len + 1);
2698
2699                         if (i >= MAX_INFO_LINES) {
2700                                 break;
2701                         }
2702                 }
2703         }
2704
2705         for (int j = 0; j < i; j++) {
2706                 info_array_final[j] = info_array[j];
2707         }
2708         info_array_final[i] = NULL;
2709
2710         if (info_array[0] != NULL) {
2711                 ED_region_info_draw_multiline(ar, info_array_final, fill_color, true);
2712         }
2713 }
2714
2715 #undef MAX_INFO_LINES
2716
2717 static void use_drw_engine(DrawEngineType *engine)
2718 {
2719         LinkData *ld = MEM_callocN(sizeof(LinkData), "enabled engine link data");
2720         ld->data = engine;
2721         BLI_addtail(&DST.enabled_engines, ld);
2722 }
2723
2724 /* TODO revisit this when proper layering is implemented */
2725 /* Gather all draw engines needed and store them in DST.enabled_engines
2726  * That also define the rendering order of engines */
2727 static void DRW_engines_enable_from_engine(const Scene *scene)
2728 {
2729         /* TODO layers */
2730         RenderEngineType *type = RE_engines_find(scene->r.engine);
2731         if (type->draw_engine != NULL) {
2732                 use_drw_engine(type->draw_engine);
2733         }
2734
2735         if ((type->flag & RE_INTERNAL) == 0) {
2736                 DRW_engines_enable_external();
2737         }
2738 }
2739
2740 static void DRW_engines_enable_from_object_mode(void)
2741 {
2742         use_drw_engine(&draw_engine_object_type);
2743 }
2744
2745 static void DRW_engines_enable_from_mode(int mode)
2746 {
2747         switch (mode) {
2748                 case CTX_MODE_EDIT_MESH:
2749                         use_drw_engine(&draw_engine_edit_mesh_type);
2750                         break;
2751                 case CTX_MODE_EDIT_CURVE:
2752                         use_drw_engine(&draw_engine_edit_curve_type);
2753                         break;
2754                 case CTX_MODE_EDIT_SURFACE:
2755                         use_drw_engine(&draw_engine_edit_surface_type);
2756                         break;
2757                 case CTX_MODE_EDIT_TEXT:
2758                         use_drw_engine(&draw_engine_edit_text_type);
2759                         break;
2760                 case CTX_MODE_EDIT_ARMATURE:
2761                         use_drw_engine(&draw_engine_edit_armature_type);
2762                         break;
2763                 case CTX_MODE_EDIT_METABALL:
2764                         use_drw_engine(&draw_engine_edit_metaball_type);
2765                         break;
2766                 case CTX_MODE_EDIT_LATTICE:
2767                         use_drw_engine(&draw_engine_edit_lattice_type);
2768                         break;
2769                 case CTX_MODE_POSE:
2770                         use_drw_engine(&draw_engine_pose_type);
2771                         break;
2772                 case CTX_MODE_SCULPT:
2773                         use_drw_engine(&draw_engine_sculpt_type);
2774                         break;
2775                 case CTX_MODE_PAINT_WEIGHT:
2776                         use_drw_engine(&draw_engine_pose_type);
2777                         use_drw_engine(&draw_engine_paint_weight_type);
2778                         break;
2779                 case CTX_MODE_PAINT_VERTEX:
2780                         use_drw_engine(&draw_engine_paint_vertex_type);
2781                         break;
2782                 case CTX_MODE_PAINT_TEXTURE:
2783                         use_drw_engine(&draw_engine_paint_texture_type);
2784                         break;
2785                 case CTX_MODE_PARTICLE:
2786                         use_drw_engine(&draw_engine_particle_type);
2787                         break;
2788                 case CTX_MODE_OBJECT:
2789                         break;
2790                 default:
2791                         BLI_assert(!"Draw mode invalid");
2792                         break;
2793         }
2794 }
2795
2796 /**
2797  * Use for select and depth-drawing.
2798  */
2799 static void DRW_engines_enable_basic(void)
2800 {
2801         use_drw_engine(DRW_engine_viewport_basic_type.draw_engine);
2802 }
2803
2804 /**
2805  * Use for external render engines.
2806  */
2807 static void DRW_engines_enable_external(void)
2808 {
2809         use_drw_engine(DRW_engine_viewport_external_type.draw_engine);
2810 }
2811
2812 static void DRW_engines_enable(const Scene *scene, SceneLayer *sl)
2813 {
2814         const int mode = CTX_data_mode_enum_ex(scene->obedit, OBACT_NEW);
2815         DRW_engines_enable_from_engine(scene);
2816
2817         if (DRW_state_draw_support()) {
2818                 DRW_engines_enable_from_object_mode();
2819                 DRW_engines_enable_from_mode(mode);
2820         }
2821 }
2822
2823 static void DRW_engines_disable(void)
2824 {
2825         BLI_freelistN(&DST.enabled_engines);
2826 }
2827
2828 static unsigned int DRW_engines_get_hash(void)
2829 {
2830         unsigned int hash = 0;
2831         /* The cache depends on enabled engines */
2832         /* FIXME : if collision occurs ... segfault */
2833         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2834                 DrawEngineType *engine = link->data;
2835                 hash += BLI_ghashutil_strhash_p(engine->idname);
2836         }
2837
2838         return hash;
2839 }
2840
2841 static void draw_stat(rcti *rect, int u, int v, const char *txt, const int size)
2842 {
2843         BLF_draw_default_ascii(rect->xmin + (1 + u * 5) * U.widget_unit,
2844                                rect->ymax - (3 + v++) * U.widget_unit, 0.0f,
2845                                txt, size);
2846 }
2847
2848 /* CPU stats */
2849 static void DRW_debug_cpu_stats(void)
2850 {
2851         int u, v;
2852         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;
2853         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2854         rcti rect;
2855         struct ARegion *ar = DST.draw_ctx.ar;
2856         ED_region_visible_rect(ar, &rect);
2857
2858         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2859
2860         /* row by row */
2861         v = 0; u = 0;
2862         /* Label row */
2863         char col_label[32];
2864         sprintf(col_label, "Engine");
2865         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2866         sprintf(col_label, "Cache");
2867         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2868         sprintf(col_label, "Init");
2869         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2870         sprintf(col_label, "Background");
2871         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2872         sprintf(col_label, "Render");
2873         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2874         sprintf(col_label, "Total (w/o cache)");
2875         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2876         v++;
2877
2878         /* Engines rows */
2879         char time_to_txt[16];
2880         for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2881                 u = 0;
2882                 DrawEngineType *engine = link->data;
2883                 ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2884
2885                 draw_stat(&rect, u++, v, engine->idname, sizeof(engine->idname));
2886
2887                 cache_tot_time += data->cache_time;
2888                 sprintf(time_to_txt, "%.2fms", data->cache_time);
2889                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2890
2891                 init_tot_time += data->init_time;
2892                 sprintf(time_to_txt, "%.2fms", data->init_time);
2893                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2894
2895                 background_tot_time += data->background_time;
2896                 sprintf(time_to_txt, "%.2fms", data->background_time);
2897                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2898
2899                 render_tot_time += data->render_time;
2900                 sprintf(time_to_txt, "%.2fms", data->render_time);
2901                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2902
2903                 tot_time += data->init_time + data->background_time + data->render_time;
2904                 sprintf(time_to_txt, "%.2fms", data->init_time + data->background_time + data->render_time);
2905                 draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2906                 v++;
2907         }
2908
2909         /* Totals row */
2910         u = 0;
2911         sprintf(col_label, "Sub Total");
2912         draw_stat(&rect, u++, v, col_label, sizeof(col_label));
2913         sprintf(time_to_txt, "%.2fms", cache_tot_time);
2914         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2915         sprintf(time_to_txt, "%.2fms", init_tot_time);
2916         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2917         sprintf(time_to_txt, "%.2fms", background_tot_time);
2918         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2919         sprintf(time_to_txt, "%.2fms", render_tot_time);
2920         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2921         sprintf(time_to_txt, "%.2fms", tot_time);
2922         draw_stat(&rect, u++, v, time_to_txt, sizeof(time_to_txt));
2923 }
2924
2925 /* Display GPU time for each passes */
2926 static void DRW_debug_gpu_stats(void)
2927 {
2928         /* local coordinate visible rect inside region, to accomodate overlapping ui */
2929         rcti rect;
2930         struct ARegion *ar = DST.draw_ctx.ar;
2931         ED_region_visible_rect(ar, &rect);
2932
2933         UI_FontThemeColor(BLF_default(), TH_TEXT_HI);
2934
2935         char time_to_txt[16];
2936         char pass_name[MAX_PASS_NAME + 16];
2937         int v = BLI_listbase_count(&DST.enabled_engines) + 3;
2938         GLuint64 tot_time = 0;
2939
2940         if (G.debug_value > 666) {
2941                 for (LinkData *link = DST.enabled_engines.first; link; link = link->next) {
2942                         GLuint64 engine_time = 0;
2943                         DrawEngineType *engine = link->data;
2944                         ViewportEngineData *data = DRW_viewport_engine_data_get(engine);
2945                         int vsta = v;
2946
2947                         draw_stat(&rect, 0, v, engine->idname, sizeof(engine->idname));
2948                         v++;
2949
2950                         for (int i = 0; i < engine->vedata_size->psl_len; ++i) {
2951                                 DRWPass *pass = data->psl->passes[i];
2952                                 if (pass != NULL && pass->wasdrawn) {
2953                                         GLuint64 time;
2954                                         glGetQueryObjectui64v(pass->timer_queries[pass->front_idx], GL_QUERY_RESULT, &time);
2955
2956                                         sprintf(pass_name, "   |--> %s", pass->name);
2957                                         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2958
2959                                         sprintf(time_to_txt, "%.2fms", time / 1000000.0);
2960                                         engine_time += time;
2961                                         tot_time += time;
2962
2963                                         draw_stat(&rect, 2, v++, time_to_txt, sizeof(time_to_txt));
2964
2965                                         pass->wasdrawn = false;
2966                                 }
2967                         }
2968                         /* engine total time */
2969                         sprintf(time_to_txt, "%.2fms", engine_time / 1000000.0);
2970                         draw_stat(&rect, 2, vsta, time_to_txt, sizeof(time_to_txt));
2971                         v++;
2972                 }
2973
2974                 sprintf(pass_name, "Total GPU time %.2fms (%.1f fps)", tot_time / 1000000.0, 1000000000.0 / tot_time);
2975                 draw_stat(&rect, 0, v++, pass_name, sizeof(pass_name));
2976                 v++;
2977         }
2978
2979         /* Memory Stats */
2980         unsigned int tex_mem = GPU_texture_memory_usage_get();
2981         unsigned int vbo_mem = GWN_vertbuf_get_memory_usage();
2982
2983         sprintf(pass_name, "GPU Memory");
2984         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2985         sprintf(pass_name, "%.2fMB", (float)(tex_mem + vbo_mem) / 1000000.0);
2986         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2987         sprintf(pass_name, "   |--> Textures");
2988         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2989         sprintf(pass_name, "%.2fMB", (float)tex_mem / 1000000.0);
2990         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2991         sprintf(pass_name, "   |--> Meshes");
2992         draw_stat(&rect, 0, v, pass_name, sizeof(pass_name));
2993         sprintf(pass_name, "%.2fMB", (float)vbo_mem / 1000000.0);
2994         draw_stat(&rect, 1, v++, pass_name, sizeof(pass_name));
2995 }
2996
2997
2998 /* -------------------------------------------------------------------- */
2999
3000 /** \name Main Draw Loops (DRW_draw)
3001  * \{ */
3002
3003 /* Everything starts here.
3004  * This function takes care of calling all cache and rendering functions
3005  * for each relevant engine / mode engine. */
3006 void DRW_draw_view(const bContext *C)
3007 {
3008         struct Depsgraph *graph = CTX_data_depsgraph(C);
3009         ARegion *ar = CTX_wm_region(C);
3010         View3D *v3d = CTX_wm_view3d(C);
3011
3012         /* Reset before using it. */
3013         memset(&DST, 0x0, sizeof(DST));
3014         DRW_draw_render_loop_ex(graph, ar, v3d, C);
3015 }
3016
3017 /**
3018  * Used for both regular and off-screen drawing.
3019  * Need to reset DST before calling this function
3020  */
3021 void DRW_draw_render_loop_ex(
3022         struct Depsgraph *graph,
3023         ARegion *ar, View3D *v3d,
3024         const bContext *evil_C)
3025 {
3026         Scene *scene = DEG_get_scene(graph);
3027         SceneLayer *sl = DEG_get_scene_layer(graph);
3028         RegionView3D *rv3d = ar->regiondata;
3029
3030         DST.draw_ctx.evil_C = evil_C;
3031
3032         bool cache_is_dirty;
3033         DST.viewport = rv3d->viewport;
3034         v3d->zbuf = true;
3035
3036         /* Setup viewport */
3037         cache_is_dirty = GPU_viewport_cache_validate(DST.viewport, DRW_engines_get_hash());
3038
3039         DST.draw_ctx = (DRWContextState){
3040                 ar, rv3d, v3d, scene, sl, OBACT_NEW,
3041                 /* reuse if caller sets */
3042                 DST.draw_ctx.evil_C,
3043         };
3044
3045         DRW_viewport_var_init();
3046
3047         /* Get list of enabled engines */
3048         DRW_engines_enable(scene, sl);
3049
3050         /* Update ubos */
3051         DRW_globals_update();
3052
3053         /* Init engines */
3054         DRW_engines_init();
3055
3056         /* TODO : tag to refresh by the deps graph */
3057         /* ideally only refresh when objects are added/removed */
3058         /* or render properties / materials change */
3059         if (cache_is_dirty) {
3060                 DRW_engines_cache_init();
3061
3062                 DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_ALL);
3063                 {
3064                         DRW_engines_cache_populate(ob);
3065                         /* XXX find a better place for this. maybe Depsgraph? */
3066                         ob->deg_update_flag = 0;
3067                 }
3068                 DEG_OBJECT_ITER_END
3069
3070                 DRW_engines_cache_finish();
3071         }
3072
3073         /* Start Drawing */
3074         DRW_state_reset();
3075         DRW_engines_draw_background();
3076
3077         DRW_draw_callbacks_pre_scene();
3078         if (DST.draw_ctx.evil_C) {
3079                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_PRE_VIEW);
3080         }
3081
3082         DRW_engines_draw_scene();
3083
3084         DRW_draw_callbacks_post_scene();
3085         if (DST.draw_ctx.evil_C) {
3086                 ED_region_draw_cb_draw(DST.draw_ctx.evil_C, DST.draw_ctx.ar, REGION_DRAW_POST_VIEW);
3087         }
3088
3089         DRW_state_reset();
3090
3091         DRW_engines_draw_text();
3092
3093         if (DST.draw_ctx.evil_C) {
3094                 /* needed so manipulator isn't obscured */
3095                 glDisable(GL_DEPTH_TEST);
3096
3097                 DRW_draw_manipulator();
3098                 glEnable(GL_DEPTH_TEST);
3099
3100                 DRW_draw_region_info();
3101         }
3102
3103         if (G.debug_value > 20) {
3104                 DRW_debug_cpu_stats();
3105                 DRW_debug_gpu_stats();
3106         }
3107
3108         DRW_state_reset();
3109         DRW_engines_disable();
3110
3111 #ifdef DEBUG
3112         /* Avoid accidental reuse. */
3113         memset(&DST, 0xFF, sizeof(DST));
3114 #endif
3115 }
3116
3117 void DRW_draw_render_loop(
3118         struct Depsgraph *graph,
3119         ARegion *ar, View3D *v3d)
3120 {
3121         /* Reset before using it. */
3122         memset(&DST, 0x0, sizeof(DST));
3123         DRW_draw_render_loop_ex(graph, ar, v3d, NULL);
3124 }
3125
3126 void DRW_draw_render_loop_offscreen(
3127         struct Depsgraph *graph,
3128         ARegion *ar, View3D *v3d, GPUOffScreen *ofs)
3129 {
3130         RegionView3D *rv3d = ar->regiondata;
3131
3132         /* backup */
3133         void *backup_viewport = rv3d->viewport;
3134         {
3135                 /* backup (_never_ use rv3d->viewport) */
3136                 rv3d->viewport = GPU_viewport_create_from_offscreen(ofs);
3137         }
3138
3139         /* Reset before using it. */
3140         memset(&DST, 0x0, sizeof(DST));
3141         DST.options.is_image_render = true;
3142         DRW_draw_render_loop_ex(graph, ar, v3d, NULL);
3143
3144         /* restore */
3145         {
3146                 /* don't free data owned by 'ofs' */
3147                 GPU_viewport_clear_from_offscreen(rv3d->viewport);
3148                 GPU_viewport_free(rv3d->viewport);
3149                 MEM_freeN(rv3d->viewport);
3150
3151                 rv3d->viewport = backup_viewport;
3152         }
3153
3154         /* we need to re-bind (annoying!) */
3155         GPU_offscreen_bind(ofs, false);
3156 }
3157
3158 /**
3159  * object mode select-loop, see: ED_view3d_draw_select_loop (legacy drawing).
3160  */
3161 void DRW_draw_select_loop(
3162         struct Depsgraph *graph,
3163         ARegion *ar, View3D *v3d,
3164         bool UNUSED(use_obedit_skip), bool UNUSED(use_nearest), const rcti *rect)
3165 {
3166         Scene *scene = DEG_get_scene(graph);
3167         SceneLayer *sl = DEG_get_scene_layer(graph);
3168 #ifndef USE_GPU_SELECT
3169         UNUSED_VARS(vc, scene, sl, v3d, ar, rect);
3170 #else
3171         RegionView3D *rv3d = ar->regiondata;
3172
3173         /* Reset before using it. */
3174         memset(&DST, 0x0, sizeof(DST));
3175
3176         /* backup (_never_ use rv3d->viewport) */
3177         void *backup_viewport = rv3d->viewport;
3178         rv3d->viewport = NULL;
3179
3180         bool use_obedit = false;
3181         int obedit_mode = 0;
3182         if (scene->obedit && scene->obedit->type == OB_MBALL) {
3183                 use_obedit = true;
3184                 DRW_engines_cache_populate(scene->obedit);
3185                 obedit_mode = CTX_MODE_EDIT_METABALL;
3186         }
3187         else if ((scene->obedit && scene->obedit->type == OB_ARMATURE)) {
3188                 /* if not drawing sketch, draw bones */
3189                 // if (!BDR_drawSketchNames(vc))
3190                 {
3191                         use_obedit = true;
3192                         obedit_mode = CTX_MODE_EDIT_ARMATURE;
3193                 }
3194         }
3195
3196         struct GPUViewport *viewport = GPU_viewport_create();
3197         GPU_viewport_size_set(viewport, (const int[2]){BLI_rcti_size_x(rect), BLI_rcti_size_y(rect)});
3198
3199         bool cache_is_dirty;
3200         DST.viewport = viewport;
3201         v3d->zbuf = true;
3202
3203         DST.options.is_select = true;
3204
3205         /* Get list of enabled engines */
3206         if (use_obedit) {
3207                 DRW_engines_enable_from_mode(obedit_mode);
3208         }
3209         else {
3210                 DRW_engines_enable_basic();
3211                 DRW_engines_enable_from_object_mode();
3212         }
3213
3214         /* Setup viewport */
3215         cache_is_dirty = true;
3216
3217         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
3218         DST.draw_ctx = (DRWContextState){
3219                 ar, rv3d, v3d, scene, sl, OBACT_NEW, (bContext *)NULL,
3220         };
3221
3222         DRW_viewport_var_init();
3223
3224         /* Update ubos */
3225         DRW_globals_update();
3226
3227         /* Init engines */
3228         DRW_engines_init();
3229
3230         /* TODO : tag to refresh by the deps graph */
3231         /* ideally only refresh when objects are added/removed */
3232         /* or render properties / materials change */
3233         if (cache_is_dirty) {
3234
3235                 DRW_engines_cache_init();
3236
3237                 if (use_obedit) {
3238                         DRW_engines_cache_populate(scene->obedit);
3239                 }
3240                 else {
3241                         DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_DUPLI)
3242                         {
3243                                 if ((ob->base_flag & BASE_SELECTABLED) != 0) {
3244                                         DRW_select_load_id(ob->select_color);
3245                                         DRW_engines_cache_populate(ob);
3246                                 }
3247                         }
3248                         DEG_OBJECT_ITER_END
3249                 }
3250
3251                 DRW_engines_cache_finish();
3252         }
3253
3254         /* Start Drawing */
3255         DRW_state_reset();
3256         DRW_draw_callbacks_pre_scene();
3257         DRW_engines_draw_scene();
3258         DRW_draw_callbacks_post_scene();
3259
3260         DRW_state_reset();
3261         DRW_engines_disable();
3262
3263 #ifdef DEBUG
3264         /* Avoid accidental reuse. */
3265         memset(&DST, 0xFF, sizeof(DST));
3266 #endif
3267
3268         /* Cleanup for selection state */
3269         GPU_viewport_free(viewport);
3270         MEM_freeN(viewport);
3271
3272         /* restore */
3273         rv3d->viewport = backup_viewport;
3274 #endif  /* USE_GPU_SELECT */
3275 }
3276
3277 /**
3278  * object mode select-loop, see: ED_view3d_draw_depth_loop (legacy drawing).
3279  */
3280 void DRW_draw_depth_loop(
3281         Depsgraph *graph,
3282         ARegion *ar, View3D *v3d)
3283 {
3284         Scene *scene = DEG_get_scene(graph);
3285         SceneLayer *sl = DEG_get_scene_layer(graph);
3286         RegionView3D *rv3d = ar->regiondata;
3287
3288         /* backup (_never_ use rv3d->viewport) */
3289         void *backup_viewport = rv3d->viewport;
3290         rv3d->viewport = NULL;
3291
3292         /* Reset before using it. */
3293         memset(&DST, 0x0, sizeof(DST));
3294
3295         struct GPUViewport *viewport = GPU_viewport_create();
3296         GPU_viewport_size_set(viewport, (const int[2]){ar->winx, ar->winy});
3297
3298         bool cache_is_dirty;
3299         DST.viewport = viewport;
3300         v3d->zbuf = true;
3301
3302         DST.options.is_depth = true;
3303
3304         /* Get list of enabled engines */
3305         {
3306                 DRW_engines_enable_basic();
3307                 DRW_engines_enable_from_object_mode();
3308         }
3309
3310         /* Setup viewport */
3311         cache_is_dirty = true;
3312
3313         /* Instead of 'DRW_context_state_init(C, &DST.draw_ctx)', assign from args */
3314         DST.draw_ctx = (DRWContextState){
3315                 ar, rv3d, v3d, scene, sl, OBACT_NEW, (bContext *)NULL,
3316         };
3317
3318         DRW_viewport_var_init();
3319
3320         /* Update ubos */
3321         DRW_globals_update();
3322
3323         /* Init engines */
3324         DRW_engines_init();
3325
3326         /* TODO : tag to refresh by the deps graph */
3327         /* ideally only refresh when objects are added/removed */
3328         /* or render properties / materials change */
3329         if (cache_is_dirty) {
3330
3331                 DRW_engines_cache_init();
3332
3333                 DEG_OBJECT_ITER(graph, ob, DEG_OBJECT_ITER_FLAG_ALL)
3334                 {
3335                         DRW_engines_cache_populate(ob);
3336                 }
3337                 DEG_OBJECT_ITER_END
3338
3339                 DRW_engines_cache_finish();
3340         }
3341
3342         /* Start Drawing */
3343         DRW_state_reset();
3344         DRW_draw_callbacks_pre_scene();
3345         DRW_engines_draw_scene();
3346         DRW_draw_callbacks_post_scene();
3347
3348         DRW_state_reset();
3349         DRW_engines_disable();
3350
3351 #ifdef DEBUG
3352         /* Avoid accidental reuse. */
3353         memset(&DST, 0xFF, sizeof(DST));
3354 #endif
3355
3356         /* Cleanup for selection state */
3357         GPU_viewport_free(viewport);
3358         MEM_freeN(viewport);
3359
3360         /* restore */
3361         rv3d->viewport = backup_viewport;
3362 }
3363
3364 /** \} */
3365
3366
3367 /* -------------------------------------------------------------------- */
3368
3369 /** \name Draw Manager State (DRW_state)
3370  * \{ */
3371
3372 void DRW_state_dfdy_factors_get(float dfdyfac[2])
3373 {
3374         GPU_get_dfdy_factors(dfdyfac);
3375 }
3376
3377 /**
3378  * When false, drawing doesn't output to a pixel buffer
3379  * eg: Occlusion queries, or when we have setup a context to draw in already.
3380  */
3381 bool DRW_state_is_fbo(void)
3382 {
3383         return (DST.default_framebuffer != NULL);
3384 }
3385
3386 /**
3387  * For when engines need to know if this is drawing for selection or not.
3388  */
3389 bool DRW_state_is_select(void)
3390 {
3391         return DST.options.is_select;
3392 }
3393
3394 bool DRW_state_is_depth(void)
3395 {
3396         return DST.options.is_depth;
3397 }
3398
3399 /**
3400  * Whether we are rendering for an image
3401  */
3402 bool DRW_state_is_image_render(void)
3403 {
3404         return DST.options.is_image_render;
3405 }
3406
3407 /**
3408  * Whether we are rendering only the render engine,
3409  * or if we should also render the mode engines.
3410  */
3411 bool DRW_state_is_scene_render(void)
3412 {
3413         BLI_assert(DST.options.is_scene_render ?
3414                    DST.options.is_image_render : true);
3415         return DST.options.is_scene_render;
3416 }
3417
3418 /**
3419  * Should text draw in this mode?
3420  */
3421 bool DRW_state_show_text(void)
3422 {
3423         return (DST.options.is_select) == 0 &&
3424                (DST.options.is_depth) == 0 &&