doxygen: add newline after \file
[blender.git] / source / blender / draw / engines / eevee / eevee_lights.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 DNA
21  */
22
23 #include "DRW_render.h"
24
25 #include "BLI_dynstr.h"
26 #include "BLI_rand.h"
27 #include "BLI_rect.h"
28
29 #include "BKE_object.h"
30
31 #include "DEG_depsgraph_query.h"
32
33 #include "eevee_private.h"
34
35 #define SHADOW_CASTER_ALLOC_CHUNK 16
36
37 // #define DEBUG_CSM
38 // #define DEBUG_SHADOW_DISTRIBUTION
39
40 static struct {
41         struct GPUShader *shadow_sh;
42         struct GPUShader *shadow_store_cube_sh[SHADOW_METHOD_MAX];
43         struct GPUShader *shadow_store_cube_high_sh[SHADOW_METHOD_MAX];
44         struct GPUShader *shadow_store_cascade_sh[SHADOW_METHOD_MAX];
45         struct GPUShader *shadow_store_cascade_high_sh[SHADOW_METHOD_MAX];
46         struct GPUShader *shadow_copy_cube_sh[SHADOW_METHOD_MAX];
47         struct GPUShader *shadow_copy_cascade_sh[SHADOW_METHOD_MAX];
48 } e_data = {NULL}; /* Engine data */
49
50 extern char datatoc_shadow_vert_glsl[];
51 extern char datatoc_shadow_frag_glsl[];
52 extern char datatoc_shadow_store_frag_glsl[];
53 extern char datatoc_shadow_copy_frag_glsl[];
54 extern char datatoc_concentric_samples_lib_glsl[];
55
56 /* Prototypes */
57 static void eevee_light_setup(Object *ob, EEVEE_Light *evli);
58 static float light_attenuation_radius_get(Lamp *la, float light_threshold);
59
60 /* *********** LIGHT BITS *********** */
61 static void lightbits_set_single(EEVEE_LightBits *bitf, uint idx, bool val)
62 {
63         if (val) {
64                 bitf->fields[idx / 8] |=  (1 << (idx % 8));
65         }
66         else {
67                 bitf->fields[idx / 8] &= ~(1 << (idx % 8));
68         }
69 }
70
71 static void lightbits_set_all(EEVEE_LightBits *bitf, bool val)
72 {
73         memset(bitf, (val) ? 0xFF : 0x00, sizeof(EEVEE_LightBits));
74 }
75
76 static void lightbits_or(EEVEE_LightBits *r, const EEVEE_LightBits *v)
77 {
78         for (int i = 0; i < MAX_LIGHTBITS_FIELDS; ++i) {
79                 r->fields[i] |= v->fields[i];
80         }
81 }
82
83 static bool lightbits_get(const EEVEE_LightBits *r, uint idx)
84 {
85         return r->fields[idx / 8] & (1 << (idx % 8));
86 }
87
88 static void lightbits_convert(
89         EEVEE_LightBits *r, const EEVEE_LightBits *bitf, const int *light_bit_conv_table, uint table_length)
90 {
91         for (int i = 0; i < table_length; ++i) {
92                 if (lightbits_get(bitf, i) != 0) {
93                         if (light_bit_conv_table[i] >= 0) {
94                                 r->fields[i / 8] |= (1 << (i % 8));
95                         }
96                 }
97         }
98 }
99
100 /* *********** FUNCTIONS *********** */
101
102 void EEVEE_lights_init(EEVEE_ViewLayerData *sldata)
103 {
104         const uint shadow_ubo_size = sizeof(EEVEE_Shadow) * MAX_SHADOW +
105                                              sizeof(EEVEE_ShadowCube) * MAX_SHADOW_CUBE +
106                                              sizeof(EEVEE_ShadowCascade) * MAX_SHADOW_CASCADE;
107
108         const DRWContextState *draw_ctx = DRW_context_state_get();
109         const Scene *scene_eval = DEG_get_evaluated_scene(draw_ctx->depsgraph);
110
111         if (!e_data.shadow_sh) {
112                 e_data.shadow_sh = DRW_shader_create(
113                         datatoc_shadow_vert_glsl, NULL, datatoc_shadow_frag_glsl, NULL);
114         }
115
116         if (!sldata->lamps) {
117                 sldata->lamps              = MEM_callocN(sizeof(EEVEE_LampsInfo), "EEVEE_LampsInfo");
118                 sldata->light_ubo          = DRW_uniformbuffer_create(sizeof(EEVEE_Light) * MAX_LIGHT, NULL);
119                 sldata->shadow_ubo         = DRW_uniformbuffer_create(shadow_ubo_size, NULL);
120                 sldata->shadow_render_ubo  = DRW_uniformbuffer_create(sizeof(EEVEE_ShadowRender), NULL);
121
122                 for (int i = 0; i < 2; ++i) {
123                         sldata->shcasters_buffers[i].shadow_casters = MEM_callocN(sizeof(EEVEE_ShadowCaster) * SHADOW_CASTER_ALLOC_CHUNK, "EEVEE_ShadowCaster buf");
124                         sldata->shcasters_buffers[i].flags = MEM_callocN(sizeof(sldata->shcasters_buffers[0].flags) * SHADOW_CASTER_ALLOC_CHUNK, "EEVEE_shcast_buffer flags buf");
125                         sldata->shcasters_buffers[i].alloc_count = SHADOW_CASTER_ALLOC_CHUNK;
126                         sldata->shcasters_buffers[i].count = 0;
127                 }
128
129                 sldata->lamps->shcaster_frontbuffer = &sldata->shcasters_buffers[0];
130                 sldata->lamps->shcaster_backbuffer = &sldata->shcasters_buffers[1];
131         }
132
133         /* Flip buffers */
134         SWAP(EEVEE_ShadowCasterBuffer *, sldata->lamps->shcaster_frontbuffer, sldata->lamps->shcaster_backbuffer);
135
136         const int sh_method = scene_eval->eevee.shadow_method;
137         int sh_cube_size = scene_eval->eevee.shadow_cube_size;
138         int sh_cascade_size = scene_eval->eevee.shadow_cascade_size;
139         const bool sh_high_bitdepth = (scene_eval->eevee.flag & SCE_EEVEE_SHADOW_HIGH_BITDEPTH) != 0;
140         sldata->lamps->soft_shadows = (scene_eval->eevee.flag & SCE_EEVEE_SHADOW_SOFT) != 0;
141
142         EEVEE_LampsInfo *linfo = sldata->lamps;
143         if ((linfo->shadow_cube_size != sh_cube_size) ||
144             (linfo->shadow_method != sh_method) ||
145             (linfo->shadow_high_bitdepth != sh_high_bitdepth))
146         {
147                 BLI_assert((sh_cube_size > 0) && (sh_cube_size <= 4096));
148                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_pool);
149                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_target);
150                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_blur);
151
152                 /* Compute adequate size for the octahedral map. */
153                 linfo->shadow_cube_store_size = OCTAHEDRAL_SIZE_FROM_CUBESIZE(sh_cube_size);
154
155                 CLAMP(linfo->shadow_cube_store_size, 1, 4096);
156                 CLAMP(sh_cube_size, 1, 4096);
157
158                 linfo->shadow_render_data.cube_texel_size = 1.0f / sh_cube_size;
159         }
160
161         if ((linfo->shadow_cascade_size != sh_cascade_size) ||
162             (linfo->shadow_method != sh_method) ||
163             (linfo->shadow_high_bitdepth != sh_high_bitdepth))
164         {
165                 BLI_assert((sh_cascade_size > 0) && (sh_cascade_size <= 4096));
166                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_pool);
167                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_target);
168                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_blur);
169
170                 CLAMP(sh_cascade_size, 1, 4096);
171         }
172
173         linfo->shadow_high_bitdepth = sh_high_bitdepth;
174         linfo->shadow_method = sh_method;
175         linfo->shadow_cube_size = sh_cube_size;
176         linfo->shadow_cascade_size = sh_cascade_size;
177
178         /* only compile the ones needed. reduce startup time. */
179         if ((sh_method == SHADOW_ESM) && !e_data.shadow_copy_cube_sh[SHADOW_ESM]) {
180                 e_data.shadow_copy_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(
181                         datatoc_shadow_copy_frag_glsl,
182                         "#define ESM\n"
183                         "#define COPY\n");
184                 e_data.shadow_copy_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(
185                         datatoc_shadow_copy_frag_glsl,
186                         "#define ESM\n"
187                         "#define COPY\n"
188                         "#define CSM\n");
189         }
190         else if ((sh_method == SHADOW_VSM) && !e_data.shadow_copy_cube_sh[SHADOW_VSM]) {
191                 e_data.shadow_copy_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(
192                         datatoc_shadow_copy_frag_glsl,
193                         "#define VSM\n"
194                         "#define COPY\n");
195                 e_data.shadow_copy_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(
196                         datatoc_shadow_copy_frag_glsl,
197                         "#define VSM\n"
198                         "#define COPY\n"
199                         "#define CSM\n");
200         }
201 }
202
203 static GPUShader *eevee_lights_get_store_sh(int shadow_method, bool high_blur, bool cascade)
204 {
205         GPUShader **shader;
206
207         if (cascade) {
208                 shader = (high_blur) ? &e_data.shadow_store_cascade_high_sh[shadow_method]
209                                      : &e_data.shadow_store_cascade_sh[shadow_method];
210         }
211         else {
212                 shader = (high_blur) ? &e_data.shadow_store_cube_high_sh[shadow_method]
213                                      : &e_data.shadow_store_cube_sh[shadow_method];
214         }
215
216         if (*shader == NULL) {
217                 DynStr *ds_frag = BLI_dynstr_new();
218                 BLI_dynstr_append(ds_frag, datatoc_concentric_samples_lib_glsl);
219                 BLI_dynstr_append(ds_frag, datatoc_shadow_store_frag_glsl);
220                 char *store_shadow_shader_str = BLI_dynstr_get_cstring(ds_frag);
221                 BLI_dynstr_free(ds_frag);
222
223                 ds_frag = BLI_dynstr_new();
224                 BLI_dynstr_append(ds_frag, (shadow_method == SHADOW_VSM) ? "#define VSM\n" : "#define ESM\n");
225                 if (high_blur) BLI_dynstr_append(ds_frag, "#define HIGH_BLUR\n");
226                 if (cascade)   BLI_dynstr_append(ds_frag, "#define CSM\n");
227                 char *define_str = BLI_dynstr_get_cstring(ds_frag);
228                 BLI_dynstr_free(ds_frag);
229
230                 *shader = DRW_shader_create_fullscreen(
231                         store_shadow_shader_str, define_str);
232
233                 MEM_freeN(store_shadow_shader_str);
234                 MEM_freeN(define_str);
235         }
236
237         return *shader;
238 }
239
240 static DRWPass *eevee_lights_cube_store_pass_get(EEVEE_PassList *psl, EEVEE_ViewLayerData *sldata, int shadow_method, int shadow_samples_len)
241 {
242         bool high_blur = shadow_samples_len > 16;
243         DRWPass **pass = (high_blur) ? &psl->shadow_cube_store_pass : &psl->shadow_cube_store_high_pass;
244         if (*pass == NULL) {
245                 EEVEE_LampsInfo *linfo = sldata->lamps;
246                 *pass = DRW_pass_create("Shadow Cube Storage Pass", DRW_STATE_WRITE_COLOR);
247                 GPUShader *shader = eevee_lights_get_store_sh(shadow_method, high_blur, false);
248                 DRWShadingGroup *grp = DRW_shgroup_create(shader, *pass);
249                 DRW_shgroup_uniform_texture_ref(grp, "shadowTexture", &sldata->shadow_cube_blur);
250                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
251                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
252                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
253         }
254         return *pass;
255 }
256
257 static DRWPass *eevee_lights_cascade_store_pass_get(EEVEE_PassList *psl, EEVEE_ViewLayerData *sldata, int shadow_method, int shadow_samples_len)
258 {
259         bool high_blur = shadow_samples_len > 16;
260         DRWPass **pass = (high_blur) ? &psl->shadow_cascade_store_pass : &psl->shadow_cascade_store_high_pass;
261         if (*pass == NULL) {
262                 EEVEE_LampsInfo *linfo = sldata->lamps;
263                 *pass = DRW_pass_create("Shadow Cascade Storage Pass", DRW_STATE_WRITE_COLOR);
264                 GPUShader *shader = eevee_lights_get_store_sh(shadow_method, high_blur, true);
265                 DRWShadingGroup *grp = DRW_shgroup_create(shader, *pass);
266                 DRW_shgroup_uniform_texture_ref(grp, "shadowTexture", &sldata->shadow_cascade_blur);
267                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
268                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
269                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
270                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
271         }
272         return *pass;
273 }
274
275 void EEVEE_lights_cache_init(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
276 {
277         EEVEE_LampsInfo *linfo = sldata->lamps;
278         EEVEE_StorageList *stl = vedata->stl;
279         EEVEE_PassList *psl = vedata->psl;
280
281         linfo->shcaster_frontbuffer->count = 0;
282         linfo->num_light = 0;
283         linfo->num_cube_layer = 0;
284         linfo->num_cascade_layer = 0;
285         linfo->gpu_cube_len = linfo->gpu_cascade_len = linfo->gpu_shadow_len = 0;
286         linfo->cpu_cube_len = linfo->cpu_cascade_len = 0;
287         memset(linfo->light_ref, 0, sizeof(linfo->light_ref));
288         memset(linfo->shadow_cube_ref, 0, sizeof(linfo->shadow_cube_ref));
289         memset(linfo->shadow_cascade_ref, 0, sizeof(linfo->shadow_cascade_ref));
290         memset(linfo->new_shadow_id, -1, sizeof(linfo->new_shadow_id));
291
292         /* Shadow Casters: Reset flags. */
293         memset(linfo->shcaster_backbuffer->flags, (char)SHADOW_CASTER_PRUNED, linfo->shcaster_backbuffer->alloc_count);
294         memset(linfo->shcaster_frontbuffer->flags, 0x00, linfo->shcaster_frontbuffer->alloc_count);
295
296         psl->shadow_cube_store_pass = NULL;
297         psl->shadow_cube_store_high_pass = NULL;
298         psl->shadow_cascade_store_pass = NULL;
299         psl->shadow_cascade_store_high_pass = NULL;
300
301         {
302                 psl->shadow_cube_copy_pass = DRW_pass_create("Shadow Copy Pass", DRW_STATE_WRITE_COLOR);
303
304                 DRWShadingGroup *grp = DRW_shgroup_create(
305                         e_data.shadow_copy_cube_sh[linfo->shadow_method], psl->shadow_cube_copy_pass);
306                 DRW_shgroup_uniform_texture_ref(grp, "shadowTexture", &sldata->shadow_cube_target);
307                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
308                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
309                 DRW_shgroup_uniform_int(grp, "faceId", &linfo->current_shadow_face, 1);
310                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
311         }
312
313         {
314                 psl->shadow_cascade_copy_pass = DRW_pass_create("Shadow Cascade Copy Pass", DRW_STATE_WRITE_COLOR);
315
316                 DRWShadingGroup *grp = DRW_shgroup_create(
317                         e_data.shadow_copy_cascade_sh[linfo->shadow_method], psl->shadow_cascade_copy_pass);
318                 DRW_shgroup_uniform_texture_ref(grp, "shadowTexture", &sldata->shadow_cascade_target);
319                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
320                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
321                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
322                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
323         }
324
325         {
326                 DRWState state = DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS_EQUAL;
327                 psl->shadow_pass = DRW_pass_create("Shadow Pass", state);
328
329                 stl->g_data->shadow_shgrp = DRW_shgroup_create(e_data.shadow_sh, psl->shadow_pass);
330         }
331 }
332
333 void EEVEE_lights_cache_add(EEVEE_ViewLayerData *sldata, Object *ob)
334 {
335         EEVEE_LampsInfo *linfo = sldata->lamps;
336
337         const DRWContextState *draw_ctx = DRW_context_state_get();
338         const float threshold = draw_ctx->scene->eevee.light_threshold;
339
340         /* Step 1 find all lamps in the scene and setup them */
341         if (linfo->num_light >= MAX_LIGHT) {
342                 printf("Too many lights in the scene !!!\n");
343         }
344         else {
345                 Lamp *la = (Lamp *)ob->data;
346                 EEVEE_Light *evli = linfo->light_data + linfo->num_light;
347                 eevee_light_setup(ob, evli);
348
349                 /* We do not support shadowmaps for dupli lamps. */
350                 if ((ob->base_flag & BASE_FROM_DUPLI) != 0) {
351                         linfo->num_light++;
352                         return;
353                 }
354
355                 EEVEE_LampEngineData *led = EEVEE_lamp_data_ensure(ob);
356
357                 /* Save previous shadow id. */
358                 int prev_cube_sh_id = led->prev_cube_shadow_id;
359
360                 /* Default light without shadows */
361                 led->data.ld.shadow_id = -1;
362                 led->prev_cube_shadow_id = -1;
363
364                 if (la->mode & LA_SHADOW) {
365                         if (la->type == LA_SUN) {
366                                 int cascade_nbr = la->cascade_count;
367
368                                 if ((linfo->gpu_cascade_len + 1) <= MAX_SHADOW_CASCADE) {
369                                         /* Save Light object. */
370                                         linfo->shadow_cascade_ref[linfo->cpu_cascade_len] = ob;
371
372                                         /* Store indices. */
373                                         EEVEE_ShadowCascadeData *data = &led->data.scad;
374                                         data->shadow_id = linfo->gpu_shadow_len;
375                                         data->cascade_id = linfo->gpu_cascade_len;
376                                         data->layer_id = linfo->num_cascade_layer;
377
378                                         /* Increment indices. */
379                                         linfo->gpu_shadow_len += 1;
380                                         linfo->gpu_cascade_len += 1;
381                                         linfo->num_cascade_layer += cascade_nbr;
382
383                                         linfo->cpu_cascade_len += 1;
384                                 }
385                         }
386                         else if (la->type == LA_SPOT || la->type == LA_LOCAL || la->type == LA_AREA) {
387                                 if ((linfo->gpu_cube_len + 1) <= MAX_SHADOW_CUBE) {
388                                         /* Save Light object. */
389                                         linfo->shadow_cube_ref[linfo->cpu_cube_len] = ob;
390
391                                         /* For light update tracking. */
392                                         if ((prev_cube_sh_id >= 0) &&
393                                             (prev_cube_sh_id < linfo->shcaster_backbuffer->count))
394                                         {
395                                                 linfo->new_shadow_id[prev_cube_sh_id] = linfo->cpu_cube_len;
396                                         }
397                                         led->prev_cube_shadow_id = linfo->cpu_cube_len;
398
399                                         /* Saving lamp bounds for later. */
400                                         BLI_assert(linfo->cpu_cube_len >= 0 && linfo->cpu_cube_len < MAX_LIGHT);
401                                         copy_v3_v3(linfo->shadow_bounds[linfo->cpu_cube_len].center, ob->obmat[3]);
402                                         linfo->shadow_bounds[linfo->cpu_cube_len].radius = light_attenuation_radius_get(la, threshold);
403
404                                         EEVEE_ShadowCubeData *data = &led->data.scd;
405                                         /* Store indices. */
406                                         data->shadow_id = linfo->gpu_shadow_len;
407                                         data->cube_id = linfo->gpu_cube_len;
408                                         data->layer_id = linfo->num_cube_layer;
409
410                                         /* Increment indices. */
411                                         linfo->gpu_shadow_len += 1;
412                                         linfo->gpu_cube_len += 1;
413                                         linfo->num_cube_layer += 1;
414
415                                         linfo->cpu_cube_len += 1;
416                                 }
417                         }
418                 }
419
420                 led->data.ld.light_id = linfo->num_light;
421                 linfo->light_ref[linfo->num_light] = ob;
422                 linfo->num_light++;
423         }
424 }
425
426 /* Add a shadow caster to the shadowpasses */
427 void EEVEE_lights_cache_shcaster_add(
428         EEVEE_ViewLayerData *UNUSED(sldata), EEVEE_StorageList *stl, struct GPUBatch *geom, Object *ob)
429 {
430         DRW_shgroup_call_object_add(
431                 stl->g_data->shadow_shgrp,
432                 geom, ob);
433 }
434
435 void EEVEE_lights_cache_shcaster_material_add(
436         EEVEE_ViewLayerData *sldata, EEVEE_PassList *psl, struct GPUMaterial *gpumat,
437         struct GPUBatch *geom, struct Object *ob, float *alpha_threshold)
438 {
439         /* TODO / PERF : reuse the same shading group for objects with the same material */
440         DRWShadingGroup *grp = DRW_shgroup_material_create(gpumat, psl->shadow_pass);
441
442         if (grp == NULL) return;
443
444         /* Grrr needed for correctness but not 99% of the time not needed.
445          * TODO detect when needed? */
446         DRW_shgroup_uniform_block(grp, "probe_block", sldata->probe_ubo);
447         DRW_shgroup_uniform_block(grp, "grid_block", sldata->grid_ubo);
448         DRW_shgroup_uniform_block(grp, "planar_block", sldata->planar_ubo);
449         DRW_shgroup_uniform_block(grp, "light_block", sldata->light_ubo);
450         DRW_shgroup_uniform_block(grp, "shadow_block", sldata->shadow_ubo);
451         DRW_shgroup_uniform_block(grp, "common_block", sldata->common_ubo);
452
453         if (alpha_threshold != NULL) {
454                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
455         }
456
457         DRW_shgroup_call_object_add(grp, geom, ob);
458 }
459
460 /* Make that object update shadow casting lamps inside its influence bounding box. */
461 void EEVEE_lights_cache_shcaster_object_add(EEVEE_ViewLayerData *sldata, Object *ob)
462 {
463         if ((ob->base_flag & BASE_FROM_DUPLI) != 0) {
464                 /* TODO: Special case for dupli objects because we cannot save the object pointer. */
465                 return;
466         }
467
468         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_ensure(ob);
469         EEVEE_LampsInfo *linfo = sldata->lamps;
470         EEVEE_ShadowCasterBuffer *backbuffer = linfo->shcaster_backbuffer;
471         EEVEE_ShadowCasterBuffer *frontbuffer = linfo->shcaster_frontbuffer;
472         int past_id = oedata->shadow_caster_id;
473
474         /* Update flags in backbuffer. */
475         if (past_id > -1 && past_id < backbuffer->count) {
476                 backbuffer->flags[past_id] &= ~SHADOW_CASTER_PRUNED;
477
478                 if (oedata->need_update) {
479                         backbuffer->flags[past_id] |= SHADOW_CASTER_UPDATED;
480                 }
481         }
482
483         /* Update id. */
484         oedata->shadow_caster_id = frontbuffer->count++;
485
486         /* Make sure shadow_casters is big enough. */
487         if (oedata->shadow_caster_id >= frontbuffer->alloc_count) {
488                 frontbuffer->alloc_count += SHADOW_CASTER_ALLOC_CHUNK;
489                 frontbuffer->shadow_casters = MEM_reallocN(frontbuffer->shadow_casters, sizeof(EEVEE_ShadowCaster) * frontbuffer->alloc_count);
490                 frontbuffer->flags = MEM_reallocN(frontbuffer->flags, sizeof(EEVEE_ShadowCaster) * frontbuffer->alloc_count);
491         }
492
493         EEVEE_ShadowCaster *shcaster = frontbuffer->shadow_casters + oedata->shadow_caster_id;
494
495         if (oedata->need_update) {
496                 frontbuffer->flags[oedata->shadow_caster_id] = SHADOW_CASTER_UPDATED;
497         }
498
499         /* Update World AABB in frontbuffer. */
500         BoundBox *bb = BKE_object_boundbox_get(ob);
501         float min[3], max[3];
502         INIT_MINMAX(min, max);
503         for (int i = 0; i < 8; ++i) {
504                 float vec[3];
505                 copy_v3_v3(vec, bb->vec[i]);
506                 mul_m4_v3(ob->obmat, vec);
507                 minmax_v3v3_v3(min, max, vec);
508         }
509
510         EEVEE_BoundBox *aabb = &shcaster->bbox;
511         add_v3_v3v3(aabb->center, min, max);
512         mul_v3_fl(aabb->center, 0.5f);
513         sub_v3_v3v3(aabb->halfdim, aabb->center, max);
514
515         aabb->halfdim[0] = fabsf(aabb->halfdim[0]);
516         aabb->halfdim[1] = fabsf(aabb->halfdim[1]);
517         aabb->halfdim[2] = fabsf(aabb->halfdim[2]);
518
519         oedata->need_update = false;
520 }
521
522 void EEVEE_lights_cache_finish(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
523 {
524         EEVEE_LampsInfo *linfo = sldata->lamps;
525         eGPUTextureFormat shadow_pool_format = GPU_R32F;
526
527         sldata->common_data.la_num_light = linfo->num_light;
528
529         /* Setup enough layers. */
530         /* Free textures if number mismatch. */
531         if (linfo->num_cube_layer != linfo->cache_num_cube_layer) {
532                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_pool);
533                 linfo->cache_num_cube_layer = linfo->num_cube_layer;
534                 linfo->update_flag |= LIGHT_UPDATE_SHADOW_CUBE;
535         }
536
537         if (linfo->num_cascade_layer != linfo->cache_num_cascade_layer) {
538                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_pool);
539                 linfo->cache_num_cascade_layer = linfo->num_cascade_layer;
540         }
541
542         switch (linfo->shadow_method) {
543                 case SHADOW_ESM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? GPU_R32F : GPU_R16F); break;
544                 case SHADOW_VSM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? GPU_RG32F : GPU_RG16F); break;
545                 default:
546                         BLI_assert(!"Incorrect Shadow Method");
547                         break;
548         }
549
550         /* Cubemaps */
551         if (!sldata->shadow_cube_target) {
552                 sldata->shadow_cube_target = DRW_texture_create_cube(
553                         linfo->shadow_cube_size, GPU_DEPTH_COMPONENT24, 0, NULL);
554                 sldata->shadow_cube_blur = DRW_texture_create_cube(
555                         linfo->shadow_cube_size, shadow_pool_format, DRW_TEX_FILTER, NULL);
556         }
557         if (!sldata->shadow_cube_pool) {
558                 sldata->shadow_cube_pool = DRW_texture_create_2D_array(
559                         linfo->shadow_cube_store_size, linfo->shadow_cube_store_size, max_ii(1, linfo->num_cube_layer),
560                         shadow_pool_format, DRW_TEX_FILTER, NULL);
561         }
562         GPU_framebuffer_ensure_config(&sldata->shadow_cube_target_fb, {
563                 GPU_ATTACHMENT_TEXTURE(sldata->shadow_cube_target)
564         });
565         GPU_framebuffer_ensure_config(&sldata->shadow_cube_store_fb, {
566                 GPU_ATTACHMENT_NONE,
567                 GPU_ATTACHMENT_TEXTURE(sldata->shadow_cube_pool)
568         });
569
570         /* CSM */
571         if (!sldata->shadow_cascade_target) {
572                 sldata->shadow_cascade_target = DRW_texture_create_2D_array(
573                         linfo->shadow_cascade_size, linfo->shadow_cascade_size, MAX_CASCADE_NUM, GPU_DEPTH_COMPONENT24, 0, NULL);
574                 sldata->shadow_cascade_blur = DRW_texture_create_2D_array(
575                         linfo->shadow_cascade_size, linfo->shadow_cascade_size, MAX_CASCADE_NUM, shadow_pool_format, DRW_TEX_FILTER, NULL);
576         }
577         if (!sldata->shadow_cascade_pool) {
578                 sldata->shadow_cascade_pool = DRW_texture_create_2D_array(
579                         linfo->shadow_cascade_size, linfo->shadow_cascade_size, max_ii(1, linfo->num_cascade_layer),
580                         shadow_pool_format, DRW_TEX_FILTER, NULL);
581         }
582         GPU_framebuffer_ensure_config(&sldata->shadow_cascade_target_fb, {
583                 GPU_ATTACHMENT_TEXTURE(sldata->shadow_cascade_target)
584         });
585         GPU_framebuffer_ensure_config(&sldata->shadow_cascade_store_fb, {
586                 GPU_ATTACHMENT_NONE,
587                 GPU_ATTACHMENT_TEXTURE(sldata->shadow_cascade_pool)
588         });
589
590         /* Update Lamps UBOs. */
591         EEVEE_lights_update(sldata, vedata);
592 }
593
594 float light_attenuation_radius_get(Lamp *la, float light_threshold)
595 {
596         if (la->mode & LA_CUSTOM_ATTENUATION) {
597                 return la->att_dist;
598         }
599
600         /* Compute max light power. */
601         float power = max_fff(la->r, la->g, la->b);
602         power *= fabsf(la->energy);
603         power *= max_ff(1.0f, la->spec_fac);
604         /* Compute the distance (using the inverse square law)
605          * at which the light power reaches the light_threshold. */
606         float distance = sqrtf(max_ff(1e-16, power / max_ff(1e-16, light_threshold)));
607         return distance;
608 }
609
610 static void light_shape_parameters_set(EEVEE_Light *evli, const Lamp *la, float scale[3])
611 {
612         if (la->type == LA_SPOT) {
613                 /* Spot size & blend */
614                 evli->sizex = scale[0] / scale[2];
615                 evli->sizey = scale[1] / scale[2];
616                 evli->spotsize = cosf(la->spotsize * 0.5f);
617                 evli->spotblend = (1.0f - evli->spotsize) * la->spotblend;
618                 evli->radius = max_ff(0.001f, la->area_size);
619         }
620         else if (la->type == LA_AREA) {
621                 evli->sizex = max_ff(0.003f, la->area_size * scale[0] * 0.5f);
622                 if (ELEM(la->area_shape, LA_AREA_RECT, LA_AREA_ELLIPSE)) {
623                         evli->sizey = max_ff(0.003f, la->area_sizey * scale[1] * 0.5f);
624                 }
625                 else {
626                         evli->sizey = max_ff(0.003f, la->area_size * scale[1] * 0.5f);
627                 }
628         }
629         else {
630                 evli->radius = max_ff(0.001f, la->area_size);
631         }
632 }
633
634 static float light_shape_power_get(const Lamp *la, const EEVEE_Light *evli)
635 {
636         float power;
637         /* Make illumination power constant */
638         if (la->type == LA_AREA) {
639                 power = 1.0f / (evli->sizex * evli->sizey * 4.0f * M_PI) * /* 1/(w*h*Pi) */
640                         80.0f; /* XXX : Empirical, Fit cycles power */
641                 if (ELEM(la->area_shape, LA_AREA_DISK, LA_AREA_ELLIPSE)) {
642                         /* Scale power to account for the lower area of the ellipse compared to the surrounding rectangle. */
643                         power *= 4.0f / M_PI;
644                 }
645         }
646         else if (la->type == LA_SPOT || la->type == LA_LOCAL) {
647                 power = 1.0f / (4.0f * evli->radius * evli->radius * M_PI * M_PI) * /* 1/(4*r²*Pi²) */
648                         M_PI * M_PI * 10.0; /* XXX : Empirical, Fit cycles power */
649
650                 /* for point lights (a.k.a radius == 0.0) */
651                 // power = M_PI * M_PI * 0.78; /* XXX : Empirical, Fit cycles power */
652         }
653         else {
654                 power = 1.0f / (evli->radius * evli->radius * M_PI); /* 1/(r²*Pi) */
655                 /* Make illumation power closer to cycles for bigger radii. Cycles uses a cos^3 term that we cannot reproduce
656                  * so we account for that by scaling the light power. This function is the result of a rough manual fitting. */
657                 power += 1.0f / (2.0f * M_PI); /* power *= 1 + r²/2 */
658         }
659         return power;
660 }
661
662 /* Update buffer with lamp data */
663 static void eevee_light_setup(Object *ob, EEVEE_Light *evli)
664 {
665         Lamp *la = (Lamp *)ob->data;
666         float mat[4][4], scale[3], power, att_radius;
667
668         const DRWContextState *draw_ctx = DRW_context_state_get();
669         const float light_threshold = draw_ctx->scene->eevee.light_threshold;
670
671         /* Position */
672         copy_v3_v3(evli->position, ob->obmat[3]);
673
674         /* Color */
675         copy_v3_v3(evli->color, &la->r);
676
677         evli->spec = la->spec_fac;
678
679         /* Influence Radius */
680         att_radius = light_attenuation_radius_get(la, light_threshold);
681         /* Take the inverse square of this distance. */
682         evli->invsqrdist = 1.0 / max_ff(1e-4f, att_radius * att_radius);
683
684         /* Vectors */
685         normalize_m4_m4_ex(mat, ob->obmat, scale);
686         copy_v3_v3(evli->forwardvec, mat[2]);
687         normalize_v3(evli->forwardvec);
688         negate_v3(evli->forwardvec);
689
690         copy_v3_v3(evli->rightvec, mat[0]);
691         normalize_v3(evli->rightvec);
692
693         copy_v3_v3(evli->upvec, mat[1]);
694         normalize_v3(evli->upvec);
695
696         light_shape_parameters_set(evli, la, scale);
697
698         /* Lamp Type */
699         evli->lamptype = (float)la->type;
700         if ((la->type == LA_AREA) && ELEM(la->area_shape, LA_AREA_DISK, LA_AREA_ELLIPSE)) {
701                 evli->lamptype = LAMPTYPE_AREA_ELLIPSE;
702         }
703
704         power = light_shape_power_get(la, evli);
705         mul_v3_fl(evli->color, power * la->energy);
706
707         /* No shadow by default */
708         evli->shadowid = -1.0f;
709 }
710
711 /**
712  * Special ball distribution:
713  * Point are distributed in a way that when they are orthogonaly
714  * projected into any plane, the resulting distribution is (close to)
715  * a uniform disc distribution.
716  **/
717 static void sample_ball(int sample_ofs, float radius, float rsample[3])
718 {
719         double ht_point[3];
720         double ht_offset[3] = {0.0, 0.0, 0.0};
721         uint ht_primes[3] = {2, 3, 7};
722
723         BLI_halton_3D(ht_primes, ht_offset, sample_ofs, ht_point);
724
725         float omega = ht_point[1] * 2.0f * M_PI;
726
727         rsample[2] = ht_point[0] * 2.0f - 1.0f; /* cos theta */
728
729         float r = sqrtf(fmaxf(0.0f, 1.0f - rsample[2] * rsample[2])); /* sin theta */
730
731         rsample[0] = r * cosf(omega);
732         rsample[1] = r * sinf(omega);
733
734         radius *= sqrt(sqrt(ht_point[2]));
735         mul_v3_fl(rsample, radius);
736 }
737
738 static void sample_rectangle(
739         int sample_ofs, float x_axis[3], float y_axis[3], float size_x, float size_y,
740         float rsample[3])
741 {
742         double ht_point[2];
743         double ht_offset[2] = {0.0, 0.0};
744         uint ht_primes[2] = {2, 3};
745
746         BLI_halton_2D(ht_primes, ht_offset, sample_ofs, ht_point);
747
748         /* Change ditribution center to be 0,0 */
749         ht_point[0] = (ht_point[0] > 0.5f) ? ht_point[0] - 1.0f : ht_point[0];
750         ht_point[1] = (ht_point[1] > 0.5f) ? ht_point[1] - 1.0f : ht_point[1];
751
752         zero_v3(rsample);
753         madd_v3_v3fl(rsample, x_axis, (ht_point[0] * 2.0f) * size_x);
754         madd_v3_v3fl(rsample, y_axis, (ht_point[1] * 2.0f) * size_y);
755 }
756
757 static void sample_ellipse(
758         int sample_ofs, float x_axis[3], float y_axis[3], float size_x, float size_y,
759         float rsample[3])
760 {
761         double ht_point[2];
762         double ht_offset[2] = {0.0, 0.0};
763         uint ht_primes[2] = {2, 3};
764
765         BLI_halton_2D(ht_primes, ht_offset, sample_ofs, ht_point);
766
767         /* Uniform disc sampling. */
768         float omega = ht_point[1] * 2.0f * M_PI;
769         float r = sqrtf(ht_point[0]);
770         ht_point[0] = r * cosf(omega) * size_x;
771         ht_point[1] = r * sinf(omega) * size_y;
772
773         zero_v3(rsample);
774         madd_v3_v3fl(rsample, x_axis, ht_point[0]);
775         madd_v3_v3fl(rsample, y_axis, ht_point[1]);
776 }
777
778
779 static void shadow_cube_random_position_set(
780         EEVEE_Light *evli, Lamp *la,
781         int sample_ofs,
782         float ws_sample_pos[3])
783 {
784         float jitter[3];
785
786 #ifndef DEBUG_SHADOW_DISTRIBUTION
787         int i = sample_ofs;
788 #else
789         for (int i = 0; i <= sample_ofs; ++i) {
790 #endif
791                 switch (la->type) {
792                         case LA_AREA:
793                                 if (ELEM(la->area_shape, LA_AREA_RECT, LA_AREA_SQUARE)) {
794                                         sample_rectangle(i, evli->rightvec, evli->upvec, evli->sizex, evli->sizey, jitter);
795                                 }
796                                 else {
797                                         sample_ellipse(i, evli->rightvec, evli->upvec, evli->sizex, evli->sizey, jitter);
798                                 }
799                                 break;
800                         default:
801                                 sample_ball(i, evli->radius, jitter);
802                 }
803 #ifdef DEBUG_SHADOW_DISTRIBUTION
804                 float p[3];
805                 add_v3_v3v3(p, jitter, ws_sample_pos);
806                 DRW_debug_sphere(p, 0.01f, (float[4]){1.0f, (sample_ofs == i) ? 1.0f : 0.0f, 0.0f, 1.0f});
807         }
808 #endif
809         add_v3_v3(ws_sample_pos, jitter);
810 }
811
812 static void eevee_shadow_cube_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led, int sample_ofs)
813 {
814         EEVEE_ShadowCubeData *sh_data = &led->data.scd;
815         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
816         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
817         EEVEE_ShadowCube *cube_data = linfo->shadow_cube_data + sh_data->cube_id;
818         Lamp *la = (Lamp *)ob->data;
819
820         copy_v3_v3(cube_data->position, ob->obmat[3]);
821
822         if (linfo->soft_shadows) {
823                 shadow_cube_random_position_set(evli, la, sample_ofs, cube_data->position);
824         }
825
826         ubo_data->bias = 0.05f * la->bias;
827         ubo_data->near = la->clipsta;
828         ubo_data->far = 1.0f / (evli->invsqrdist * evli->invsqrdist);
829         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
830
831         evli->shadowid = (float)(sh_data->shadow_id);
832         ubo_data->shadow_start = (float)(sh_data->layer_id);
833         ubo_data->data_start = (float)(sh_data->cube_id);
834         ubo_data->shadow_blur = la->soft * 0.02f; /* Used by translucence shadowmap blur */
835
836         ubo_data->contact_dist = (la->mode & LA_SHAD_CONTACT) ? la->contact_dist : 0.0f;
837         ubo_data->contact_bias = 0.05f * la->contact_bias;
838         ubo_data->contact_spread = la->contact_spread;
839         ubo_data->contact_thickness = la->contact_thickness;
840 }
841
842 static void shadow_cascade_random_matrix_set(float mat[4][4], float radius, int sample_ofs)
843 {
844         float jitter[3];
845
846 #ifndef DEBUG_SHADOW_DISTRIBUTION
847         int i = sample_ofs;
848 #else
849         for (int i = 0; i <= sample_ofs; ++i) {
850 #endif
851                 sample_ellipse(i, mat[0], mat[1], radius, radius, jitter);
852 #ifdef DEBUG_SHADOW_DISTRIBUTION
853                 float p[3];
854                 add_v3_v3v3(p, jitter, mat[2]);
855                 DRW_debug_sphere(p, 0.01f, (float[4]){1.0f, (sample_ofs == i) ? 1.0f : 0.0f, 0.0f, 1.0f});
856         }
857 #endif
858
859         add_v3_v3(mat[2], jitter);
860         orthogonalize_m4(mat, 2);
861 }
862
863 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
864
865 static double round_to_digits(double value, int digits)
866 {
867         double factor = pow(10.0, digits - ceil(log10(fabs(value))));
868         return round(value * factor) / factor;
869 }
870
871 static void frustum_min_bounding_sphere(const float corners[8][3], float r_center[3], float *r_radius)
872 {
873 #if 0 /* Simple solution but waste too much space. */
874         float minvec[3], maxvec[3];
875
876         /* compute the bounding box */
877         INIT_MINMAX(minvec, maxvec);
878         for (int i = 0; i < 8; ++i) {
879                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
880         }
881
882         /* compute the bounding sphere of this box */
883         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
884         add_v3_v3v3(r_center, minvec, maxvec);
885         mul_v3_fl(r_center, 0.5f);
886 #else
887         /* Find averaged center. */
888         zero_v3(r_center);
889         for (int i = 0; i < 8; ++i) {
890                 add_v3_v3(r_center, corners[i]);
891         }
892         mul_v3_fl(r_center, 1.0f / 8.0f);
893
894         /* Search the largest distance from the sphere center. */
895         *r_radius = 0.0f;
896         for (int i = 0; i < 8; ++i) {
897                 float rad = len_squared_v3v3(corners[i], r_center);
898                 if (rad > *r_radius) {
899                         *r_radius = rad;
900                 }
901         }
902
903         /* TODO try to reduce the radius further by moving the center.
904          * Remember we need a __stable__ solution! */
905
906         /* Try to reduce float imprecision leading to shimmering. */
907         *r_radius = (float)round_to_digits(sqrtf(*r_radius), 3);
908 #endif
909 }
910
911 static void eevee_shadow_cascade_setup(
912         Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led,
913         DRWMatrixState *saved_mats, float view_near, float view_far, int sample_ofs)
914 {
915         Lamp *la = (Lamp *)ob->data;
916
917         /* Camera Matrices */
918         float (*persinv)[4] = saved_mats->mat[DRW_MAT_PERSINV];
919         float (*vp_projmat)[4] = saved_mats->mat[DRW_MAT_WIN];
920         bool is_persp = DRW_viewport_is_persp_get();
921
922         /* Lamps Matrices */
923         int cascade_nbr = la->cascade_count;
924
925         EEVEE_ShadowCascadeData *sh_data = &led->data.scad;
926         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
927         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
928         EEVEE_ShadowCascade *cascade_data = linfo->shadow_cascade_data + sh_data->cascade_id;
929
930         /* obmat = Object Space > World Space */
931         /* viewmat = World Space > View Space */
932         float (*viewmat)[4] = sh_data->viewmat;
933 #if 0 /* done at culling time */
934         normalize_m4_m4(viewmat, ob->obmat);
935 #endif
936
937         if (linfo->soft_shadows) {
938                 shadow_cascade_random_matrix_set(viewmat, evli->radius, sample_ofs);
939         }
940
941         copy_m4_m4(sh_data->viewinv, viewmat);
942         invert_m4(viewmat);
943
944         /* The technique consists into splitting
945          * the view frustum into several sub-frustum
946          * that are individually receiving one shadow map */
947
948         float csm_start, csm_end;
949
950         if (is_persp) {
951                 csm_start = view_near;
952                 csm_end = max_ff(view_far, -la->cascade_max_dist);
953                 /* Avoid artifacts */
954                 csm_end = min_ff(view_near, csm_end);
955         }
956         else {
957                 csm_start = -view_far;
958                 csm_end = view_far;
959         }
960
961         /* init near/far */
962         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
963                 cascade_data->split_start[c] = csm_end;
964                 cascade_data->split_end[c] = csm_end;
965         }
966
967         /* Compute split planes */
968         float splits_start_ndc[MAX_CASCADE_NUM];
969         float splits_end_ndc[MAX_CASCADE_NUM];
970
971         {
972                 /* Nearest plane */
973                 float p[4] = {1.0f, 1.0f, csm_start, 1.0f};
974                 /* TODO: we don't need full m4 multiply here */
975                 mul_m4_v4(vp_projmat, p);
976                 splits_start_ndc[0] = p[2];
977                 if (is_persp) {
978                         splits_start_ndc[0] /= p[3];
979                 }
980         }
981
982         {
983                 /* Farthest plane */
984                 float p[4] = {1.0f, 1.0f, csm_end, 1.0f};
985                 /* TODO: we don't need full m4 multiply here */
986                 mul_m4_v4(vp_projmat, p);
987                 splits_end_ndc[cascade_nbr - 1] = p[2];
988                 if (is_persp) {
989                         splits_end_ndc[cascade_nbr - 1] /= p[3];
990                 }
991         }
992
993         cascade_data->split_start[0] = csm_start;
994         cascade_data->split_end[cascade_nbr - 1] = csm_end;
995
996         for (int c = 1; c < cascade_nbr; ++c) {
997                 /* View Space */
998                 float linear_split = LERP(((float)(c) / (float)cascade_nbr), csm_start, csm_end);
999                 float exp_split = csm_start * powf(csm_end / csm_start, (float)(c) / (float)cascade_nbr);
1000
1001                 if (is_persp) {
1002                         cascade_data->split_start[c] = LERP(la->cascade_exponent, linear_split, exp_split);
1003                 }
1004                 else {
1005                         cascade_data->split_start[c] = linear_split;
1006                 }
1007                 cascade_data->split_end[c - 1] = cascade_data->split_start[c];
1008
1009                 /* Add some overlap for smooth transition */
1010                 cascade_data->split_start[c] = LERP(la->cascade_fade, cascade_data->split_end[c - 1],
1011                                                     (c > 1) ? cascade_data->split_end[c - 2] : cascade_data->split_start[0]);
1012
1013                 /* NDC Space */
1014                 {
1015                         float p[4] = {1.0f, 1.0f, cascade_data->split_start[c], 1.0f};
1016                         /* TODO: we don't need full m4 multiply here */
1017                         mul_m4_v4(vp_projmat, p);
1018                         splits_start_ndc[c] = p[2];
1019
1020                         if (is_persp) {
1021                                 splits_start_ndc[c] /= p[3];
1022                         }
1023                 }
1024
1025                 {
1026                         float p[4] = {1.0f, 1.0f, cascade_data->split_end[c - 1], 1.0f};
1027                         /* TODO: we don't need full m4 multiply here */
1028                         mul_m4_v4(vp_projmat, p);
1029                         splits_end_ndc[c - 1] = p[2];
1030
1031                         if (is_persp) {
1032                                 splits_end_ndc[c - 1] /= p[3];
1033                         }
1034                 }
1035         }
1036
1037         /* Set last cascade split fade distance into the first split_start. */
1038         float prev_split = (cascade_nbr > 1) ? cascade_data->split_end[cascade_nbr - 2] : cascade_data->split_start[0];
1039         cascade_data->split_start[0] = LERP(la->cascade_fade, cascade_data->split_end[cascade_nbr - 1], prev_split);
1040
1041         /* For each cascade */
1042         for (int c = 0; c < cascade_nbr; ++c) {
1043                 float (*projmat)[4] = sh_data->projmat[c];
1044                 /* Given 8 frustum corners */
1045                 float corners[8][3] = {
1046                         /* Near Cap */
1047                         { 1.0f, -1.0f, splits_start_ndc[c]},
1048                         {-1.0f, -1.0f, splits_start_ndc[c]},
1049                         {-1.0f,  1.0f, splits_start_ndc[c]},
1050                         { 1.0f,  1.0f, splits_start_ndc[c]},
1051                         /* Far Cap */
1052                         { 1.0f, -1.0f, splits_end_ndc[c]},
1053                         {-1.0f, -1.0f, splits_end_ndc[c]},
1054                         {-1.0f,  1.0f, splits_end_ndc[c]},
1055                         { 1.0f,  1.0f, splits_end_ndc[c]},
1056                 };
1057
1058                 /* Transform them into world space */
1059                 for (int i = 0; i < 8; ++i) {
1060                         mul_project_m4_v3(persinv, corners[i]);
1061                 }
1062
1063                 float center[3];
1064                 frustum_min_bounding_sphere(corners, center, &(sh_data->radius[c]));
1065
1066 #ifdef DEBUG_CSM
1067                 float dbg_col[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1068                 if (c < 3) {
1069                         dbg_col[c] = 1.0f;
1070                 }
1071                 DRW_debug_bbox((BoundBox *)&corners, dbg_col);
1072                 DRW_debug_sphere(center, sh_data->radius[c], dbg_col);
1073 #endif
1074
1075                 /* Project into lightspace */
1076                 mul_m4_v3(viewmat, center);
1077
1078                 /* Snap projection center to nearest texel to cancel shimmering. */
1079                 float shadow_origin[2], shadow_texco[2];
1080                 /* Light to texture space. */
1081                 mul_v2_v2fl(shadow_origin, center, linfo->shadow_cascade_size / (2.0f * sh_data->radius[c]));
1082
1083                 /* Find the nearest texel. */
1084                 shadow_texco[0] = roundf(shadow_origin[0]);
1085                 shadow_texco[1] = roundf(shadow_origin[1]);
1086
1087                 /* Compute offset. */
1088                 sub_v2_v2(shadow_texco, shadow_origin);
1089                 mul_v2_fl(shadow_texco, (2.0f * sh_data->radius[c]) / linfo->shadow_cascade_size); /* Texture to light space. */
1090
1091                 /* Apply offset. */
1092                 add_v2_v2(center, shadow_texco);
1093
1094                 /* Expand the projection to cover frustum range */
1095                 rctf rect_cascade;
1096                 BLI_rctf_init_pt_radius(&rect_cascade, center, sh_data->radius[c]);
1097                 orthographic_m4(projmat,
1098                                 rect_cascade.xmin, rect_cascade.xmax,
1099                                 rect_cascade.ymin, rect_cascade.ymax,
1100                                 la->clipsta, la->clipend);
1101
1102                 mul_m4_m4m4(sh_data->viewprojmat[c], projmat, viewmat);
1103                 mul_m4_m4m4(cascade_data->shadowmat[c], texcomat, sh_data->viewprojmat[c]);
1104
1105 #ifdef DEBUG_CSM
1106                 DRW_debug_m4_as_bbox(sh_data->viewprojmat[c], dbg_col, true);
1107 #endif
1108         }
1109
1110         ubo_data->bias = 0.05f * la->bias;
1111         ubo_data->near = la->clipsta;
1112         ubo_data->far = la->clipend;
1113         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
1114
1115         evli->shadowid = (float)(sh_data->shadow_id);
1116         ubo_data->shadow_start = (float)(sh_data->layer_id);
1117         ubo_data->data_start = (float)(sh_data->cascade_id);
1118         ubo_data->shadow_blur = la->soft * 0.02f; /* Used by translucence shadowmap blur */
1119
1120         ubo_data->contact_dist = (la->mode & LA_SHAD_CONTACT) ? la->contact_dist : 0.0f;
1121         ubo_data->contact_bias = 0.05f * la->contact_bias;
1122         ubo_data->contact_spread = la->contact_spread;
1123         ubo_data->contact_thickness = la->contact_thickness;
1124 }
1125
1126 /* Used for checking if object is inside the shadow volume. */
1127 static bool sphere_bbox_intersect(const EEVEE_BoundSphere *bs, const EEVEE_BoundBox *bb)
1128 {
1129         /* We are testing using a rougher AABB vs AABB test instead of full AABB vs Sphere. */
1130         /* TODO test speed with AABB vs Sphere. */
1131         bool x = fabsf(bb->center[0] - bs->center[0]) <= (bb->halfdim[0] + bs->radius);
1132         bool y = fabsf(bb->center[1] - bs->center[1]) <= (bb->halfdim[1] + bs->radius);
1133         bool z = fabsf(bb->center[2] - bs->center[2]) <= (bb->halfdim[2] + bs->radius);
1134
1135         return x && y && z;
1136 }
1137
1138 void EEVEE_lights_update(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
1139 {
1140         EEVEE_StorageList *stl = vedata->stl;
1141         EEVEE_EffectsInfo *effects = stl->effects;
1142         EEVEE_LampsInfo *linfo = sldata->lamps;
1143         Object *ob;
1144         int i;
1145         char *flag;
1146         EEVEE_ShadowCaster *shcaster;
1147         EEVEE_BoundSphere *bsphere;
1148         EEVEE_ShadowCasterBuffer *frontbuffer = linfo->shcaster_frontbuffer;
1149         EEVEE_ShadowCasterBuffer *backbuffer = linfo->shcaster_backbuffer;
1150
1151         EEVEE_LightBits update_bits = {{0}};
1152         if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
1153                 /* Update all lights. */
1154                 lightbits_set_all(&update_bits, true);
1155         }
1156         else {
1157                 /* Search for deleted shadow casters and if shcaster WAS in shadow radius. */
1158                 /* No need to run this if we already update all lamps. */
1159                 EEVEE_LightBits past_bits = {{0}};
1160                 EEVEE_LightBits curr_bits = {{0}};
1161                 shcaster = backbuffer->shadow_casters;
1162                 flag = backbuffer->flags;
1163                 for (i = 0; i < backbuffer->count; ++i, ++flag, ++shcaster) {
1164                         /* If the shadowcaster has been deleted or updated. */
1165                         if (*flag != 0) {
1166                                 /* Add the lamps that were intersecting with its BBox. */
1167                                 lightbits_or(&past_bits, &shcaster->bits);
1168                         }
1169                 }
1170                 /* Convert old bits to new bits and add result to final update bits. */
1171                 /* NOTE: This might be overkill since all lights are tagged to refresh if
1172                  * the light count changes. */
1173                 lightbits_convert(&curr_bits, &past_bits, linfo->new_shadow_id, MAX_LIGHT);
1174                 lightbits_or(&update_bits, &curr_bits);
1175         }
1176
1177         /* Search for updates in current shadow casters. */
1178         shcaster = frontbuffer->shadow_casters;
1179         flag = frontbuffer->flags;
1180         for (i = 0; i < frontbuffer->count; i++, flag++, shcaster++) {
1181                 /* Run intersection checks to fill the bitfields. */
1182                 bsphere = linfo->shadow_bounds;
1183                 for (int j = 0; j < linfo->cpu_cube_len; j++, bsphere++) {
1184                         bool iter = sphere_bbox_intersect(bsphere, &shcaster->bbox);
1185                         lightbits_set_single(&shcaster->bits, j, iter);
1186                 }
1187                 /* Only add to final bits if objects has been updated. */
1188                 if (*flag != 0) {
1189                         lightbits_or(&update_bits, &shcaster->bits);
1190                 }
1191         }
1192
1193         /* Setup shadow cube in UBO and tag for update if necessary. */
1194         for (i = 0; (i < MAX_SHADOW_CUBE) && (ob = linfo->shadow_cube_ref[i]); i++) {
1195                 EEVEE_LampEngineData *led = EEVEE_lamp_data_ensure(ob);
1196
1197                 eevee_shadow_cube_setup(ob, linfo, led, effects->taa_current_sample - 1);
1198                 if (lightbits_get(&update_bits, i) != 0 || linfo->soft_shadows) {
1199                         led->need_update = true;
1200                 }
1201         }
1202
1203         /* Resize shcasters buffers if too big. */
1204         if (frontbuffer->alloc_count - frontbuffer->count > SHADOW_CASTER_ALLOC_CHUNK) {
1205                 frontbuffer->alloc_count  = (frontbuffer->count / SHADOW_CASTER_ALLOC_CHUNK) * SHADOW_CASTER_ALLOC_CHUNK;
1206                 frontbuffer->alloc_count += (frontbuffer->count % SHADOW_CASTER_ALLOC_CHUNK != 0) ? SHADOW_CASTER_ALLOC_CHUNK : 0;
1207                 frontbuffer->shadow_casters = MEM_reallocN(frontbuffer->shadow_casters, sizeof(EEVEE_ShadowCaster) * frontbuffer->alloc_count);
1208                 frontbuffer->flags = MEM_reallocN(frontbuffer->flags, sizeof(EEVEE_ShadowCaster) * frontbuffer->alloc_count);
1209         }
1210 }
1211
1212 /* this refresh lamps shadow buffers */
1213 void EEVEE_draw_shadows(EEVEE_ViewLayerData *sldata, EEVEE_Data *vedata)
1214 {
1215         EEVEE_PassList *psl = vedata->psl;
1216         EEVEE_StorageList *stl = vedata->stl;
1217         EEVEE_EffectsInfo *effects = stl->effects;
1218         EEVEE_LampsInfo *linfo = sldata->lamps;
1219         const DRWContextState *draw_ctx = DRW_context_state_get();
1220         const float light_threshold = draw_ctx->scene->eevee.light_threshold;
1221         Object *ob;
1222         int i;
1223
1224         DRWMatrixState saved_mats;
1225         int saved_ray_type = sldata->common_data.ray_type;
1226
1227         /* TODO: make it optionnal if we don't draw shadows. */
1228         sldata->common_data.ray_type = EEVEE_RAY_SHADOW;
1229         DRW_uniformbuffer_update(sldata->common_ubo, &sldata->common_data);
1230
1231         /* Precompute all shadow/view test before rendering and trashing the culling cache. */
1232         bool cube_visible[MAX_SHADOW_CUBE];
1233         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
1234                 Lamp *la = (Lamp *)ob->data;
1235                 BoundSphere bsphere = {
1236                         .center = {ob->obmat[3][0], ob->obmat[3][1], ob->obmat[3][2]},
1237                         .radius = light_attenuation_radius_get(la, light_threshold),
1238                 };
1239                 cube_visible[i] = DRW_culling_sphere_test(&bsphere);
1240         }
1241         bool cascade_visible[MAX_SHADOW_CASCADE];
1242         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
1243                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
1244                 EEVEE_ShadowCascadeData *sh_data = &led->data.scad;
1245                 float plane[4];
1246                 normalize_m4_m4(sh_data->viewmat, ob->obmat);
1247
1248                 plane_from_point_normal_v3(plane, sh_data->viewmat[3], sh_data->viewmat[2]);
1249                 /* TODO: check against near/far instead of "local Z = 0" plane.
1250                  * Or even the cascades AABB. */
1251                 cascade_visible[i] = DRW_culling_plane_test(plane);
1252         }
1253
1254         /* We need to save the Matrices before overidding them */
1255         DRW_viewport_matrix_get_all(&saved_mats);
1256
1257         /* Cube Shadow Maps */
1258         DRW_stats_group_start("Cube Shadow Maps");
1259         /* Render each shadow to one layer of the array */
1260         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
1261                 EEVEE_LampEngineData *led = EEVEE_lamp_data_ensure(ob);
1262                 Lamp *la = (Lamp *)ob->data;
1263
1264                 if (!led->need_update || !cube_visible[i]) {
1265                         continue;
1266                 }
1267
1268                 DRWMatrixState render_mats;
1269                 float (*winmat)[4] = render_mats.mat[DRW_MAT_WIN];
1270                 float (*viewmat)[4] = render_mats.mat[DRW_MAT_VIEW];
1271                 float (*persmat)[4] = render_mats.mat[DRW_MAT_PERS];
1272
1273                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
1274                 EEVEE_ShadowCubeData *evscd = &led->data.scd;
1275                 EEVEE_ShadowCube *cube_data = linfo->shadow_cube_data + evscd->cube_id;
1276
1277                 srd->clip_near = la->clipsta;
1278                 srd->clip_far = light_attenuation_radius_get(la, light_threshold);
1279                 srd->stored_texel_size = 1.0 / (float)linfo->shadow_cube_store_size;
1280                 srd->exponent = la->bleedexp;
1281                 copy_v3_v3(srd->position, cube_data->position);
1282
1283                 perspective_m4(winmat, -srd->clip_near, srd->clip_near, -srd->clip_near, srd->clip_near, srd->clip_near, srd->clip_far);
1284
1285                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
1286
1287                 /* Render shadow cube */
1288                 /* Render 6 faces separately: seems to be faster for the general case.
1289                  * The only time it's more beneficial is when the CPU culling overhead
1290                  * outweigh the instancing overhead. which is rarely the case. */
1291                 for (int j = 0; j < 6; j++) {
1292                         /* TODO optimize */
1293                         float tmp[4][4];
1294                         unit_m4(tmp);
1295                         negate_v3_v3(tmp[3], srd->position);
1296                         mul_m4_m4m4(viewmat, cubefacemat[j], tmp);
1297                         mul_m4_m4m4(persmat, winmat, viewmat);
1298                         invert_m4_m4(render_mats.mat[DRW_MAT_WININV], winmat);
1299                         invert_m4_m4(render_mats.mat[DRW_MAT_VIEWINV], viewmat);
1300                         invert_m4_m4(render_mats.mat[DRW_MAT_PERSINV], persmat);
1301
1302                         DRW_viewport_matrix_override_set_all(&render_mats);
1303
1304                         GPU_framebuffer_texture_cubeface_attach(sldata->shadow_cube_target_fb,
1305                                                                 sldata->shadow_cube_target, 0, j, 0);
1306                         GPU_framebuffer_bind(sldata->shadow_cube_target_fb);
1307                         GPU_framebuffer_clear_depth(sldata->shadow_cube_target_fb, 1.0f);
1308                         DRW_draw_pass(psl->shadow_pass);
1309                 }
1310
1311                 /* 0.001f is arbitrary, but it should be relatively small so that filter size is not too big. */
1312                 float filter_texture_size = la->soft * 0.001f;
1313                 float filter_pixel_size = ceil(filter_texture_size / srd->cube_texel_size);
1314                 linfo->filter_size = srd->cube_texel_size * ((filter_pixel_size > 1.0f) ? 1.5f : 0.0f);
1315
1316                 /* TODO: OPTI: Filter all faces in one/two draw call */
1317                 /* TODO: OPTI: Don't do this intermediate step if no filter is needed. */
1318                 for (linfo->current_shadow_face = 0;
1319                      linfo->current_shadow_face < 6;
1320                      linfo->current_shadow_face++)
1321                 {
1322                         /* Copy using a small 3x3 box filter */
1323                         GPU_framebuffer_texture_cubeface_attach(sldata->shadow_cube_store_fb, sldata->shadow_cube_blur, 0,
1324                                                                 linfo->current_shadow_face, 0);
1325                         GPU_framebuffer_bind(sldata->shadow_cube_store_fb);
1326                         DRW_draw_pass(psl->shadow_cube_copy_pass);
1327                 }
1328
1329                 /* Push it to shadowmap array */
1330
1331                 /* Adjust constants if concentric samples change. */
1332                 const float max_filter_size = 7.5f;
1333                 const float magic = 4.5f; /* Dunno why but that works. */
1334                 const int max_sample = 256;
1335
1336                 if (filter_pixel_size > 2.0f) {
1337                         linfo->filter_size = srd->cube_texel_size * max_filter_size * magic;
1338                         filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
1339                         /* Compute number of concentric samples. Depends directly on filter size. */
1340                         float pix_size_sqr = filter_pixel_size * filter_pixel_size;
1341                         srd->shadow_samples_len = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
1342                 }
1343                 else {
1344                         linfo->filter_size = 0.0f;
1345                         srd->shadow_samples_len = 4;
1346                 }
1347                 srd->shadow_samples_len_inv = 1.0f / (float)srd->shadow_samples_len;
1348                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
1349
1350                 GPU_framebuffer_texture_layer_attach(sldata->shadow_cube_store_fb, sldata->shadow_cube_pool, 0, evscd->layer_id, 0);
1351                 GPU_framebuffer_bind(sldata->shadow_cube_store_fb);
1352
1353                 DRWPass *store_pass = eevee_lights_cube_store_pass_get(psl, sldata, linfo->shadow_method, srd->shadow_samples_len);
1354                 DRW_draw_pass(store_pass);
1355
1356                 if (linfo->soft_shadows == false) {
1357                         led->need_update = false;
1358                 }
1359         }
1360         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
1361         DRW_stats_group_end();
1362
1363         DRW_viewport_matrix_override_set_all(&saved_mats);
1364         float near = DRW_viewport_near_distance_get();
1365         float far = DRW_viewport_far_distance_get();
1366
1367         /* Cascaded Shadow Maps */
1368         DRW_stats_group_start("Cascaded Shadow Maps");
1369         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
1370                 if (!cascade_visible[i]) {
1371                         continue;
1372                 }
1373
1374                 EEVEE_LampEngineData *led = EEVEE_lamp_data_ensure(ob);
1375                 Lamp *la = (Lamp *)ob->data;
1376
1377                 EEVEE_ShadowCascadeData *evscd = &led->data.scad;
1378                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
1379
1380                 DRWMatrixState render_mats;
1381                 float (*winmat)[4] = render_mats.mat[DRW_MAT_WIN];
1382                 float (*viewmat)[4] = render_mats.mat[DRW_MAT_VIEW];
1383                 float (*persmat)[4] = render_mats.mat[DRW_MAT_PERS];
1384
1385                 eevee_shadow_cascade_setup(ob, linfo, led, &saved_mats, near, far, effects->taa_current_sample - 1);
1386
1387                 srd->clip_near = la->clipsta;
1388                 srd->clip_far = la->clipend;
1389                 srd->stored_texel_size = 1.0 / (float)linfo->shadow_cascade_size;
1390
1391                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1392
1393                 copy_m4_m4(viewmat, evscd->viewmat);
1394                 invert_m4_m4(render_mats.mat[DRW_MAT_VIEWINV], viewmat);
1395
1396                 /* Render shadow cascades */
1397                 /* Render cascade separately: seems to be faster for the general case.
1398                  * The only time it's more beneficial is when the CPU culling overhead
1399                  * outweigh the instancing overhead. which is rarely the case. */
1400                 for (int j = 0; j < la->cascade_count; j++) {
1401                         copy_m4_m4(winmat, evscd->projmat[j]);
1402                         copy_m4_m4(persmat, evscd->viewprojmat[j]);
1403                         invert_m4_m4(render_mats.mat[DRW_MAT_WININV], winmat);
1404                         invert_m4_m4(render_mats.mat[DRW_MAT_PERSINV], persmat);
1405
1406                         DRW_viewport_matrix_override_set_all(&render_mats);
1407
1408                         GPU_framebuffer_texture_layer_attach(sldata->shadow_cascade_target_fb,
1409                                                              sldata->shadow_cascade_target, 0, j, 0);
1410                         GPU_framebuffer_bind(sldata->shadow_cascade_target_fb);
1411                         GPU_framebuffer_clear_depth(sldata->shadow_cascade_target_fb, 1.0f);
1412                         DRW_draw_pass(psl->shadow_pass);
1413                 }
1414
1415                 /* TODO: OPTI: Filter all cascade in one/two draw call */
1416                 for (linfo->current_shadow_cascade = 0;
1417                      linfo->current_shadow_cascade < la->cascade_count;
1418                      ++linfo->current_shadow_cascade)
1419                 {
1420                         /* 0.01f factor to convert to percentage */
1421                         float filter_texture_size = la->soft * 0.01f / evscd->radius[linfo->current_shadow_cascade];
1422                         float filter_pixel_size = ceil(linfo->shadow_cascade_size * filter_texture_size);
1423
1424                         /* Copy using a small 3x3 box filter */
1425                         /* NOTE: We always do it in the case of CSM because of artifacts in the farthest cascade. */
1426                         linfo->filter_size = srd->stored_texel_size;
1427                         GPU_framebuffer_texture_layer_attach(
1428                                 sldata->shadow_cascade_store_fb, sldata->shadow_cascade_blur, 0, linfo->current_shadow_cascade, 0);
1429                         GPU_framebuffer_bind(sldata->shadow_cascade_store_fb);
1430                         DRW_draw_pass(psl->shadow_cascade_copy_pass);
1431
1432                         /* Push it to shadowmap array and blur more */
1433
1434                         /* Adjust constants if concentric samples change. */
1435                         const float max_filter_size = 7.5f;
1436                         const float magic = 3.2f; /* Arbitrary: less banding */
1437                         const int max_sample = 256;
1438
1439                         if (filter_pixel_size > 2.0f) {
1440                                 linfo->filter_size = srd->stored_texel_size * max_filter_size * magic;
1441                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
1442                                 /* Compute number of concentric samples. Depends directly on filter size. */
1443                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
1444                                 srd->shadow_samples_len = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
1445                         }
1446                         else {
1447                                 linfo->filter_size = 0.0f;
1448                                 srd->shadow_samples_len = 4;
1449                         }
1450                         srd->shadow_samples_len_inv = 1.0f / (float)srd->shadow_samples_len;
1451                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1452
1453                         int layer = evscd->layer_id + linfo->current_shadow_cascade;
1454                         GPU_framebuffer_texture_layer_attach(sldata->shadow_cascade_store_fb, sldata->shadow_cascade_pool, 0, layer, 0);
1455                         GPU_framebuffer_bind(sldata->shadow_cascade_store_fb);
1456
1457                         DRWPass *store_pass = eevee_lights_cascade_store_pass_get(psl, sldata, linfo->shadow_method, srd->shadow_samples_len);
1458                         DRW_draw_pass(store_pass);
1459                 }
1460         }
1461
1462         DRW_stats_group_end();
1463
1464         DRW_viewport_matrix_override_set_all(&saved_mats);
1465
1466         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
1467         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_data); /* Update all data at once */
1468
1469         sldata->common_data.ray_type = saved_ray_type;
1470         DRW_uniformbuffer_update(sldata->common_ubo, &sldata->common_data);
1471 }
1472
1473 void EEVEE_lights_free(void)
1474 {
1475         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
1476         for (int i = 0; i < SHADOW_METHOD_MAX; ++i) {
1477                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_sh[i]);
1478                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_high_sh[i]);
1479                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_sh[i]);
1480                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_high_sh[i]);
1481                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cube_sh[i]);
1482                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cascade_sh[i]);
1483         }
1484 }