Merge branch 'master' into blender2.8
[blender.git] / source / blender / draw / engines / eevee / eevee_materials.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 eevee_materials.c
23  *  \ingroup draw_engine
24  */
25
26 #include "DRW_render.h"
27
28 #include "BLI_dynstr.h"
29 #include "BLI_ghash.h"
30 #include "BLI_alloca.h"
31 #include "BLI_rand.h"
32 #include "BLI_string_utils.h"
33
34 #include "BKE_particle.h"
35 #include "BKE_paint.h"
36 #include "BKE_pbvh.h"
37 #include "BKE_studiolight.h"
38
39 #include "DNA_world_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_view3d_types.h"
42
43 #include "GPU_material.h"
44
45 #include "eevee_engine.h"
46 #include "eevee_lut.h"
47 #include "eevee_private.h"
48
49 /* *********** STATIC *********** */
50 static struct {
51         char *frag_shader_lib;
52         char *vert_shader_str;
53         char *volume_shader_lib;
54
55         struct GPUShader *default_prepass_sh;
56         struct GPUShader *default_prepass_clip_sh;
57         struct GPUShader *default_hair_prepass_sh;
58         struct GPUShader *default_hair_prepass_clip_sh;
59         struct GPUShader *default_lit[VAR_MAT_MAX];
60         struct GPUShader *default_background;
61         struct GPUShader *default_studiolight_background;
62         struct GPUShader *update_noise_sh;
63
64         /* 64*64 array texture containing all LUTs and other utilitarian arrays.
65          * Packing enables us to same precious textures slots. */
66         struct GPUTexture *util_tex;
67         struct GPUTexture *noise_tex;
68
69         struct GPUUniformBuffer *dummy_sss_profile;
70
71         uint sss_count;
72
73         float alpha_hash_offset;
74         float alpha_hash_scale;
75         float noise_offsets[3];
76 } e_data = {NULL}; /* Engine data */
77
78 extern char datatoc_lamps_lib_glsl[];
79 extern char datatoc_lightprobe_lib_glsl[];
80 extern char datatoc_ambient_occlusion_lib_glsl[];
81 extern char datatoc_prepass_frag_glsl[];
82 extern char datatoc_prepass_vert_glsl[];
83 extern char datatoc_default_frag_glsl[];
84 extern char datatoc_default_world_frag_glsl[];
85 extern char datatoc_ltc_lib_glsl[];
86 extern char datatoc_bsdf_lut_frag_glsl[];
87 extern char datatoc_btdf_lut_frag_glsl[];
88 extern char datatoc_bsdf_common_lib_glsl[];
89 extern char datatoc_bsdf_sampling_lib_glsl[];
90 extern char datatoc_common_uniforms_lib_glsl[];
91 extern char datatoc_common_hair_lib_glsl[];
92 extern char datatoc_common_view_lib_glsl[];
93 extern char datatoc_irradiance_lib_glsl[];
94 extern char datatoc_octahedron_lib_glsl[];
95 extern char datatoc_lit_surface_frag_glsl[];
96 extern char datatoc_lit_surface_vert_glsl[];
97 extern char datatoc_raytrace_lib_glsl[];
98 extern char datatoc_ssr_lib_glsl[];
99 extern char datatoc_shadow_vert_glsl[];
100 extern char datatoc_lightprobe_geom_glsl[];
101 extern char datatoc_lightprobe_vert_glsl[];
102 extern char datatoc_background_vert_glsl[];
103 extern char datatoc_update_noise_frag_glsl[];
104 extern char datatoc_volumetric_vert_glsl[];
105 extern char datatoc_volumetric_geom_glsl[];
106 extern char datatoc_volumetric_frag_glsl[];
107 extern char datatoc_volumetric_lib_glsl[];
108
109 extern char datatoc_gpu_shader_uniform_color_frag_glsl[];
110
111 extern Material defmaterial;
112 extern GlobalsUboStorage ts;
113
114 /* *********** FUNCTIONS *********** */
115
116 #if 0 /* Used only to generate the LUT values */
117 static struct GPUTexture *create_ggx_lut_texture(int UNUSED(w), int UNUSED(h))
118 {
119         struct GPUTexture *tex;
120         struct GPUFrameBuffer *fb = NULL;
121         static float samples_len = 8192.0f;
122         static float inv_samples_len = 1.0f / 8192.0f;
123
124         char *lib_str = BLI_string_joinN(
125                 datatoc_bsdf_common_lib_glsl,
126                 datatoc_bsdf_sampling_lib_glsl);
127
128         struct GPUShader *sh = DRW_shader_create_with_lib(
129                 datatoc_lightprobe_vert_glsl, datatoc_lightprobe_geom_glsl, datatoc_bsdf_lut_frag_glsl, lib_str,
130                 "#define HAMMERSLEY_SIZE 8192\n"
131                 "#define BRDF_LUT_SIZE 64\n"
132                 "#define NOISE_SIZE 64\n");
133
134         DRWPass *pass = DRW_pass_create("LightProbe Filtering", DRW_STATE_WRITE_COLOR);
135         DRWShadingGroup *grp = DRW_shgroup_create(sh, pass);
136         DRW_shgroup_uniform_float(grp, "sampleCount", &samples_len, 1);
137         DRW_shgroup_uniform_float(grp, "invSampleCount", &inv_samples_len, 1);
138         DRW_shgroup_uniform_texture(grp, "texHammersley", e_data.hammersley);
139         DRW_shgroup_uniform_texture(grp, "texJitter", e_data.jitter);
140
141         struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
142         DRW_shgroup_call_add(grp, geom, NULL);
143
144         float *texels = MEM_mallocN(sizeof(float[2]) * w * h, "lut");
145
146         tex = DRW_texture_create_2D(w, h, GPU_RG16F, DRW_TEX_FILTER, (float *)texels);
147
148         DRWFboTexture tex_filter = {&tex, GPU_RG16F, DRW_TEX_FILTER};
149         GPU_framebuffer_init(&fb, &draw_engine_eevee_type, w, h, &tex_filter, 1);
150
151         GPU_framebuffer_bind(fb);
152         DRW_draw_pass(pass);
153
154         float *data = MEM_mallocN(sizeof(float[3]) * w * h, "lut");
155         glReadBuffer(GL_COLOR_ATTACHMENT0);
156         glReadPixels(0, 0, w, h, GL_RGB, GL_FLOAT, data);
157
158         printf("{");
159         for (int i = 0; i < w*h * 3; i+=3) {
160                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
161                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
162                 printf("%ff, %ff, ", data[i],  data[i+1]); i+=3;
163                 printf("%ff, %ff, \n", data[i],  data[i+1]);
164         }
165         printf("}");
166
167         MEM_freeN(texels);
168         MEM_freeN(data);
169
170         return tex;
171 }
172
173 static struct GPUTexture *create_ggx_refraction_lut_texture(int w, int h)
174 {
175         struct GPUTexture *tex;
176         struct GPUTexture *hammersley = create_hammersley_sample_texture(8192);
177         struct GPUFrameBuffer *fb = NULL;
178         static float samples_len = 8192.0f;
179         static float a2 = 0.0f;
180         static float inv_samples_len = 1.0f / 8192.0f;
181
182         char *frag_str = BLI_string_joinN(
183                 datatoc_bsdf_common_lib_glsl,
184                 datatoc_bsdf_sampling_lib_glsl,
185                 datatoc_btdf_lut_frag_glsl);
186
187         struct GPUShader *sh = DRW_shader_create_fullscreen(frag_str,
188                 "#define HAMMERSLEY_SIZE 8192\n"
189                 "#define BRDF_LUT_SIZE 64\n"
190                 "#define NOISE_SIZE 64\n"
191                 "#define LUT_SIZE 64\n");
192
193         MEM_freeN(frag_str);
194
195         DRWPass *pass = DRW_pass_create("LightProbe Filtering", DRW_STATE_WRITE_COLOR);
196         DRWShadingGroup *grp = DRW_shgroup_create(sh, pass);
197         DRW_shgroup_uniform_float(grp, "a2", &a2, 1);
198         DRW_shgroup_uniform_float(grp, "sampleCount", &samples_len, 1);
199         DRW_shgroup_uniform_float(grp, "invSampleCount", &inv_samples_len, 1);
200         DRW_shgroup_uniform_texture(grp, "texHammersley", hammersley);
201         DRW_shgroup_uniform_texture(grp, "utilTex", e_data.util_tex);
202
203         struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
204         DRW_shgroup_call_add(grp, geom, NULL);
205
206         float *texels = MEM_mallocN(sizeof(float[2]) * w * h, "lut");
207
208         tex = DRW_texture_create_2D(w, h, GPU_R16F, DRW_TEX_FILTER, (float *)texels);
209
210         DRWFboTexture tex_filter = {&tex, GPU_R16F, DRW_TEX_FILTER};
211         GPU_framebuffer_init(&fb, &draw_engine_eevee_type, w, h, &tex_filter, 1);
212
213         GPU_framebuffer_bind(fb);
214
215         float *data = MEM_mallocN(sizeof(float[3]) * w * h, "lut");
216
217         float inc = 1.0f / 31.0f;
218         float roughness = 1e-8f - inc;
219         FILE *f = BLI_fopen("btdf_split_sum_ggx.h", "w");
220         fprintf(f, "static float btdf_split_sum_ggx[32][64 * 64] = {\n");
221         do {
222                 roughness += inc;
223                 CLAMP(roughness, 1e-4f, 1.0f);
224                 a2 = powf(roughness, 4.0f);
225                 DRW_draw_pass(pass);
226
227                 GPU_framebuffer_read_data(0, 0, w, h, 3, 0, data);
228
229 #if 1
230                 fprintf(f, "\t{\n\t\t");
231                 for (int i = 0; i < w*h * 3; i+=3) {
232                         fprintf(f, "%ff,", data[i]);
233                         if (((i/3)+1) % 12 == 0) fprintf(f, "\n\t\t");
234                         else fprintf(f, " ");
235                 }
236                 fprintf(f, "\n\t},\n");
237 #else
238                 for (int i = 0; i < w*h * 3; i+=3) {
239                         if (data[i] < 0.01) printf(" ");
240                         else if (data[i] < 0.3) printf(".");
241                         else if (data[i] < 0.6) printf("+");
242                         else if (data[i] < 0.9) printf("%%");
243                         else printf("#");
244                         if ((i/3+1) % 64 == 0) printf("\n");
245                 }
246 #endif
247
248         } while (roughness < 1.0f);
249         fprintf(f, "\n};\n");
250
251         fclose(f);
252
253         MEM_freeN(texels);
254         MEM_freeN(data);
255
256         return tex;
257 }
258 #endif
259 /* XXX TODO define all shared resources in a shared place without duplication */
260 struct GPUTexture *EEVEE_materials_get_util_tex(void)
261 {
262         return e_data.util_tex;
263 }
264
265 static int eevee_material_shadow_option(int shadow_method)
266 {
267         switch (shadow_method) {
268                 case SHADOW_ESM: return VAR_MAT_ESM;
269                 case SHADOW_VSM: return VAR_MAT_VSM;
270                 default:
271                         BLI_assert(!"Incorrect Shadow Method");
272                         break;
273         }
274
275         return 0;
276 }
277
278 static char *eevee_get_defines(int options)
279 {
280         char *str = NULL;
281
282         DynStr *ds = BLI_dynstr_new();
283         BLI_dynstr_appendf(ds, SHADER_DEFINES);
284
285         if ((options & VAR_MAT_MESH) != 0) {
286                 BLI_dynstr_appendf(ds, "#define MESH_SHADER\n");
287         }
288         if ((options & VAR_MAT_HAIR) != 0) {
289                 BLI_dynstr_appendf(ds, "#define HAIR_SHADER\n");
290         }
291         if ((options & VAR_MAT_PROBE) != 0) {
292                 BLI_dynstr_appendf(ds, "#define PROBE_CAPTURE\n");
293         }
294         if ((options & VAR_MAT_FLAT) != 0) {
295                 BLI_dynstr_appendf(ds, "#define USE_FLAT_NORMAL\n");
296         }
297         if ((options & VAR_MAT_CLIP) != 0) {
298                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_CLIP\n");
299         }
300         if ((options & VAR_MAT_SHADOW) != 0) {
301                 BLI_dynstr_appendf(ds, "#define SHADOW_SHADER\n");
302         }
303         if ((options & VAR_MAT_HASH) != 0) {
304                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_HASH\n");
305         }
306         if ((options & VAR_MAT_BLEND) != 0) {
307                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_BLEND\n");
308         }
309         if ((options & VAR_MAT_MULT) != 0) {
310                 BLI_dynstr_appendf(ds, "#define USE_MULTIPLY\n");
311         }
312         if ((options & VAR_MAT_REFRACT) != 0) {
313                 BLI_dynstr_appendf(ds, "#define USE_REFRACTION\n");
314         }
315         if ((options & VAR_MAT_SSS) != 0) {
316                 BLI_dynstr_appendf(ds, "#define USE_SSS\n");
317         }
318         if ((options & VAR_MAT_SSSALBED) != 0) {
319                 BLI_dynstr_appendf(ds, "#define USE_SSS_ALBEDO\n");
320         }
321         if ((options & VAR_MAT_TRANSLUC) != 0) {
322                 BLI_dynstr_appendf(ds, "#define USE_TRANSLUCENCY\n");
323         }
324         if ((options & VAR_MAT_VSM) != 0) {
325                 BLI_dynstr_appendf(ds, "#define SHADOW_VSM\n");
326         }
327         if ((options & VAR_MAT_ESM) != 0) {
328                 BLI_dynstr_appendf(ds, "#define SHADOW_ESM\n");
329         }
330         if (((options & VAR_MAT_VOLUME) != 0) && ((options & VAR_MAT_BLEND) != 0)) {
331                 BLI_dynstr_appendf(ds, "#define USE_ALPHA_BLEND_VOLUMETRICS\n");
332         }
333         if ((options & VAR_MAT_LOOKDEV) != 0) {
334                 BLI_dynstr_appendf(ds, "#define LOOKDEV\n");
335         }
336
337         str = BLI_dynstr_get_cstring(ds);
338         BLI_dynstr_free(ds);
339
340         return str;
341 }
342
343 static char *eevee_get_volume_defines(int options)
344 {
345         char *str = NULL;
346
347         DynStr *ds = BLI_dynstr_new();
348         BLI_dynstr_appendf(ds, SHADER_DEFINES);
349         BLI_dynstr_appendf(ds, "#define VOLUMETRICS\n");
350
351         if ((options & VAR_MAT_VOLUME) != 0) {
352                 BLI_dynstr_appendf(ds, "#define MESH_SHADER\n");
353         }
354
355         str = BLI_dynstr_get_cstring(ds);
356         BLI_dynstr_free(ds);
357
358         return str;
359 }
360
361 /**
362  * ssr_id can be null to disable ssr contribution.
363  **/
364 static void add_standard_uniforms(
365         DRWShadingGroup *shgrp, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
366         int *ssr_id, float *refract_depth,
367         bool use_diffuse, bool use_glossy, bool use_refract,
368         bool use_ssrefraction, bool use_alpha_blend)
369 {
370         LightCache *lcache = vedata->stl->g_data->light_cache;
371
372         if (ssr_id == NULL) {
373                 static int no_ssr = -1.0f;
374                 ssr_id = &no_ssr;
375         }
376
377         DRW_shgroup_uniform_block(shgrp, "probe_block", sldata->probe_ubo);
378         DRW_shgroup_uniform_block(shgrp, "grid_block", sldata->grid_ubo);
379         DRW_shgroup_uniform_block(shgrp, "planar_block", sldata->planar_ubo);
380         DRW_shgroup_uniform_block(shgrp, "light_block", sldata->light_ubo);
381         DRW_shgroup_uniform_block(shgrp, "shadow_block", sldata->shadow_ubo);
382         DRW_shgroup_uniform_block(shgrp, "common_block", sldata->common_ubo);
383         DRW_shgroup_uniform_block(shgrp, "clip_block", sldata->clip_ubo);
384
385         if (use_diffuse || use_glossy || use_refract) {
386                 DRW_shgroup_uniform_texture(shgrp, "utilTex", e_data.util_tex);
387                 DRW_shgroup_uniform_texture_ref(shgrp, "shadowCubeTexture", &sldata->shadow_cube_pool);
388                 DRW_shgroup_uniform_texture_ref(shgrp, "shadowCascadeTexture", &sldata->shadow_cascade_pool);
389                 DRW_shgroup_uniform_texture_ref(shgrp, "maxzBuffer", &vedata->txl->maxzbuffer);
390         }
391         if ((use_diffuse || use_glossy) && !use_ssrefraction) {
392                 if ((vedata->stl->effects->enabled_effects & EFFECT_GTAO) != 0) {
393                         DRW_shgroup_uniform_texture_ref(shgrp, "horizonBuffer", &vedata->stl->effects->gtao_horizons);
394                 }
395                 else {
396                         /* Use maxzbuffer as fallback to avoid sampling problem on certain platform, see: T52593 */
397                         DRW_shgroup_uniform_texture_ref(shgrp, "horizonBuffer", &vedata->txl->maxzbuffer);
398                 }
399         }
400         if (use_diffuse) {
401                 DRW_shgroup_uniform_texture_ref(shgrp, "irradianceGrid", &lcache->grid_tx.tex);
402         }
403         if (use_glossy || use_refract) {
404                 DRW_shgroup_uniform_texture_ref(shgrp, "probeCubes", &lcache->cube_tx.tex);
405         }
406         if (use_glossy) {
407                 DRW_shgroup_uniform_texture_ref(shgrp, "probePlanars", &vedata->txl->planar_pool);
408                 DRW_shgroup_uniform_int(shgrp, "outputSsrId", ssr_id, 1);
409         }
410         if (use_refract && use_ssrefraction) {
411                 BLI_assert(refract_depth != NULL);
412                 DRW_shgroup_uniform_float(shgrp, "refractionDepth", refract_depth, 1);
413                 DRW_shgroup_uniform_texture_ref(shgrp, "colorBuffer", &vedata->txl->refract_color);
414         }
415
416         if ((vedata->stl->effects->enabled_effects & EFFECT_VOLUMETRIC) != 0 &&
417              use_alpha_blend)
418         {
419                 /* Do not use history buffers as they already have been swapped */
420                 DRW_shgroup_uniform_texture_ref(shgrp, "inScattering", &vedata->txl->volume_scatter);
421                 DRW_shgroup_uniform_texture_ref(shgrp, "inTransmittance", &vedata->txl->volume_transmittance);
422         }
423 }
424
425 static void create_default_shader(int options)
426 {
427         char *frag_str = BLI_string_joinN(
428                 e_data.frag_shader_lib,
429                 datatoc_default_frag_glsl);
430
431         char *defines = eevee_get_defines(options);
432
433         e_data.default_lit[options] = DRW_shader_create(e_data.vert_shader_str, NULL, frag_str, defines);
434
435         MEM_freeN(defines);
436         MEM_freeN(frag_str);
437 }
438
439 static void eevee_init_dummys(void)
440 {
441         e_data.dummy_sss_profile = GPU_material_create_sss_profile_ubo();
442 }
443
444 static void eevee_init_noise_texture(void)
445 {
446         e_data.noise_tex = DRW_texture_create_2D(64, 64, GPU_RGBA16F, 0, (float *)blue_noise);
447 }
448
449 static void eevee_init_util_texture(void)
450 {
451         const int layers = 3 + 16;
452         float (*texels)[4] = MEM_mallocN(sizeof(float[4]) * 64 * 64 * layers, "utils texels");
453         float (*texels_layer)[4] = texels;
454
455         /* Copy ltc_mat_ggx into 1st layer */
456         memcpy(texels_layer, ltc_mat_ggx, sizeof(float[4]) * 64 * 64);
457         texels_layer += 64 * 64;
458
459         /* Copy bsdf_split_sum_ggx into 2nd layer red and green channels.
460            Copy ltc_mag_ggx into 2nd layer blue channel. */
461         for (int i = 0; i < 64 * 64; i++) {
462                 texels_layer[i][0] = bsdf_split_sum_ggx[i * 2 + 0];
463                 texels_layer[i][1] = bsdf_split_sum_ggx[i * 2 + 1];
464                 texels_layer[i][2] = ltc_mag_ggx[i];
465                 texels_layer[i][3] = ltc_disk_integral[i];
466         }
467         texels_layer += 64 * 64;
468
469         /* Copy blue noise in 3rd layer  */
470         for (int i = 0; i < 64 * 64; i++) {
471                 texels_layer[i][0] = blue_noise[i][0];
472                 texels_layer[i][1] = blue_noise[i][2];
473                 texels_layer[i][2] = cosf(blue_noise[i][1] * 2.0f * M_PI);
474                 texels_layer[i][3] = sinf(blue_noise[i][1] * 2.0f * M_PI);
475         }
476         texels_layer += 64 * 64;
477
478         /* Copy Refraction GGX LUT in layer 4 - 20 */
479         for (int j = 0; j < 16; ++j) {
480                 for (int i = 0; i < 64 * 64; i++) {
481                         texels_layer[i][0] = btdf_split_sum_ggx[j * 2][i];
482                         texels_layer[i][1] = btdf_split_sum_ggx[j * 2][i];
483                         texels_layer[i][2] = btdf_split_sum_ggx[j * 2][i];
484                         texels_layer[i][3] = btdf_split_sum_ggx[j * 2][i];
485                 }
486                 texels_layer += 64 * 64;
487         }
488
489         e_data.util_tex = DRW_texture_create_2D_array(
490                 64, 64, layers, GPU_RGBA16F, DRW_TEX_FILTER | DRW_TEX_WRAP, (float *)texels);
491
492         MEM_freeN(texels);
493 }
494
495 void EEVEE_update_noise(EEVEE_PassList *psl, EEVEE_FramebufferList *fbl, const double offsets[3])
496 {
497         e_data.noise_offsets[0] = offsets[0];
498         e_data.noise_offsets[1] = offsets[1];
499         e_data.noise_offsets[2] = offsets[2];
500
501         /* Attach & detach because we don't currently support multiple FB per texture,
502          * and this would be the case for multiple viewport. */
503         GPU_framebuffer_bind(fbl->update_noise_fb);
504         DRW_draw_pass(psl->update_noise_pass);
505 }
506
507 static void EEVEE_update_viewvecs(float invproj[4][4], float winmat[4][4], float (*r_viewvecs)[4])
508 {
509         /* view vectors for the corners of the view frustum.
510          * Can be used to recreate the world space position easily */
511         float view_vecs[4][4] = {
512             {-1.0f, -1.0f, -1.0f, 1.0f},
513             { 1.0f, -1.0f, -1.0f, 1.0f},
514             {-1.0f,  1.0f, -1.0f, 1.0f},
515             {-1.0f, -1.0f,  1.0f, 1.0f}
516         };
517
518         /* convert the view vectors to view space */
519         const bool is_persp = (winmat[3][3] == 0.0f);
520         for (int i = 0; i < 4; i++) {
521                 mul_project_m4_v3(invproj, view_vecs[i]);
522                 /* normalized trick see:
523                  * http://www.derschmale.com/2014/01/26/reconstructing-positions-from-the-depth-buffer */
524                 if (is_persp) {
525                         /* Divide XY by Z. */
526                         mul_v2_fl(view_vecs[i], 1.0f / view_vecs[i][2]);
527                 }
528         }
529
530         /**
531          * If ortho : view_vecs[0] is the near-bottom-left corner of the frustum and
532          *            view_vecs[1] is the vector going from the near-bottom-left corner to
533          *            the far-top-right corner.
534          * If Persp : view_vecs[0].xy and view_vecs[1].xy are respectively the bottom-left corner
535          *            when Z = 1, and top-left corner if Z = 1.
536          *            view_vecs[0].z the near clip distance and view_vecs[1].z is the (signed)
537          *            distance from the near plane to the far clip plane.
538          **/
539         copy_v4_v4(r_viewvecs[0], view_vecs[0]);
540
541         /* we need to store the differences */
542         r_viewvecs[1][0] = view_vecs[1][0] - view_vecs[0][0];
543         r_viewvecs[1][1] = view_vecs[2][1] - view_vecs[0][1];
544         r_viewvecs[1][2] = view_vecs[3][2] - view_vecs[0][2];
545 }
546
547 void EEVEE_materials_init(EEVEE_ViewLayerData *sldata, EEVEE_StorageList *stl, EEVEE_FramebufferList *fbl)
548 {
549         if (!e_data.frag_shader_lib) {
550                 /* Shaders */
551                 e_data.frag_shader_lib = BLI_string_joinN(
552                         datatoc_common_view_lib_glsl,
553                         datatoc_common_uniforms_lib_glsl,
554                         datatoc_bsdf_common_lib_glsl,
555                         datatoc_bsdf_sampling_lib_glsl,
556                         datatoc_ambient_occlusion_lib_glsl,
557                         datatoc_raytrace_lib_glsl,
558                         datatoc_ssr_lib_glsl,
559                         datatoc_octahedron_lib_glsl,
560                         datatoc_irradiance_lib_glsl,
561                         datatoc_lightprobe_lib_glsl,
562                         datatoc_ltc_lib_glsl,
563                         datatoc_lamps_lib_glsl,
564                         /* Add one for each Closure */
565                         datatoc_lit_surface_frag_glsl,
566                         datatoc_lit_surface_frag_glsl,
567                         datatoc_lit_surface_frag_glsl,
568                         datatoc_lit_surface_frag_glsl,
569                         datatoc_lit_surface_frag_glsl,
570                         datatoc_lit_surface_frag_glsl,
571                         datatoc_lit_surface_frag_glsl,
572                         datatoc_lit_surface_frag_glsl,
573                         datatoc_lit_surface_frag_glsl,
574                         datatoc_lit_surface_frag_glsl,
575                         datatoc_volumetric_lib_glsl);
576
577                 e_data.volume_shader_lib = BLI_string_joinN(
578                         datatoc_common_view_lib_glsl,
579                         datatoc_common_uniforms_lib_glsl,
580                         datatoc_bsdf_common_lib_glsl,
581                         datatoc_ambient_occlusion_lib_glsl,
582                         datatoc_octahedron_lib_glsl,
583                         datatoc_irradiance_lib_glsl,
584                         datatoc_lightprobe_lib_glsl,
585                         datatoc_ltc_lib_glsl,
586                         datatoc_lamps_lib_glsl,
587                         datatoc_volumetric_lib_glsl,
588                         datatoc_volumetric_frag_glsl);
589
590                 e_data.vert_shader_str = BLI_string_joinN(
591                         datatoc_common_view_lib_glsl,
592                         datatoc_common_hair_lib_glsl,
593                         datatoc_lit_surface_vert_glsl);
594
595                 e_data.default_background = DRW_shader_create(
596                         datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl,
597                         NULL);
598
599                 e_data.default_studiolight_background = DRW_shader_create(
600                         datatoc_background_vert_glsl, NULL, datatoc_default_world_frag_glsl,
601                         "#define LOOKDEV\n");
602
603                 e_data.default_prepass_sh = DRW_shader_create(
604                         datatoc_prepass_vert_glsl, NULL, datatoc_prepass_frag_glsl,
605                         NULL);
606
607                 e_data.default_prepass_clip_sh = DRW_shader_create(
608                         datatoc_prepass_vert_glsl, NULL, datatoc_prepass_frag_glsl,
609                         "#define CLIP_PLANES\n");
610
611                 char *vert_str = BLI_string_joinN(
612                         datatoc_common_view_lib_glsl,
613                         datatoc_common_hair_lib_glsl,
614                         datatoc_prepass_vert_glsl);
615
616                 e_data.default_hair_prepass_sh = DRW_shader_create(
617                         vert_str, NULL, datatoc_prepass_frag_glsl,
618                         "#define HAIR_SHADER\n");
619
620                 e_data.default_hair_prepass_clip_sh = DRW_shader_create(
621                         vert_str, NULL, datatoc_prepass_frag_glsl,
622                         "#define HAIR_SHADER\n"
623                         "#define CLIP_PLANES\n");
624
625                 MEM_freeN(vert_str);
626
627                 e_data.update_noise_sh = DRW_shader_create_fullscreen(
628                         datatoc_update_noise_frag_glsl, NULL);
629
630                 eevee_init_util_texture();
631                 eevee_init_noise_texture();
632                 eevee_init_dummys();
633         }
634
635         if (!DRW_state_is_image_render() &&
636             ((stl->effects->enabled_effects & EFFECT_TAA) == 0))
637         {
638                 e_data.alpha_hash_offset = 0.0f;
639                 e_data.alpha_hash_scale = 1.0f;
640         }
641         else {
642                 double r;
643                 BLI_halton_1D(5, 0.0, stl->effects->taa_current_sample - 1, &r);
644                 e_data.alpha_hash_offset = (float)r;
645                 e_data.alpha_hash_scale = 0.01f;
646         }
647
648         {
649                 /* Update view_vecs */
650                 float invproj[4][4], winmat[4][4];
651                 DRW_viewport_matrix_get(winmat, DRW_MAT_WIN);
652                 DRW_viewport_matrix_get(invproj, DRW_MAT_WININV);
653
654                 EEVEE_update_viewvecs(invproj, winmat, sldata->common_data.view_vecs);
655         }
656
657         {
658                 /* Update noise Framebuffer. */
659                 GPU_framebuffer_ensure_config(&fbl->update_noise_fb, {
660                         GPU_ATTACHMENT_NONE,
661                         GPU_ATTACHMENT_TEXTURE_LAYER(e_data.util_tex, 2)
662                 });
663         }
664 }
665
666 struct GPUMaterial *EEVEE_material_world_lightprobe_get(struct Scene *scene, World *wo)
667 {
668         const void *engine = &DRW_engine_viewport_eevee_type;
669         const int options = VAR_WORLD_PROBE;
670
671         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, false);
672         if (mat != NULL) {
673                 return mat;
674         }
675         return DRW_shader_create_from_world(
676                 scene, wo, engine, options,
677                 datatoc_background_vert_glsl, NULL, e_data.frag_shader_lib,
678                 SHADER_DEFINES "#define PROBE_CAPTURE\n", false);
679 }
680
681 struct GPUMaterial *EEVEE_material_world_background_get(struct Scene *scene, World *wo)
682 {
683         const void *engine = &DRW_engine_viewport_eevee_type;
684         int options = VAR_WORLD_BACKGROUND;
685
686         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, true);
687         if (mat != NULL) {
688                 return mat;
689         }
690         return DRW_shader_create_from_world(
691                 scene, wo, engine, options,
692                 datatoc_background_vert_glsl, NULL, e_data.frag_shader_lib,
693                 SHADER_DEFINES "#define WORLD_BACKGROUND\n", true);
694 }
695
696 struct GPUMaterial *EEVEE_material_world_volume_get(struct Scene *scene, World *wo)
697 {
698         const void *engine = &DRW_engine_viewport_eevee_type;
699         int options = VAR_WORLD_VOLUME;
700
701         GPUMaterial *mat = DRW_shader_find_from_world(wo, engine, options, true);
702         if (mat != NULL) {
703                 return mat;
704         }
705
706         char *defines = eevee_get_volume_defines(options);
707
708         mat = DRW_shader_create_from_world(
709                 scene, wo, engine, options,
710                 datatoc_volumetric_vert_glsl, datatoc_volumetric_geom_glsl, e_data.volume_shader_lib,
711                 defines, true);
712
713         MEM_freeN(defines);
714
715         return mat;
716 }
717
718 struct GPUMaterial *EEVEE_material_mesh_get(
719         struct Scene *scene, Material *ma, EEVEE_Data *vedata,
720         bool use_blend, bool use_multiply, bool use_refract, bool use_sss, bool use_translucency, int shadow_method)
721 {
722         EEVEE_EffectsInfo *effects = vedata->stl->effects;
723         const void *engine = &DRW_engine_viewport_eevee_type;
724         int options = VAR_MAT_MESH;
725
726         if (use_blend) options |= VAR_MAT_BLEND;
727         if (use_multiply) options |= VAR_MAT_MULT;
728         if (use_refract) options |= VAR_MAT_REFRACT;
729         if (use_sss) options |= VAR_MAT_SSS;
730         if (use_sss && effects->sss_separate_albedo) options |= VAR_MAT_SSSALBED;
731         if (use_translucency) options |= VAR_MAT_TRANSLUC;
732         if (((effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_blend) options |= VAR_MAT_VOLUME;
733
734         options |= eevee_material_shadow_option(shadow_method);
735
736         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
737         if (mat) {
738                 return mat;
739         }
740
741         char *defines = eevee_get_defines(options);
742
743         mat = DRW_shader_create_from_material(
744                 scene, ma, engine, options,
745                 e_data.vert_shader_str, NULL, e_data.frag_shader_lib,
746                 defines, true);
747
748         MEM_freeN(defines);
749
750         return mat;
751 }
752
753 struct GPUMaterial *EEVEE_material_mesh_volume_get(struct Scene *scene, Material *ma)
754 {
755         const void *engine = &DRW_engine_viewport_eevee_type;
756         int options = VAR_MAT_VOLUME;
757
758         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
759         if (mat != NULL) {
760                 return mat;
761         }
762
763         char *defines = eevee_get_volume_defines(options);
764
765         mat = DRW_shader_create_from_material(
766                 scene, ma, engine, options,
767                 datatoc_volumetric_vert_glsl, datatoc_volumetric_geom_glsl, e_data.volume_shader_lib,
768                 defines, true);
769
770         MEM_freeN(defines);
771
772         return mat;
773 }
774
775 struct GPUMaterial *EEVEE_material_mesh_depth_get(
776         struct Scene *scene, Material *ma,
777         bool use_hashed_alpha, bool is_shadow)
778 {
779         const void *engine = &DRW_engine_viewport_eevee_type;
780         int options = VAR_MAT_MESH;
781
782         if (use_hashed_alpha) {
783                 options |= VAR_MAT_HASH;
784         }
785         else {
786                 options |= VAR_MAT_CLIP;
787         }
788
789         if (is_shadow)
790                 options |= VAR_MAT_SHADOW;
791
792         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
793         if (mat) {
794                 return mat;
795         }
796
797         char *defines = eevee_get_defines(options);
798
799         char *frag_str = BLI_string_joinN(
800                 e_data.frag_shader_lib,
801                 datatoc_prepass_frag_glsl);
802
803         mat = DRW_shader_create_from_material(
804                 scene, ma, engine, options,
805                 (is_shadow) ? datatoc_shadow_vert_glsl : e_data.vert_shader_str,
806                 NULL,
807                 frag_str,
808                 defines,
809                 true);
810
811         MEM_freeN(frag_str);
812         MEM_freeN(defines);
813
814         return mat;
815 }
816
817 struct GPUMaterial *EEVEE_material_hair_get(
818         struct Scene *scene, Material *ma, int shadow_method)
819 {
820         const void *engine = &DRW_engine_viewport_eevee_type;
821         int options = VAR_MAT_MESH | VAR_MAT_HAIR;
822
823         options |= eevee_material_shadow_option(shadow_method);
824
825         GPUMaterial *mat = DRW_shader_find_from_material(ma, engine, options, true);
826         if (mat) {
827                 return mat;
828         }
829
830         char *defines = eevee_get_defines(options);
831
832         mat = DRW_shader_create_from_material(
833                 scene, ma, engine, options,
834                 e_data.vert_shader_str, NULL, e_data.frag_shader_lib,
835                 defines, true);
836
837         MEM_freeN(defines);
838
839         return mat;
840 }
841
842 /**
843  * Create a default shading group inside the given pass.
844  **/
845 static struct DRWShadingGroup *EEVEE_default_shading_group_create(
846         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata, DRWPass *pass,
847         bool is_hair, bool is_flat_normal, bool use_blend, bool use_ssr, int shadow_method)
848 {
849         EEVEE_EffectsInfo *effects = vedata->stl->effects;
850         static int ssr_id;
851         ssr_id = (use_ssr) ? 1 : -1;
852         int options = VAR_MAT_MESH;
853
854         if (is_hair) options |= VAR_MAT_HAIR;
855         if (is_flat_normal) options |= VAR_MAT_FLAT;
856         if (use_blend) options |= VAR_MAT_BLEND;
857         if (((effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_blend) options |= VAR_MAT_VOLUME;
858
859         options |= eevee_material_shadow_option(shadow_method);
860
861         if (e_data.default_lit[options] == NULL) {
862                 create_default_shader(options);
863         }
864
865         DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], pass);
866         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, use_blend);
867
868         return shgrp;
869 }
870
871 /**
872  * Create a default shading group inside the default pass without standard uniforms.
873  **/
874 static struct DRWShadingGroup *EEVEE_default_shading_group_get(
875         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
876         Object *ob, ParticleSystem *psys, ModifierData *md,
877         bool is_hair, bool is_flat_normal, bool use_ssr, int shadow_method)
878 {
879         static int ssr_id;
880         ssr_id = (use_ssr) ? 1 : -1;
881         int options = VAR_MAT_MESH;
882
883         BLI_assert(!is_hair || (ob && psys && md));
884
885         if (is_hair) options |= VAR_MAT_HAIR;
886         if (is_flat_normal) options |= VAR_MAT_FLAT;
887
888         options |= eevee_material_shadow_option(shadow_method);
889
890         if (e_data.default_lit[options] == NULL) {
891                 create_default_shader(options);
892         }
893
894         if (vedata->psl->default_pass[options] == NULL) {
895                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
896                 vedata->psl->default_pass[options] = DRW_pass_create("Default Lit Pass", state);
897
898                 /* XXX / WATCH: This creates non persistent binds for the ubos and textures.
899                  * But it's currently OK because the following shgroups does not add any bind.
900                  * EDIT: THIS IS NOT THE CASE FOR HAIRS !!! DUMMY!!! */
901                 if (!is_hair) {
902                         DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], vedata->psl->default_pass[options]);
903                         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
904                 }
905         }
906
907         if (is_hair) {
908                 DRWShadingGroup *shgrp = DRW_shgroup_hair_create(ob, psys, md,
909                                                                  vedata->psl->default_pass[options],
910                                                                  e_data.default_lit[options]);
911                 add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
912                 return shgrp;
913         }
914         else {
915                 return DRW_shgroup_create(e_data.default_lit[options], vedata->psl->default_pass[options]);
916         }
917 }
918
919 /**
920  * Create a default shading group inside the lookdev pass without standard uniforms.
921  **/
922 static struct DRWShadingGroup *EEVEE_lookdev_shading_group_get(
923         EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
924         bool use_ssr, int shadow_method)
925 {
926         static int ssr_id;
927         ssr_id = (use_ssr) ? 1 : -1;
928         int options = VAR_MAT_MESH | VAR_MAT_LOOKDEV;
929
930         options |= eevee_material_shadow_option(shadow_method);
931
932         if (e_data.default_lit[options] == NULL) {
933                 create_default_shader(options);
934         }
935
936         if (vedata->psl->lookdev_pass == NULL) {
937                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_ALWAYS | DRW_STATE_CULL_BACK;
938                 vedata->psl->lookdev_pass = DRW_pass_create("LookDev Pass", state);
939
940                 DRWShadingGroup *shgrp = DRW_shgroup_create(e_data.default_lit[options], vedata->psl->lookdev_pass);
941                 /* XXX / WATCH: This creates non persistent binds for the ubos and textures.
942                  * But it's currently OK because the following shgroups does not add any bind. */
943                 add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL, true, true, false, false, false);
944         }
945
946         return DRW_shgroup_create(e_data.default_lit[options], vedata->psl->lookdev_pass);
947 }
948 void EEVEE_materials_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
949 {
950         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
951         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
952
953         /* Create Material Ghash */
954         {
955                 stl->g_data->material_hash = BLI_ghash_ptr_new("Eevee_material ghash");
956         }
957
958         {
959                 psl->background_pass = DRW_pass_create("Background Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL);
960
961                 struct GPUBatch *geom = DRW_cache_fullscreen_quad_get();
962                 DRWShadingGroup *grp = NULL;
963
964                 const DRWContextState *draw_ctx = DRW_context_state_get();
965                 Scene *scene = draw_ctx->scene;
966                 World *wo = scene->world;
967
968                 float *col = ts.colorBackground;
969
970                 /* LookDev */
971                 EEVEE_lookdev_cache_init(vedata, &grp, e_data.default_studiolight_background, psl->background_pass, wo, NULL);
972                 /* END */
973
974                 if (!grp && wo) {
975                         col = &wo->horr;
976
977                         if (wo->use_nodes && wo->nodetree) {
978                                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
979                                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
980                                 struct GPUMaterial *gpumat = EEVEE_material_world_background_get(scene, wo);
981
982                                 switch (GPU_material_status(gpumat)) {
983                                         case GPU_MAT_SUCCESS:
984                                                 grp = DRW_shgroup_material_create(gpumat, psl->background_pass);
985                                                 DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
986                                                 /* TODO (fclem): remove those (need to clean the GLSL files). */
987                                                 DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
988                                                 DRW_shgroup_uniform_block(grp, "grid_block", sldata->grid_ubo);
989                                                 DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
990                                                 DRW_shgroup_uniform_block(grp, "planar_block", sldata->planar_ubo);
991                                                 DRW_shgroup_uniform_block(grp, "light_block", sldata->light_ubo);
992                                                 DRW_shgroup_uniform_block(grp, "shadow_block", sldata->shadow_ubo);
993                                                 DRW_shgroup_call_add(grp, geom, NULL);
994                                                 break;
995                                         case GPU_MAT_QUEUED:
996                                                 /* TODO Bypass probe compilation. */
997                                                 col = compile_col;
998                                                 break;
999                                         case GPU_MAT_FAILED:
1000                                         default:
1001                                                 col = error_col;
1002                                                 break;
1003                                 }
1004                         }
1005                 }
1006
1007                 /* Fallback if shader fails or if not using nodetree. */
1008                 if (grp == NULL) {
1009                         grp = DRW_shgroup_create(e_data.default_background, psl->background_pass);
1010                         DRW_shgroup_uniform_vec3(grp, "color", col, 1);
1011                         DRW_shgroup_uniform_float(grp, "backgroundAlpha", &stl->g_data->background_alpha, 1);
1012                         DRW_shgroup_call_add(grp, geom, NULL);
1013                 }
1014         }
1015
1016         {
1017                 DRWState state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WIRE;
1018                 psl->depth_pass = DRW_pass_create("Depth Pass", state);
1019                 stl->g_data->depth_shgrp = DRW_shgroup_create(e_data.default_prepass_sh, psl->depth_pass);
1020
1021                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CULL_BACK;
1022                 psl->depth_pass_cull = DRW_pass_create("Depth Pass Cull", state);
1023                 stl->g_data->depth_shgrp_cull = DRW_shgroup_create(e_data.default_prepass_sh, psl->depth_pass_cull);
1024
1025                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1026                 psl->depth_pass_clip = DRW_pass_create("Depth Pass Clip", state);
1027                 stl->g_data->depth_shgrp_clip = DRW_shgroup_create(e_data.default_prepass_clip_sh, psl->depth_pass_clip);
1028                 DRW_shgroup_uniform_block(stl->g_data->depth_shgrp_clip, "clip_block", sldata->clip_ubo);
1029
1030                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_CULL_BACK;
1031                 psl->depth_pass_clip_cull = DRW_pass_create("Depth Pass Cull Clip", state);
1032                 stl->g_data->depth_shgrp_clip_cull = DRW_shgroup_create(
1033                         e_data.default_prepass_clip_sh, psl->depth_pass_clip_cull);
1034                 DRW_shgroup_uniform_block(stl->g_data->depth_shgrp_clip_cull, "clip_block", sldata->clip_ubo);
1035         }
1036
1037         {
1038                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1039                 psl->material_pass = DRW_pass_create("Material Shader Pass", state);
1040         }
1041
1042         {
1043                 DRWState state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_WIRE;
1044                 psl->refract_depth_pass = DRW_pass_create("Refract Depth Pass", state);
1045                 stl->g_data->refract_depth_shgrp = DRW_shgroup_create(e_data.default_prepass_sh, psl->refract_depth_pass);
1046
1047                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CULL_BACK;
1048                 psl->refract_depth_pass_cull = DRW_pass_create("Refract Depth Pass Cull", state);
1049                 stl->g_data->refract_depth_shgrp_cull = DRW_shgroup_create(
1050                         e_data.default_prepass_sh, psl->refract_depth_pass_cull);
1051
1052                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1053                 psl->refract_depth_pass_clip = DRW_pass_create("Refract Depth Pass Clip", state);
1054                 stl->g_data->refract_depth_shgrp_clip = DRW_shgroup_create(
1055                         e_data.default_prepass_clip_sh, psl->refract_depth_pass_clip);
1056                 DRW_shgroup_uniform_block(stl->g_data->refract_depth_shgrp_clip, "clip_block", sldata->clip_ubo);
1057
1058                 state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_CULL_BACK;
1059                 psl->refract_depth_pass_clip_cull = DRW_pass_create("Refract Depth Pass Cull Clip", state);
1060                 stl->g_data->refract_depth_shgrp_clip_cull = DRW_shgroup_create(
1061                         e_data.default_prepass_clip_sh, psl->refract_depth_pass_clip_cull);
1062                 DRW_shgroup_uniform_block(stl->g_data->refract_depth_shgrp_clip_cull, "clip_block", sldata->clip_ubo);
1063         }
1064
1065         {
1066                 DRWState state = (
1067                         DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES |
1068                         DRW_STATE_WIRE);
1069                 psl->refract_pass = DRW_pass_create("Opaque Refraction Pass", state);
1070         }
1071
1072         {
1073                 DRWState state = (
1074                         DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_EQUAL | DRW_STATE_CLIP_PLANES |
1075                         DRW_STATE_WIRE | DRW_STATE_WRITE_STENCIL);
1076                 psl->sss_pass = DRW_pass_create("Subsurface Pass", state);
1077                 e_data.sss_count = 0;
1078         }
1079
1080         {
1081                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_CLIP_PLANES | DRW_STATE_WIRE;
1082                 psl->transparent_pass = DRW_pass_create("Material Transparent Pass", state);
1083         }
1084
1085         {
1086                 psl->update_noise_pass = DRW_pass_create("Update Noise Pass", DRW_STATE_WRITE_COLOR);
1087                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.update_noise_sh, psl->update_noise_pass);
1088                 DRW_shgroup_uniform_texture(grp, "blueNoise", e_data.noise_tex);
1089                 DRW_shgroup_uniform_vec3(grp, "offsets", e_data.noise_offsets, 1);
1090                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
1091         }
1092 }
1093
1094 #define ADD_SHGROUP_CALL(shgrp, ob, ma, geom, oedata) do { \
1095         if (is_sculpt_mode_draw) { \
1096                 DRW_shgroup_call_sculpt_add(shgrp, ob, ob->obmat); \
1097         } \
1098         else { \
1099                 if (oedata) { \
1100                         DRW_shgroup_call_object_add_with_callback(shgrp, geom, ob, ma, EEVEE_lightprobes_obj_visibility_cb, oedata); \
1101                 } \
1102                 else { \
1103                         DRW_shgroup_call_object_add_ex(shgrp, geom, ob, ma, false); \
1104                 } \
1105         } \
1106 } while (0)
1107
1108 #define ADD_SHGROUP_CALL_SAFE(shgrp, ob, ma, geom, oedata) do { \
1109         if (shgrp) { \
1110                 ADD_SHGROUP_CALL(shgrp, ob, ma, geom, oedata); \
1111         } \
1112 } while (0)
1113
1114 typedef struct EeveeMaterialShadingGroups {
1115         struct DRWShadingGroup *shading_grp;
1116         struct DRWShadingGroup *depth_grp;
1117         struct DRWShadingGroup *depth_clip_grp;
1118 } EeveeMaterialShadingGroups;
1119
1120 static void material_opaque(
1121         Material *ma, GHash *material_hash, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1122         bool do_cull, bool use_flat_nor, struct GPUMaterial **gpumat, struct GPUMaterial **gpumat_depth,
1123         struct DRWShadingGroup **shgrp, struct DRWShadingGroup **shgrp_depth, struct DRWShadingGroup **shgrp_depth_clip)
1124 {
1125         EEVEE_EffectsInfo *effects = vedata->stl->effects;
1126         const DRWContextState *draw_ctx = DRW_context_state_get();
1127         Scene *scene = draw_ctx->scene;
1128         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1129         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
1130         EEVEE_LampsInfo *linfo = sldata->lamps;
1131         bool use_diffuse, use_glossy, use_refract;
1132
1133         float *color_p = &ma->r;
1134         float *metal_p = &ma->metallic;
1135         float *spec_p = &ma->spec;
1136         float *rough_p = &ma->roughness;
1137
1138         const bool use_gpumat = (ma->use_nodes && ma->nodetree);
1139         const bool use_ssrefract = ((ma->blend_flag & MA_BL_SS_REFRACTION) != 0) &&
1140                                  ((effects->enabled_effects & EFFECT_REFRACT) != 0);
1141         bool use_sss = ((effects->enabled_effects & EFFECT_SSS) != 0);
1142         const bool use_translucency = use_sss && ((ma->blend_flag & MA_BL_TRANSLUCENCY) != 0);
1143
1144         EeveeMaterialShadingGroups *emsg = BLI_ghash_lookup(material_hash, (const void *)ma);
1145
1146         if (emsg) {
1147                 *shgrp = emsg->shading_grp;
1148                 *shgrp_depth = emsg->depth_grp;
1149                 *shgrp_depth_clip = emsg->depth_clip_grp;
1150
1151                 /* This will have been created already, just perform a lookup. */
1152                 *gpumat = (use_gpumat) ? EEVEE_material_mesh_get(
1153                         scene, ma, vedata, false, false, use_ssrefract, use_sss, use_translucency, linfo->shadow_method) : NULL;
1154                 *gpumat_depth = (use_gpumat) ? EEVEE_material_mesh_depth_get(
1155                         scene, ma, (ma->blend_method == MA_BM_HASHED), false) : NULL;
1156                 return;
1157         }
1158
1159         if (use_gpumat) {
1160                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
1161                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1162                 static float half = 0.5f;
1163
1164                 /* Shading */
1165                 *gpumat = EEVEE_material_mesh_get(
1166                         scene, ma, vedata, false, false, use_ssrefract,
1167                         use_sss, use_translucency, linfo->shadow_method);
1168
1169                 GPUMaterialStatus status_mat_surface = GPU_material_status(*gpumat);
1170
1171                 /* Alpha CLipped : Discard pixel from depth pass, then
1172                  * fail the depth test for shading. */
1173                 if (ELEM(ma->blend_method, MA_BM_CLIP, MA_BM_HASHED)) {
1174                         *gpumat_depth = EEVEE_material_mesh_depth_get(scene, ma, (ma->blend_method == MA_BM_HASHED), false);
1175
1176                         GPUMaterialStatus status_mat_depth = GPU_material_status(*gpumat_depth);
1177                         if (status_mat_depth != GPU_MAT_SUCCESS) {
1178                                 /* Mixing both flags. If depth shader fails, show it to the user by not using
1179                                  * the surface shader. */
1180                                 status_mat_surface = status_mat_depth;
1181                         }
1182                         else if (use_ssrefract) {
1183                                 *shgrp_depth = DRW_shgroup_material_create(
1184                                         *gpumat_depth, (do_cull) ? psl->refract_depth_pass_cull : psl->refract_depth_pass);
1185                                 *shgrp_depth_clip = DRW_shgroup_material_create(
1186                                         *gpumat_depth, (do_cull) ? psl->refract_depth_pass_clip_cull : psl->refract_depth_pass_clip);
1187                         }
1188                         else {
1189                                 *shgrp_depth = DRW_shgroup_material_create(
1190                                         *gpumat_depth, (do_cull) ? psl->depth_pass_cull : psl->depth_pass);
1191                                 *shgrp_depth_clip = DRW_shgroup_material_create(
1192                                         *gpumat_depth, (do_cull) ? psl->depth_pass_clip_cull : psl->depth_pass_clip);
1193                         }
1194
1195                         if (*shgrp_depth != NULL) {
1196                                 use_diffuse = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_DIFFUSE);
1197                                 use_glossy = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_GLOSSY);
1198                                 use_refract = GPU_material_flag_get(*gpumat_depth, GPU_MATFLAG_REFRACT);
1199
1200                                 add_standard_uniforms(*shgrp_depth, sldata, vedata, NULL, NULL,
1201                                                       use_diffuse, use_glossy, use_refract, false, false);
1202                                 add_standard_uniforms(*shgrp_depth_clip, sldata, vedata, NULL, NULL,
1203                                                       use_diffuse, use_glossy, use_refract, false, false);
1204
1205                                 if (ma->blend_method == MA_BM_CLIP) {
1206                                         DRW_shgroup_uniform_float(*shgrp_depth, "alphaThreshold", &ma->alpha_threshold, 1);
1207                                         DRW_shgroup_uniform_float(*shgrp_depth_clip, "alphaThreshold", &ma->alpha_threshold, 1);
1208                                 }
1209                                 else if (ma->blend_method == MA_BM_HASHED) {
1210                                         DRW_shgroup_uniform_float(*shgrp_depth, "hashAlphaOffset", &e_data.alpha_hash_offset, 1);
1211                                         DRW_shgroup_uniform_float(*shgrp_depth_clip, "hashAlphaOffset", &e_data.alpha_hash_offset, 1);
1212                                         DRW_shgroup_uniform_float_copy(*shgrp_depth, "hashAlphaScale", e_data.alpha_hash_scale);
1213                                         DRW_shgroup_uniform_float_copy(*shgrp_depth_clip, "hashAlphaScale", e_data.alpha_hash_scale);
1214                                 }
1215                         }
1216                 }
1217
1218                 switch (status_mat_surface) {
1219                         case GPU_MAT_SUCCESS:
1220                         {
1221                                 static int no_ssr = -1;
1222                                 static int first_ssr = 1;
1223                                 int *ssr_id = (((effects->enabled_effects & EFFECT_SSR) != 0) && !use_ssrefract) ? &first_ssr : &no_ssr;
1224                                 use_diffuse = GPU_material_flag_get(*gpumat, GPU_MATFLAG_DIFFUSE);
1225                                 use_glossy = GPU_material_flag_get(*gpumat, GPU_MATFLAG_GLOSSY);
1226                                 use_refract = GPU_material_flag_get(*gpumat, GPU_MATFLAG_REFRACT);
1227                                 use_sss = use_sss && GPU_material_flag_get(*gpumat, GPU_MATFLAG_SSS);
1228
1229                                 *shgrp = DRW_shgroup_material_create(
1230                                         *gpumat,
1231                                         (use_ssrefract) ? psl->refract_pass :
1232                                         (use_sss) ? psl->sss_pass : psl->material_pass);
1233
1234                                 add_standard_uniforms(*shgrp, sldata, vedata, ssr_id, &ma->refract_depth,
1235                                                       use_diffuse, use_glossy, use_refract, use_ssrefract, false);
1236
1237                                 if (use_sss) {
1238                                         struct GPUTexture *sss_tex_profile = NULL;
1239                                         struct GPUUniformBuffer *sss_profile = GPU_material_sss_profile_get(
1240                                                 *gpumat,
1241                                                 stl->effects->sss_sample_count,
1242                                                 &sss_tex_profile);
1243
1244                                         if (sss_profile) {
1245                                                 if (use_translucency) {
1246                                                         DRW_shgroup_uniform_block(*shgrp, "sssProfile", sss_profile);
1247                                                         DRW_shgroup_uniform_texture(*shgrp, "sssTexProfile", sss_tex_profile);
1248                                                 }
1249
1250                                                 /* Limit of 8 bit stencil buffer. ID 255 is refraction. */
1251                                                 if (e_data.sss_count < 254) {
1252                                                         DRW_shgroup_stencil_mask(*shgrp, e_data.sss_count + 1);
1253                                                         EEVEE_subsurface_add_pass(sldata, vedata, e_data.sss_count + 1, sss_profile);
1254                                                         e_data.sss_count++;
1255                                                 }
1256                                                 else {
1257                                                         /* TODO : display message. */
1258                                                         printf("Error: Too many different Subsurface shader in the scene.\n");
1259                                                 }
1260                                         }
1261                                         else {
1262                                                 if (use_translucency) {
1263                                                         /* NOTE: This is a nasty workaround, because the sss profile might not have been generated
1264                                                          * but the UBO is still declared in this case even if not used. But rendering without a
1265                                                          * bound UBO might result in crashes on certain platform. */
1266                                                         DRW_shgroup_uniform_block(*shgrp, "sssProfile", e_data.dummy_sss_profile);
1267                                                 }
1268                                         }
1269                                 }
1270                                 else {
1271                                         if (use_translucency) {
1272                                                 DRW_shgroup_uniform_block(*shgrp, "sssProfile", e_data.dummy_sss_profile);
1273                                         }
1274                                 }
1275                                 break;
1276                         }
1277                         case GPU_MAT_QUEUED:
1278                         {
1279                                 color_p = compile_col;
1280                                 metal_p = spec_p = rough_p = &half;
1281                                 break;
1282                         }
1283                         case GPU_MAT_FAILED:
1284                         default:
1285                                 color_p = error_col;
1286                                 metal_p = spec_p = rough_p = &half;
1287                                 break;
1288                 }
1289         }
1290
1291         /* Fallback to default shader */
1292         if (*shgrp == NULL) {
1293                 bool use_ssr = ((effects->enabled_effects & EFFECT_SSR) != 0);
1294                 *shgrp = EEVEE_default_shading_group_get(sldata, vedata,
1295                                                          NULL, NULL, NULL,
1296                                                          false, use_flat_nor, use_ssr, linfo->shadow_method);
1297                 DRW_shgroup_uniform_vec3(*shgrp, "basecol", color_p, 1);
1298                 DRW_shgroup_uniform_float(*shgrp, "metallic", metal_p, 1);
1299                 DRW_shgroup_uniform_float(*shgrp, "specular", spec_p, 1);
1300                 DRW_shgroup_uniform_float(*shgrp, "roughness", rough_p, 1);
1301         }
1302
1303         /* Fallback default depth prepass */
1304         if (*shgrp_depth == NULL) {
1305                 if (use_ssrefract) {
1306                         *shgrp_depth = (do_cull) ? stl->g_data->refract_depth_shgrp_cull : stl->g_data->refract_depth_shgrp;
1307                         *shgrp_depth_clip = (do_cull) ? stl->g_data->refract_depth_shgrp_clip_cull : stl->g_data->refract_depth_shgrp_clip;
1308                 }
1309                 else {
1310                         *shgrp_depth = (do_cull) ? stl->g_data->depth_shgrp_cull : stl->g_data->depth_shgrp;
1311                         *shgrp_depth_clip = (do_cull) ? stl->g_data->depth_shgrp_clip_cull : stl->g_data->depth_shgrp_clip;
1312                 }
1313         }
1314
1315         emsg = MEM_mallocN(sizeof(EeveeMaterialShadingGroups), "EeveeMaterialShadingGroups");
1316         emsg->shading_grp = *shgrp;
1317         emsg->depth_grp = *shgrp_depth;
1318         emsg->depth_clip_grp = *shgrp_depth_clip;
1319         BLI_ghash_insert(material_hash, ma, emsg);
1320 }
1321
1322 static void material_transparent(
1323         Material *ma, EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata,
1324         bool do_cull, bool use_flat_nor,
1325         struct GPUMaterial **gpumat, struct DRWShadingGroup **shgrp, struct DRWShadingGroup **shgrp_depth)
1326 {
1327         const DRWContextState *draw_ctx = DRW_context_state_get();
1328         Scene *scene = draw_ctx->scene;
1329         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1330         EEVEE_PassList *psl = ((EEVEE_Data *)vedata)->psl;
1331         EEVEE_LampsInfo *linfo = sldata->lamps;
1332
1333         const bool use_ssrefract = (
1334                 ((ma->blend_flag & MA_BL_SS_REFRACTION) != 0) &&
1335                 ((stl->effects->enabled_effects & EFFECT_REFRACT) != 0)
1336         );
1337         float *color_p = &ma->r;
1338         float *metal_p = &ma->metallic;
1339         float *spec_p = &ma->spec;
1340         float *rough_p = &ma->roughness;
1341
1342         if (ma->use_nodes && ma->nodetree) {
1343                 static float error_col[3] = {1.0f, 0.0f, 1.0f};
1344                 static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1345                 static float half = 0.5f;
1346
1347                 /* Shading */
1348                 *gpumat = EEVEE_material_mesh_get(
1349                         scene, ma, vedata, true, (ma->blend_method == MA_BM_MULTIPLY), use_ssrefract,
1350                         false, false, linfo->shadow_method);
1351
1352                 switch (GPU_material_status(*gpumat)) {
1353                         case GPU_MAT_SUCCESS:
1354                         {
1355                                 static int ssr_id = -1; /* TODO transparent SSR */
1356                                 bool use_blend = (ma->blend_method & MA_BM_BLEND) != 0;
1357
1358                                 *shgrp = DRW_shgroup_material_create(*gpumat, psl->transparent_pass);
1359
1360                                 bool use_diffuse = GPU_material_flag_get(*gpumat, GPU_MATFLAG_DIFFUSE);
1361                                 bool use_glossy = GPU_material_flag_get(*gpumat, GPU_MATFLAG_GLOSSY);
1362                                 bool use_refract = GPU_material_flag_get(*gpumat, GPU_MATFLAG_REFRACT);
1363
1364                                 add_standard_uniforms(*shgrp, sldata, vedata, &ssr_id, &ma->refract_depth,
1365                                                       use_diffuse, use_glossy, use_refract, use_ssrefract, use_blend);
1366                                 break;
1367                         }
1368                         case GPU_MAT_QUEUED:
1369                         {
1370                                 /* TODO Bypass probe compilation. */
1371                                 color_p = compile_col;
1372                                 metal_p = spec_p = rough_p = &half;
1373                                 break;
1374                         }
1375                         case GPU_MAT_FAILED:
1376                         default:
1377                                 color_p = error_col;
1378                                 metal_p = spec_p = rough_p = &half;
1379                                 break;
1380                 }
1381         }
1382
1383         /* Fallback to default shader */
1384         if (*shgrp == NULL) {
1385                 *shgrp = EEVEE_default_shading_group_create(
1386                         sldata, vedata, psl->transparent_pass,
1387                         false, use_flat_nor, true, false, linfo->shadow_method);
1388                 DRW_shgroup_uniform_vec3(*shgrp, "basecol", color_p, 1);
1389                 DRW_shgroup_uniform_float(*shgrp, "metallic", metal_p, 1);
1390                 DRW_shgroup_uniform_float(*shgrp, "specular", spec_p, 1);
1391                 DRW_shgroup_uniform_float(*shgrp, "roughness", rough_p, 1);
1392         }
1393
1394         const bool use_prepass = ((ma->blend_flag & MA_BL_HIDE_BACKSIDE) != 0);
1395
1396         DRWState all_state = (
1397                 DRW_STATE_WRITE_DEPTH | DRW_STATE_WRITE_COLOR | DRW_STATE_CULL_BACK |
1398                 DRW_STATE_DEPTH_LESS_EQUAL | DRW_STATE_DEPTH_EQUAL |
1399                 DRW_STATE_BLEND | DRW_STATE_ADDITIVE | DRW_STATE_MULTIPLY
1400         );
1401
1402         DRWState cur_state = DRW_STATE_WRITE_COLOR;
1403         cur_state |= (use_prepass) ? DRW_STATE_DEPTH_EQUAL : DRW_STATE_DEPTH_LESS_EQUAL;
1404         cur_state |= (do_cull) ? DRW_STATE_CULL_BACK : 0;
1405
1406         switch (ma->blend_method) {
1407                 case MA_BM_ADD:
1408                         cur_state |= DRW_STATE_ADDITIVE;
1409                         break;
1410                 case MA_BM_MULTIPLY:
1411                         cur_state |= DRW_STATE_MULTIPLY;
1412                         break;
1413                 case MA_BM_BLEND:
1414                         cur_state |= DRW_STATE_BLEND;
1415                         break;
1416                 default:
1417                         BLI_assert(0);
1418                         break;
1419         }
1420
1421         /* Disable other blend modes and use the one we want. */
1422         DRW_shgroup_state_disable(*shgrp, all_state);
1423         DRW_shgroup_state_enable(*shgrp, cur_state);
1424
1425         /* Depth prepass */
1426         if (use_prepass) {
1427                 *shgrp_depth = DRW_shgroup_create(e_data.default_prepass_clip_sh, psl->transparent_pass);
1428                 DRW_shgroup_uniform_block(*shgrp_depth, "clip_block", sldata->clip_ubo);
1429
1430                 cur_state = DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL;
1431                 cur_state |= (do_cull) ? DRW_STATE_CULL_BACK : 0;
1432
1433                 DRW_shgroup_state_disable(*shgrp_depth, all_state);
1434                 DRW_shgroup_state_enable(*shgrp_depth, cur_state);
1435         }
1436 }
1437
1438 void EEVEE_materials_cache_populate(EEVEE_Data *vedata, EEVEE_ViewLayerData *sldata, Object *ob, bool *cast_shadow)
1439 {
1440         EEVEE_PassList *psl = vedata->psl;
1441         EEVEE_StorageList *stl = vedata->stl;
1442         const DRWContextState *draw_ctx = DRW_context_state_get();
1443         Scene *scene = draw_ctx->scene;
1444         GHash *material_hash = stl->g_data->material_hash;
1445
1446         const bool do_cull = (draw_ctx->v3d && (draw_ctx->v3d->flag2 & V3D_BACKFACE_CULLING));
1447         const bool is_active = (ob == draw_ctx->obact);
1448         const bool is_sculpt_mode = is_active && (draw_ctx->object_mode & OB_MODE_SCULPT) != 0;
1449 #if 0
1450         const bool is_sculpt_mode_draw = is_sculpt_mode && (draw_ctx->v3d->flag2 & V3D_SHOW_MODE_SHADE_OVERRIDE) == 0;
1451 #else
1452         /* For now just force fully shaded with eevee when supported. */
1453         const bool is_sculpt_mode_draw =
1454                 is_sculpt_mode &&
1455                 ((ob->sculpt && ob->sculpt->pbvh) && (BKE_pbvh_type(ob->sculpt->pbvh) != PBVH_FACES));
1456 #endif
1457         const bool is_default_mode_shader = is_sculpt_mode;
1458
1459         /* First get materials for this mesh. */
1460         if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL)) {
1461                 const int materials_len = MAX2(1, (is_sculpt_mode_draw ? 1 : ob->totcol));
1462
1463                 struct DRWShadingGroup **shgrp_array = BLI_array_alloca(shgrp_array, materials_len);
1464                 struct DRWShadingGroup **shgrp_depth_array = BLI_array_alloca(shgrp_depth_array, materials_len);
1465                 struct DRWShadingGroup **shgrp_depth_clip_array = BLI_array_alloca(shgrp_depth_clip_array, materials_len);
1466
1467                 struct GPUMaterial **gpumat_array = BLI_array_alloca(gpumat_array, materials_len);
1468                 struct GPUMaterial **gpumat_depth_array = BLI_array_alloca(gpumat_array, materials_len);
1469
1470                 bool use_flat_nor = false;
1471
1472                 if (is_default_mode_shader) {
1473                         if (is_sculpt_mode_draw) {
1474                                 use_flat_nor = DRW_object_is_flat_normal(ob);
1475                         }
1476                 }
1477
1478                 for (int i = 0; i < materials_len; ++i) {
1479                         Material *ma;
1480
1481                         if (is_sculpt_mode_draw) {
1482                                 ma = NULL;
1483                         }
1484                         else {
1485                                 ma = give_current_material(ob, i + 1);
1486                         }
1487
1488                         gpumat_array[i] = NULL;
1489                         gpumat_depth_array[i] = NULL;
1490                         shgrp_array[i] = NULL;
1491                         shgrp_depth_array[i] = NULL;
1492                         shgrp_depth_clip_array[i] = NULL;
1493
1494                         if (ma == NULL)
1495                                 ma = &defmaterial;
1496
1497                         switch (ma->blend_method) {
1498                                 case MA_BM_SOLID:
1499                                 case MA_BM_CLIP:
1500                                 case MA_BM_HASHED:
1501                                         material_opaque(ma, material_hash, sldata, vedata, do_cull, use_flat_nor,
1502                                                 &gpumat_array[i], &gpumat_depth_array[i],
1503                                                 &shgrp_array[i], &shgrp_depth_array[i], &shgrp_depth_clip_array[i]);
1504                                         break;
1505                                 case MA_BM_ADD:
1506                                 case MA_BM_MULTIPLY:
1507                                 case MA_BM_BLEND:
1508                                         material_transparent(ma, sldata, vedata, do_cull, use_flat_nor,
1509                                                 &gpumat_array[i], &shgrp_array[i], &shgrp_depth_array[i]);
1510                                         break;
1511                                 default:
1512                                         BLI_assert(0);
1513                                         break;
1514                         }
1515                 }
1516
1517                 if (is_sculpt_mode && is_sculpt_mode_draw == false) {
1518                         DRW_cache_mesh_sculpt_coords_ensure(ob);
1519                 }
1520
1521                 /* Only support single volume material for now. */
1522                 /* XXX We rely on the previously compiled surface shader
1523                  * to know if the material has a "volume nodetree".
1524                  */
1525                 bool use_volume_material = (gpumat_array[0] && GPU_material_use_domain_volume(gpumat_array[0]));
1526
1527                 if (ob->dt >= OB_SOLID) {
1528                         /* Get per-material split surface */
1529                         char *auto_layer_names;
1530                         int *auto_layer_is_srgb;
1531                         int auto_layer_count;
1532                         struct GPUBatch **mat_geom = DRW_cache_object_surface_material_get(
1533                                 ob, gpumat_array, materials_len,
1534                                 &auto_layer_names,
1535                                 &auto_layer_is_srgb,
1536                                 &auto_layer_count);
1537                         if (mat_geom) {
1538                                 for (int i = 0; i < materials_len; ++i) {
1539                                         if (mat_geom[i] == NULL) {
1540                                                 continue;
1541                                         }
1542                                         EEVEE_ObjectEngineData *oedata = NULL;
1543                                         Material *ma = give_current_material(ob, i + 1);
1544
1545                                         if (ma == NULL)
1546                                                 ma = &defmaterial;
1547
1548                                         /* Do not render surface if we are rendering a volume object
1549                                          * and do not have a surface closure. */
1550                                         if (use_volume_material &&
1551                                             (gpumat_array[i] && !GPU_material_use_domain_surface(gpumat_array[i])))
1552                                         {
1553                                                 continue;
1554                                         }
1555
1556                                         /* XXX TODO rewrite this to include the dupli objects.
1557                                          * This means we cannot exclude dupli objects from reflections!!! */
1558                                         if ((ob->base_flag & BASE_FROMDUPLI) == 0) {
1559                                                 oedata = EEVEE_object_data_ensure(ob);
1560                                                 oedata->ob = ob;
1561                                                 oedata->test_data = &sldata->probes->vis_data;
1562                                         }
1563
1564                                         /* Shading pass */
1565                                         ADD_SHGROUP_CALL(shgrp_array[i], ob, ma, mat_geom[i], oedata);
1566
1567                                         /* Depth Prepass */
1568                                         ADD_SHGROUP_CALL_SAFE(shgrp_depth_array[i], ob, ma, mat_geom[i], oedata);
1569                                         ADD_SHGROUP_CALL_SAFE(shgrp_depth_clip_array[i], ob, ma, mat_geom[i], oedata);
1570
1571                                         char *name = auto_layer_names;
1572                                         for (int j = 0; j < auto_layer_count; ++j) {
1573                                                 /* TODO don't add these uniform when not needed (default pass shaders). */
1574                                                 if (shgrp_array[i]) {
1575                                                         DRW_shgroup_uniform_bool(shgrp_array[i], name, &auto_layer_is_srgb[j], 1);
1576                                                 }
1577                                                 if (shgrp_depth_array[i]) {
1578                                                         DRW_shgroup_uniform_bool(shgrp_depth_array[i], name, &auto_layer_is_srgb[j], 1);
1579                                                 }
1580                                                 if (shgrp_depth_clip_array[i]) {
1581                                                         DRW_shgroup_uniform_bool(shgrp_depth_clip_array[i], name, &auto_layer_is_srgb[j], 1);
1582                                                 }
1583                                                 /* Go to next layer name. */
1584                                                 while (*name != '\0') { name++; }
1585                                                 name += 1;
1586                                         }
1587
1588                                         /* Shadow Pass */
1589                                         if (ma->use_nodes && ma->nodetree && (ma->blend_method != MA_BM_SOLID)) {
1590                                                 struct GPUMaterial *gpumat;
1591                                                 switch (ma->blend_shadow) {
1592                                                         case MA_BS_SOLID:
1593                                                                 EEVEE_lights_cache_shcaster_add(
1594                                                                         sldata, stl, mat_geom[i], ob);
1595                                                                 *cast_shadow = true;
1596                                                                 break;
1597                                                         case MA_BS_CLIP:
1598                                                                 gpumat = EEVEE_material_mesh_depth_get(scene, ma, false, true);
1599                                                                 EEVEE_lights_cache_shcaster_material_add(
1600                                                                         sldata, psl, gpumat, mat_geom[i], ob, &ma->alpha_threshold);
1601                                                                 *cast_shadow = true;
1602                                                                 break;
1603                                                         case MA_BS_HASHED:
1604                                                                 gpumat = EEVEE_material_mesh_depth_get(scene, ma, true, true);
1605                                                                 EEVEE_lights_cache_shcaster_material_add(
1606                                                                         sldata, psl, gpumat, mat_geom[i], ob, NULL);
1607                                                                 *cast_shadow = true;
1608                                                                 break;
1609                                                         case MA_BS_NONE:
1610                                                         default:
1611                                                                 break;
1612                                                 }
1613                                         }
1614                                         else {
1615                                                 EEVEE_lights_cache_shcaster_add(sldata, stl, mat_geom[i], ob);
1616                                                 *cast_shadow = true;
1617                                         }
1618                                 }
1619                         }
1620                 }
1621
1622                 /* Volumetrics */
1623                 if (((stl->effects->enabled_effects & EFFECT_VOLUMETRIC) != 0) && use_volume_material) {
1624                         EEVEE_volumes_cache_object_add(sldata, vedata, scene, ob);
1625                 }
1626         }
1627 }
1628
1629 void EEVEE_hair_cache_populate(EEVEE_Data *vedata, EEVEE_ViewLayerData *sldata, Object *ob, bool *cast_shadow)
1630 {
1631         EEVEE_PassList *psl = vedata->psl;
1632         EEVEE_StorageList *stl = vedata->stl;
1633         const DRWContextState *draw_ctx = DRW_context_state_get();
1634         Scene *scene = draw_ctx->scene;
1635
1636         bool use_ssr = ((stl->effects->enabled_effects & EFFECT_SSR) != 0);
1637
1638         if (ob->type == OB_MESH) {
1639                 if (ob != draw_ctx->object_edit) {
1640                         for (ModifierData *md = ob->modifiers.first; md; md = md->next) {
1641                                 if (md->type != eModifierType_ParticleSystem) {
1642                                         continue;
1643                                 }
1644                                 ParticleSystem *psys = ((ParticleSystemModifierData *)md)->psys;
1645                                 if (!psys_check_enabled(ob, psys, false)) {
1646                                         continue;
1647                                 }
1648                                 if (!DRW_object_is_visible_psys_in_active_context(ob, psys)) {
1649                                         continue;
1650                                 }
1651                                 ParticleSettings *part = psys->part;
1652                                 const int draw_as = (part->draw_as == PART_DRAW_REND) ? part->ren_as : part->draw_as;
1653                                 if (draw_as != PART_DRAW_PATH) {
1654                                         continue;
1655                                 }
1656
1657                                 DRWShadingGroup *shgrp = NULL;
1658                                 Material *ma = give_current_material(ob, part->omat);
1659
1660                                 if (ma == NULL) {
1661                                         ma = &defmaterial;
1662                                 }
1663
1664                                 float *color_p = &ma->r;
1665                                 float *metal_p = &ma->metallic;
1666                                 float *spec_p = &ma->spec;
1667                                 float *rough_p = &ma->roughness;
1668
1669                                 shgrp = DRW_shgroup_hair_create(
1670                                         ob, psys, md,
1671                                         psl->depth_pass,
1672                                         e_data.default_hair_prepass_sh);
1673
1674                                 shgrp = DRW_shgroup_hair_create(
1675                                         ob, psys, md,
1676                                         psl->depth_pass_clip,
1677                                         e_data.default_hair_prepass_clip_sh);
1678                                 DRW_shgroup_uniform_block(shgrp, "clip_block", sldata->clip_ubo);
1679
1680                                 shgrp = NULL;
1681                                 if (ma->use_nodes && ma->nodetree) {
1682                                         static int ssr_id;
1683                                         ssr_id = (use_ssr) ? 1 : -1;
1684                                         static float half = 0.5f;
1685                                         static float error_col[3] = {1.0f, 0.0f, 1.0f};
1686                                         static float compile_col[3] = {0.5f, 0.5f, 0.5f};
1687                                         struct GPUMaterial *gpumat = EEVEE_material_hair_get(scene, ma, sldata->lamps->shadow_method);
1688
1689                                         switch (GPU_material_status(gpumat)) {
1690                                                 case GPU_MAT_SUCCESS:
1691                                                 {
1692                                                         bool use_diffuse = GPU_material_flag_get(gpumat, GPU_MATFLAG_DIFFUSE);
1693                                                         bool use_glossy = GPU_material_flag_get(gpumat, GPU_MATFLAG_GLOSSY);
1694                                                         bool use_refract = GPU_material_flag_get(gpumat, GPU_MATFLAG_REFRACT);
1695
1696                                                         shgrp = DRW_shgroup_material_hair_create(
1697                                                                 ob, psys, md,
1698                                                                 psl->material_pass,
1699                                                                 gpumat);
1700
1701                                                         add_standard_uniforms(shgrp, sldata, vedata, &ssr_id, NULL,
1702                                                                               use_diffuse, use_glossy, use_refract, false, false);
1703                                                         break;
1704                                                 }
1705                                                 case GPU_MAT_QUEUED:
1706                                                 {
1707                                                         color_p = compile_col;
1708                                                         metal_p = spec_p = rough_p = &half;
1709                                                         break;
1710                                                 }
1711                                                 case GPU_MAT_FAILED:
1712                                                 default:
1713                                                         color_p = error_col;
1714                                                         metal_p = spec_p = rough_p = &half;
1715                                                         break;
1716                                         }
1717                                 }
1718
1719                                 /* Fallback to default shader */
1720                                 if (shgrp == NULL) {
1721                                         shgrp = EEVEE_default_shading_group_get(sldata, vedata,
1722                                                                                 ob, psys, md,
1723                                                                                 true, false, use_ssr,
1724                                                                                 sldata->lamps->shadow_method);
1725                                         DRW_shgroup_uniform_vec3(shgrp, "basecol", color_p, 1);
1726                                         DRW_shgroup_uniform_float(shgrp, "metallic", metal_p, 1);
1727                                         DRW_shgroup_uniform_float(shgrp, "specular", spec_p, 1);
1728                                         DRW_shgroup_uniform_float(shgrp, "roughness", rough_p, 1);
1729                                 }
1730
1731                                 /* Shadows */
1732                                 DRW_shgroup_hair_create(
1733                                         ob, psys, md,
1734                                         psl->shadow_pass,
1735                                         e_data.default_hair_prepass_sh);
1736                                 *cast_shadow = true;
1737                         }
1738                 }
1739         }
1740 }
1741
1742 void EEVEE_materials_cache_finish(EEVEE_Data *vedata)
1743 {
1744         EEVEE_StorageList *stl = ((EEVEE_Data *)vedata)->stl;
1745
1746         /* Look-Dev */
1747         const DRWContextState *draw_ctx = DRW_context_state_get();
1748         const View3D *v3d = draw_ctx->v3d;
1749         if (LOOK_DEV_OVERLAY_ENABLED(v3d)) {
1750                 EEVEE_ViewLayerData *sldata = EEVEE_view_layer_data_ensure();
1751                 EEVEE_LampsInfo *linfo = sldata->lamps;
1752                 struct GPUBatch *sphere = DRW_cache_sphere_get();
1753                 static float mat1[4][4];
1754                 static float color[3] = {0.8f, 0.8f, 0.8f};
1755                 static float metallic_on = 1.0f;
1756                 static float metallic_off = 0.00f;
1757                 static float specular_off = 0.5f;
1758                 static float specular_on = 1.0f;
1759                 static float roughness_off = 0.05f;
1760                 static float roughness_on = 1.00f;
1761
1762                 float view_mat[4][4];
1763                 DRW_viewport_matrix_get(view_mat, DRW_MAT_VIEWINV);
1764
1765                 DRWShadingGroup *shgrp = EEVEE_lookdev_shading_group_get(sldata, vedata, false, linfo->shadow_method);
1766                 DRW_shgroup_uniform_vec3(shgrp, "basecol", color, 1);
1767                 DRW_shgroup_uniform_float(shgrp, "metallic", &metallic_on, 1);
1768                 DRW_shgroup_uniform_float(shgrp, "specular", &specular_on, 1);
1769                 DRW_shgroup_uniform_float(shgrp, "roughness", &roughness_off, 1);
1770                 unit_m4(mat1);
1771                 mul_m4_m4m4(mat1, mat1, view_mat);
1772                 translate_m4(mat1, -1.5f, 0.0f, -5.0f);
1773                 DRW_shgroup_call_add(shgrp, sphere, mat1);
1774
1775                 shgrp = EEVEE_lookdev_shading_group_get(sldata, vedata, false, linfo->shadow_method);
1776                 DRW_shgroup_uniform_vec3(shgrp, "basecol", color, 1);
1777                 DRW_shgroup_uniform_float(shgrp, "metallic", &metallic_off, 1);
1778                 DRW_shgroup_uniform_float(shgrp, "specular", &specular_off, 1);
1779                 DRW_shgroup_uniform_float(shgrp, "roughness", &roughness_on, 1);
1780                 translate_m4(mat1, 3.0f, 0.0f, 0.0f);
1781                 DRW_shgroup_call_add(shgrp, sphere, mat1);
1782         }
1783         /* END */
1784
1785         BLI_ghash_free(stl->g_data->material_hash, NULL, MEM_freeN);
1786 }
1787
1788 void EEVEE_materials_free(void)
1789 {
1790         for (int i = 0; i < VAR_MAT_MAX; ++i) {
1791                 DRW_SHADER_FREE_SAFE(e_data.default_lit[i]);
1792         }
1793         MEM_SAFE_FREE(e_data.frag_shader_lib);
1794         MEM_SAFE_FREE(e_data.vert_shader_str);
1795         MEM_SAFE_FREE(e_data.volume_shader_lib);
1796         DRW_SHADER_FREE_SAFE(e_data.default_hair_prepass_sh);
1797         DRW_SHADER_FREE_SAFE(e_data.default_hair_prepass_clip_sh);
1798         DRW_SHADER_FREE_SAFE(e_data.default_prepass_sh);
1799         DRW_SHADER_FREE_SAFE(e_data.default_prepass_clip_sh);
1800         DRW_SHADER_FREE_SAFE(e_data.default_background);
1801         DRW_SHADER_FREE_SAFE(e_data.default_studiolight_background);
1802         DRW_SHADER_FREE_SAFE(e_data.update_noise_sh);
1803         DRW_TEXTURE_FREE_SAFE(e_data.util_tex);
1804         DRW_TEXTURE_FREE_SAFE(e_data.noise_tex);
1805         DRW_UBO_FREE_SAFE(e_data.dummy_sss_profile);
1806 }
1807
1808 void EEVEE_draw_default_passes(EEVEE_PassList *psl)
1809 {
1810         for (int i = 0; i < VAR_MAT_MAX; ++i) {
1811                 if (psl->default_pass[i]) {
1812                         DRW_draw_pass(psl->default_pass[i]);
1813                 }
1814         }
1815 }