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