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