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