Merge remote-tracking branch 'origin/master' into blender2.8
[blender.git] / source / blender / draw / engines / eevee / eevee_lights.c
1 /*
2  * Copyright 2016, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file eevee_lights.c
23  *  \ingroup DNA
24  */
25
26 #include "DRW_render.h"
27
28 #include "BLI_dynstr.h"
29
30 #include "BKE_object.h"
31
32 #include "eevee_engine.h"
33 #include "eevee_private.h"
34
35 /* Theses are the structs stored inside Objects.
36  * It works with even if the object is in multiple layers
37  * because we don't get the same "Object *" for each layer. */
38 typedef struct EEVEE_LightData {
39         short light_id, shadow_id;
40 } EEVEE_LightData;
41
42 typedef struct EEVEE_ShadowCubeData {
43         short light_id, shadow_id, cube_id, layer_id;
44 } EEVEE_ShadowCubeData;
45
46 typedef struct EEVEE_ShadowCascadeData {
47         short light_id, shadow_id, cascade_id, layer_id;
48         float viewprojmat[MAX_CASCADE_NUM][4][4]; /* World->Lamp->NDC : used for rendering the shadow map. */
49         float radius[MAX_CASCADE_NUM];
50 } EEVEE_ShadowCascadeData;
51
52 typedef struct ShadowCaster {
53         struct ShadowCaster *next, *prev;
54         void *ob;
55         bool prune;
56 } ShadowCaster;
57
58 static struct {
59         struct GPUShader *shadow_sh;
60         struct GPUShader *shadow_store_cube_sh[SHADOW_METHOD_MAX];
61         struct GPUShader *shadow_store_cascade_sh[SHADOW_METHOD_MAX];
62         struct GPUShader *shadow_copy_cube_sh[SHADOW_METHOD_MAX];
63         struct GPUShader *shadow_copy_cascade_sh[SHADOW_METHOD_MAX];
64 } e_data = {NULL}; /* Engine data */
65
66 extern char datatoc_shadow_vert_glsl[];
67 extern char datatoc_shadow_geom_glsl[];
68 extern char datatoc_shadow_frag_glsl[];
69 extern char datatoc_shadow_store_frag_glsl[];
70 extern char datatoc_shadow_copy_frag_glsl[];
71 extern char datatoc_concentric_samples_lib_glsl[];
72
73 /* *********** FUNCTIONS *********** */
74
75 void EEVEE_lights_init(EEVEE_SceneLayerData *sldata)
76 {
77         const unsigned int shadow_ubo_size = sizeof(EEVEE_Shadow) * MAX_SHADOW +
78                                              sizeof(EEVEE_ShadowCube) * MAX_SHADOW_CUBE +
79                                              sizeof(EEVEE_ShadowCascade) * MAX_SHADOW_CASCADE;
80
81         const DRWContextState *draw_ctx = DRW_context_state_get();
82         SceneLayer *scene_layer = draw_ctx->scene_layer;
83         IDProperty *props = BKE_scene_layer_engine_evaluated_get(scene_layer, COLLECTION_MODE_NONE, RE_engine_id_BLENDER_EEVEE);
84
85         if (!e_data.shadow_sh) {
86                 e_data.shadow_sh = DRW_shader_create(
87                         datatoc_shadow_vert_glsl, datatoc_shadow_geom_glsl, datatoc_shadow_frag_glsl, NULL);
88
89                 DynStr *ds_frag = BLI_dynstr_new();
90                 BLI_dynstr_append(ds_frag, datatoc_concentric_samples_lib_glsl);
91                 BLI_dynstr_append(ds_frag, datatoc_shadow_store_frag_glsl);
92                 char *store_shadow_shader_str = BLI_dynstr_get_cstring(ds_frag);
93                 BLI_dynstr_free(ds_frag);
94
95                 e_data.shadow_store_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define ESM\n");
96                 e_data.shadow_store_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define ESM\n"
97                                                                                                                    "#define CSM\n");
98
99                 e_data.shadow_store_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define VSM\n");
100                 e_data.shadow_store_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(store_shadow_shader_str, "#define VSM\n"
101                                                                                                                    "#define CSM\n");
102
103                 MEM_freeN(store_shadow_shader_str);
104
105                 e_data.shadow_copy_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define ESM\n"
106                                                                                                                      "#define COPY\n");
107                 e_data.shadow_copy_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define ESM\n"
108                                                                                                                         "#define COPY\n"
109                                                                                                                         "#define CSM\n");
110
111                 e_data.shadow_copy_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define VSM\n"
112                                                                                                                      "#define COPY\n");
113                 e_data.shadow_copy_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_copy_frag_glsl, "#define VSM\n"
114                                                                                                                         "#define COPY\n"
115                                                                                                                         "#define CSM\n");
116         }
117
118         if (!sldata->lamps) {
119                 sldata->lamps              = MEM_callocN(sizeof(EEVEE_LampsInfo), "EEVEE_LampsInfo");
120                 sldata->light_ubo          = DRW_uniformbuffer_create(sizeof(EEVEE_Light) * MAX_LIGHT, NULL);
121                 sldata->shadow_ubo         = DRW_uniformbuffer_create(shadow_ubo_size, NULL);
122                 sldata->shadow_render_ubo  = DRW_uniformbuffer_create(sizeof(EEVEE_ShadowRender), NULL);
123         }
124
125         int sh_method = BKE_collection_engine_property_value_get_int(props, "shadow_method");
126         int sh_size = BKE_collection_engine_property_value_get_int(props, "shadow_size");
127         int sh_high_bitdepth = BKE_collection_engine_property_value_get_int(props, "shadow_high_bitdepth");
128
129         EEVEE_LampsInfo *linfo = sldata->lamps;
130         if ((linfo->shadow_size != sh_size) ||
131                 (linfo->shadow_method != sh_method) ||
132                 (linfo->shadow_high_bitdepth != sh_high_bitdepth))
133         {
134                 BLI_assert((sh_size > 0) && (sh_size <= 8192));
135                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
136                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_target);
137                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_target);
138                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_blur);
139                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_blur);
140
141                 linfo->shadow_high_bitdepth = sh_high_bitdepth;
142                 linfo->shadow_method = sh_method;
143                 linfo->shadow_size = sh_size;
144                 linfo->shadow_render_data.stored_texel_size = 1.0 / (float)linfo->shadow_size;
145
146                 /* Compute adequate size for the cubemap render target.
147                  * The 3.0f factor is here to make sure there is no under sampling between
148                  * the octahedron mapping and the cubemap. */
149                 int new_cube_target_size = (int)ceil(sqrt((float)(sh_size * sh_size) / 6.0f) * 3.0f);
150
151                 CLAMP(new_cube_target_size, 1, 4096);
152
153                 linfo->shadow_cube_target_size = new_cube_target_size;
154                 linfo->shadow_render_data.cube_texel_size = 1.0 / (float)linfo->shadow_cube_target_size;
155         }
156 }
157
158 void EEVEE_lights_cache_init(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
159 {
160         EEVEE_LampsInfo *linfo = sldata->lamps;
161
162         linfo->num_light = 0;
163         linfo->num_layer = 0;
164         linfo->gpu_cube_ct = linfo->gpu_cascade_ct = linfo->gpu_shadow_ct = 0;
165         linfo->cpu_cube_ct = linfo->cpu_cascade_ct = 0;
166         memset(linfo->light_ref, 0, sizeof(linfo->light_ref));
167         memset(linfo->shadow_cube_ref, 0, sizeof(linfo->shadow_cube_ref));
168         memset(linfo->shadow_cascade_ref, 0, sizeof(linfo->shadow_cascade_ref));
169
170         {
171                 psl->shadow_cube_store_pass = DRW_pass_create("Shadow Storage Pass", DRW_STATE_WRITE_COLOR);
172
173                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cube_sh[linfo->shadow_method], psl->shadow_cube_store_pass);
174                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cube_blur);
175                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
176                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
177                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
178         }
179
180         {
181                 psl->shadow_cascade_store_pass = DRW_pass_create("Shadow Cascade Storage Pass", DRW_STATE_WRITE_COLOR);
182
183                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cascade_sh[linfo->shadow_method], psl->shadow_cascade_store_pass);
184                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cascade_blur);
185                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
186                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
187                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
188                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
189         }
190
191         {
192                 psl->shadow_cube_copy_pass = DRW_pass_create("Shadow Copy Pass", DRW_STATE_WRITE_COLOR);
193
194                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_copy_cube_sh[linfo->shadow_method], psl->shadow_cube_copy_pass);
195                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cube_target);
196                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
197                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
198                 DRW_shgroup_uniform_int(grp, "faceId", &linfo->current_shadow_face, 1);
199                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
200         }
201
202         {
203                 psl->shadow_cascade_copy_pass = DRW_pass_create("Shadow Cascade Copy Pass", DRW_STATE_WRITE_COLOR);
204
205                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_copy_cascade_sh[linfo->shadow_method], psl->shadow_cascade_copy_pass);
206                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cascade_target);
207                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
208                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
209                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
210                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
211         }
212
213         {
214                 psl->shadow_cube_pass = DRW_pass_create("Shadow Cube Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
215         }
216
217         {
218                 psl->shadow_cascade_pass = DRW_pass_create("Shadow Cascade Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
219         }
220
221         /* Reset shadow casters list */
222         BLI_freelistN(&sldata->shadow_casters);
223 }
224
225 void EEVEE_lights_cache_add(EEVEE_SceneLayerData *sldata, Object *ob)
226 {
227         EEVEE_LampsInfo *linfo = sldata->lamps;
228
229         /* Step 1 find all lamps in the scene and setup them */
230         if (linfo->num_light >= MAX_LIGHT) {
231                 printf("Too much lamps in the scene !!!\n");
232                 linfo->num_light = MAX_LIGHT - 1;
233         }
234         else {
235                 Lamp *la = (Lamp *)ob->data;
236                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
237
238                 if ((ob->deg_update_flag & DEG_RUNTIME_DATA_UPDATE) != 0) {
239                         led->need_update = true;
240                 }
241
242                 MEM_SAFE_FREE(led->storage);
243
244                 if (la->mode & (LA_SHAD_BUF | LA_SHAD_RAY)) {
245                         if (la->type == LA_SUN) {
246                                 int sh_nbr = 1; /* TODO : MSM */
247                                 int cascade_nbr = MAX_CASCADE_NUM; /* TODO : Custom cascade number */
248
249                                 if ((linfo->gpu_cascade_ct + sh_nbr) <= MAX_SHADOW_CASCADE) {
250                                         /* Save Light object. */
251                                         linfo->shadow_cascade_ref[linfo->cpu_cascade_ct] = ob;
252
253                                         /* Create storage and store indices. */
254                                         EEVEE_ShadowCascadeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCascadeData), "EEVEE_ShadowCascadeData");
255                                         data->shadow_id = linfo->gpu_shadow_ct;
256                                         data->cascade_id = linfo->gpu_cascade_ct;
257                                         data->layer_id = linfo->num_layer;
258                                         led->storage = data;
259
260                                         /* Increment indices. */
261                                         linfo->gpu_shadow_ct += 1;
262                                         linfo->gpu_cascade_ct += sh_nbr;
263                                         linfo->num_layer += sh_nbr * cascade_nbr;
264
265                                         linfo->cpu_cascade_ct += 1;
266                                 }
267                         }
268                         else if (la->type == LA_SPOT || la->type == LA_LOCAL || la->type == LA_AREA) {
269                                 int sh_nbr = 1; /* TODO : MSM */
270
271                                 if ((linfo->gpu_cube_ct + sh_nbr) <= MAX_SHADOW_CUBE) {
272                                         /* Save Light object. */
273                                         linfo->shadow_cube_ref[linfo->cpu_cube_ct] = ob;
274
275                                         /* Create storage and store indices. */
276                                         EEVEE_ShadowCubeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCubeData), "EEVEE_ShadowCubeData");
277                                         data->shadow_id = linfo->gpu_shadow_ct;
278                                         data->cube_id = linfo->gpu_cube_ct;
279                                         data->layer_id = linfo->num_layer;
280                                         led->storage = data;
281
282                                         /* Increment indices. */
283                                         linfo->gpu_shadow_ct += 1;
284                                         linfo->gpu_cube_ct += sh_nbr;
285                                         linfo->num_layer += sh_nbr;
286
287                                         linfo->cpu_cube_ct += 1;
288                                 }
289                         }
290                 }
291
292                 /* Default light without shadows */
293                 if (!led->storage) {
294                         led->storage = MEM_mallocN(sizeof(EEVEE_LightData), "EEVEE_LightData");
295                         ((EEVEE_LightData *)led->storage)->shadow_id = -1;
296                 }
297
298                 ((EEVEE_LightData *)led->storage)->light_id = linfo->num_light;
299                 linfo->light_ref[linfo->num_light] = ob;
300                 linfo->num_light++;
301         }
302 }
303
304 /* Add a shadow caster to the shadowpasses */
305 void EEVEE_lights_cache_shcaster_add(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct Gwn_Batch *geom, float (*obmat)[4])
306 {
307         DRWShadingGroup *grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cube_pass, geom);
308         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
309         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
310
311         for (int i = 0; i < 6; ++i)
312                 DRW_shgroup_call_dynamic_add_empty(grp);
313
314         grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cascade_pass, geom);
315         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
316         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
317
318         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
319                 DRW_shgroup_call_dynamic_add_empty(grp);
320 }
321
322 void EEVEE_lights_cache_shcaster_material_add(
323         EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct GPUMaterial *gpumat,
324         struct Gwn_Batch *geom, struct Object *ob, float (*obmat)[4], float *alpha_threshold)
325 {
326         DRWShadingGroup *grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cube_pass, geom, ob);
327
328         if (grp == NULL) return;
329
330         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
331         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
332
333         if (alpha_threshold != NULL)
334                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
335
336         for (int i = 0; i < 6; ++i)
337                 DRW_shgroup_call_dynamic_add_empty(grp);
338
339         grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cascade_pass, geom, ob);
340         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
341         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
342
343         if (alpha_threshold != NULL)
344                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
345
346         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
347                 DRW_shgroup_call_dynamic_add_empty(grp);
348 }
349
350 void EEVEE_lights_cache_finish(EEVEE_SceneLayerData *sldata)
351 {
352         EEVEE_LampsInfo *linfo = sldata->lamps;
353         DRWTextureFormat shadow_pool_format;
354
355         /* Setup enough layers. */
356         /* Free textures if number mismatch. */
357         if (linfo->num_layer != linfo->cache_num_layer) {
358                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
359                 linfo->cache_num_layer = linfo->num_layer;
360                 linfo->update_flag |= LIGHT_UPDATE_SHADOW_CUBE;
361         }
362
363         switch (linfo->shadow_method) {
364                 case SHADOW_ESM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_R_32 : DRW_TEX_R_16); break;
365                 case SHADOW_VSM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_RG_32 : DRW_TEX_RG_16); break;
366                 default:
367                         BLI_assert(!"Incorrect Shadow Method");
368                         break;
369         }
370
371         if (!sldata->shadow_cube_target) {
372                 /* TODO render everything on the same 2d render target using clip planes and no Geom Shader. */
373                 /* Cubemaps */
374                 sldata->shadow_cube_target = DRW_texture_create_cube(linfo->shadow_cube_target_size, DRW_TEX_DEPTH_24, 0, NULL);
375                 sldata->shadow_cube_blur = DRW_texture_create_cube(linfo->shadow_cube_target_size, shadow_pool_format, DRW_TEX_FILTER, NULL);
376         }
377
378         if (!sldata->shadow_cascade_target) {
379                 /* CSM */
380                 sldata->shadow_cascade_target = DRW_texture_create_2D_array(
381                         linfo->shadow_size, linfo->shadow_size, MAX_CASCADE_NUM, DRW_TEX_DEPTH_24, 0, NULL);
382                 sldata->shadow_cascade_blur = DRW_texture_create_2D_array(
383                         linfo->shadow_size, linfo->shadow_size, MAX_CASCADE_NUM, shadow_pool_format, DRW_TEX_FILTER, NULL);
384         }
385
386         /* Initialize Textures Array first so DRW_framebuffer_init just bind them. */
387         if (!sldata->shadow_pool) {
388                 /* All shadows fit in this array */
389                 sldata->shadow_pool = DRW_texture_create_2D_array(
390                         linfo->shadow_size, linfo->shadow_size, max_ff(1, linfo->num_layer),
391                         shadow_pool_format, DRW_TEX_FILTER, NULL);
392         }
393
394         /* Render FB */
395         DRWFboTexture tex_cascade = {&sldata->shadow_cube_target, DRW_TEX_DEPTH_24, 0};
396         DRW_framebuffer_init(&sldata->shadow_target_fb, &draw_engine_eevee_type,
397                              linfo->shadow_size, linfo->shadow_size,
398                              &tex_cascade, 1);
399
400         /* Storage FB */
401         DRWFboTexture tex_pool = {&sldata->shadow_pool, shadow_pool_format, DRW_TEX_FILTER};
402         DRW_framebuffer_init(&sldata->shadow_store_fb, &draw_engine_eevee_type,
403                              linfo->shadow_size, linfo->shadow_size,
404                              &tex_pool, 1);
405
406         /* Restore */
407         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
408
409         /* Update Lamps UBOs. */
410         EEVEE_lights_update(sldata);
411 }
412
413 /* Update buffer with lamp data */
414 static void eevee_light_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
415 {
416         /* TODO only update if data changes */
417         EEVEE_LightData *evld = led->storage;
418         EEVEE_Light *evli = linfo->light_data + evld->light_id;
419         Lamp *la = (Lamp *)ob->data;
420         float mat[4][4], scale[3], power;
421
422         /* Position */
423         copy_v3_v3(evli->position, ob->obmat[3]);
424
425         /* Color */
426         copy_v3_v3(evli->color, &la->r);
427
428         /* Influence Radius */
429         evli->dist = la->dist;
430
431         /* Vectors */
432         normalize_m4_m4_ex(mat, ob->obmat, scale);
433         copy_v3_v3(evli->forwardvec, mat[2]);
434         normalize_v3(evli->forwardvec);
435         negate_v3(evli->forwardvec);
436
437         copy_v3_v3(evli->rightvec, mat[0]);
438         normalize_v3(evli->rightvec);
439
440         copy_v3_v3(evli->upvec, mat[1]);
441         normalize_v3(evli->upvec);
442
443         /* Spot size & blend */
444         if (la->type == LA_SPOT) {
445                 evli->sizex = scale[0] / scale[2];
446                 evli->sizey = scale[1] / scale[2];
447                 evli->spotsize = cosf(la->spotsize * 0.5f);
448                 evli->spotblend = (1.0f - evli->spotsize) * la->spotblend;
449                 evli->radius = max_ff(0.001f, la->area_size);
450         }
451         else if (la->type == LA_AREA) {
452                 evli->sizex = max_ff(0.0001f, la->area_size * scale[0] * 0.5f);
453                 if (la->area_shape == LA_AREA_RECT) {
454                         evli->sizey = max_ff(0.0001f, la->area_sizey * scale[1] * 0.5f);
455                 }
456                 else {
457                         evli->sizey = max_ff(0.0001f, la->area_size * scale[1] * 0.5f);
458                 }
459         }
460         else {
461                 evli->radius = max_ff(0.001f, la->area_size);
462         }
463
464         /* Make illumination power constant */
465         if (la->type == LA_AREA) {
466                 power = 1.0f / (evli->sizex * evli->sizey * 4.0f * M_PI) /* 1/(w*h*Pi) */
467                         * 80.0f; /* XXX : Empirical, Fit cycles power */
468         }
469         else if (la->type == LA_SPOT || la->type == LA_LOCAL) {
470                 power = 1.0f / (4.0f * evli->radius * evli->radius * M_PI * M_PI) /* 1/(4*r²*Pi²) */
471                         * M_PI * M_PI * M_PI * 10.0; /* XXX : Empirical, Fit cycles power */
472
473                 /* for point lights (a.k.a radius == 0.0) */
474                 // power = M_PI * M_PI * 0.78; /* XXX : Empirical, Fit cycles power */
475         }
476         else {
477                 power = 1.0f;
478         }
479         mul_v3_fl(evli->color, power * la->energy);
480
481         /* Lamp Type */
482         evli->lamptype = (float)la->type;
483
484         /* No shadow by default */
485         evli->shadowid = -1.0f;
486 }
487
488 static void eevee_shadow_cube_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
489 {
490         EEVEE_ShadowCubeData *sh_data = (EEVEE_ShadowCubeData *)led->storage;
491         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
492         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
493         EEVEE_ShadowCube *cube_data = linfo->shadow_cube_data + sh_data->cube_id;
494         Lamp *la = (Lamp *)ob->data;
495
496         int sh_nbr = 1; /* TODO: MSM */
497
498         for (int i = 0; i < sh_nbr; ++i) {
499                 /* TODO : choose MSM sample point here. */
500                 copy_v3_v3(cube_data->position, ob->obmat[3]);
501         }
502
503         ubo_data->bias = 0.05f * la->bias;
504         ubo_data->near = la->clipsta;
505         ubo_data->far = la->clipend;
506         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
507
508         evli->shadowid = (float)(sh_data->shadow_id);
509         ubo_data->shadow_start = (float)(sh_data->layer_id);
510         ubo_data->data_start = (float)(sh_data->cube_id);
511         ubo_data->multi_shadow_count = (float)(sh_nbr);
512 }
513
514 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
515
516 static void frustum_min_bounding_sphere(const float corners[8][4], float r_center[3], float *r_radius)
517 {
518 #if 0 /* Simple solution but waist too much space. */
519         float minvec[3], maxvec[3];
520
521         /* compute the bounding box */
522         INIT_MINMAX(minvec, maxvec);
523         for (int i = 0; i < 8; ++i)     {
524                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
525         }
526
527         /* compute the bounding sphere of this box */
528         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
529         add_v3_v3v3(r_center, minvec, maxvec);
530         mul_v3_fl(r_center, 0.5f);
531 #else
532         /* Make the bouding sphere always centered on the front diagonal */
533         add_v3_v3v3(r_center, corners[4], corners[7]);
534         mul_v3_fl(r_center, 0.5f);
535         *r_radius = len_v3v3(corners[0], r_center);
536
537         /* Search the largest distance between the sphere center
538          * and the front plane corners. */
539         for (int i = 0; i < 4; ++i) {
540                 float rad = len_v3v3(corners[4+i], r_center);
541                 if (rad > *r_radius) {
542                         *r_radius = rad;
543                 }
544         }
545 #endif
546 }
547
548 static void eevee_shadow_cascade_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
549 {
550         Lamp *la = (Lamp *)ob->data;
551
552         /* Camera Matrices */
553         float persmat[4][4], persinv[4][4];
554         float viewprojmat[4][4], projinv[4][4];
555         float view_near, view_far;
556         float near_v[4] = {0.0f, 0.0f, -1.0f, 1.0f};
557         float far_v[4] = {0.0f, 0.0f,  1.0f, 1.0f};
558         bool is_persp = DRW_viewport_is_persp_get();
559         DRW_viewport_matrix_get(persmat, DRW_MAT_PERS);
560         invert_m4_m4(persinv, persmat);
561         /* FIXME : Get near / far from Draw manager? */
562         DRW_viewport_matrix_get(viewprojmat, DRW_MAT_WIN);
563         invert_m4_m4(projinv, viewprojmat);
564         mul_m4_v4(projinv, near_v);
565         mul_m4_v4(projinv, far_v);
566         view_near = near_v[2];
567         view_far = far_v[2]; /* TODO: Should be a shadow parameter */
568         if (is_persp) {
569                 view_near /= near_v[3];
570                 view_far /= far_v[3];
571         }
572
573         /* Lamps Matrices */
574         float viewmat[4][4], projmat[4][4];
575         int sh_nbr = 1; /* TODO : MSM */
576         int cascade_nbr = la->cascade_count;
577
578         EEVEE_ShadowCascadeData *sh_data = (EEVEE_ShadowCascadeData *)led->storage;
579         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
580         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
581         EEVEE_ShadowCascade *cascade_data = linfo->shadow_cascade_data + sh_data->cascade_id;
582
583         /* The technique consists into splitting
584          * the view frustum into several sub-frustum
585          * that are individually receiving one shadow map */
586
587         float csm_start, csm_end;
588
589         if (is_persp) {
590                 csm_start = view_near;
591                 csm_end = max_ff(view_far, -la->cascade_max_dist);
592                 /* Avoid artifacts */
593                 csm_end = min_ff(view_near, csm_end);
594         }
595         else {
596                 csm_start = -view_far;
597                 csm_end = view_far;
598         }
599
600         /* init near/far */
601         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
602                 cascade_data->split_start[c] = csm_end;
603                 cascade_data->split_end[c] = csm_end;
604         }
605
606         /* Compute split planes */
607         float splits_start_ndc[MAX_CASCADE_NUM];
608         float splits_end_ndc[MAX_CASCADE_NUM];
609
610         {
611                 /* Nearest plane */
612                 float p[4] = {1.0f, 1.0f, csm_start, 1.0f};
613                 /* TODO: we don't need full m4 multiply here */
614                 mul_m4_v4(viewprojmat, p);
615                 splits_start_ndc[0] = p[2];
616                 if (is_persp) {
617                         splits_start_ndc[0] /= p[3];
618                 }
619         }
620
621         {
622                 /* Farthest plane */
623                 float p[4] = {1.0f, 1.0f, csm_end, 1.0f};
624                 /* TODO: we don't need full m4 multiply here */
625                 mul_m4_v4(viewprojmat, p);
626                 splits_end_ndc[cascade_nbr - 1] = p[2];
627                 if (is_persp) {
628                         splits_end_ndc[cascade_nbr - 1] /= p[3];
629                 }
630         }
631
632         cascade_data->split_start[0] = csm_start;
633         cascade_data->split_end[cascade_nbr - 1] = csm_end;
634
635         for (int c = 1; c < cascade_nbr; ++c) {
636                 /* View Space */
637                 float linear_split = LERP(((float)(c) / (float)cascade_nbr), csm_start, csm_end);
638                 float exp_split = csm_start * powf(csm_end / csm_start, (float)(c) / (float)cascade_nbr);
639
640                 if (is_persp) {
641                         cascade_data->split_start[c] = LERP(la->cascade_exponent, linear_split, exp_split);
642                 }
643                 else {
644                         cascade_data->split_start[c] = linear_split;
645                 }
646                 cascade_data->split_end[c-1] = cascade_data->split_start[c];
647
648                 /* Add some overlap for smooth transition */
649                 cascade_data->split_start[c] = LERP(la->cascade_fade, cascade_data->split_end[c-1],
650                                                     (c > 1) ? cascade_data->split_end[c-2] : cascade_data->split_start[0]);
651
652                 /* NDC Space */
653                 {
654                         float p[4] = {1.0f, 1.0f, cascade_data->split_start[c], 1.0f};
655                         /* TODO: we don't need full m4 multiply here */
656                         mul_m4_v4(viewprojmat, p);
657                         splits_start_ndc[c] = p[2];
658
659                         if (is_persp) {
660                                 splits_start_ndc[c] /= p[3];
661                         }
662                 }
663
664                 {
665                         float p[4] = {1.0f, 1.0f, cascade_data->split_end[c-1], 1.0f};
666                         /* TODO: we don't need full m4 multiply here */
667                         mul_m4_v4(viewprojmat, p);
668                         splits_end_ndc[c-1] = p[2];
669
670                         if (is_persp) {
671                                 splits_end_ndc[c-1] /= p[3];
672                         }
673                 }
674         }
675
676         /* Set last cascade split fade distance into the first split_start. */
677         float prev_split = (cascade_nbr > 1) ? cascade_data->split_end[cascade_nbr-2] : cascade_data->split_start[0];
678         cascade_data->split_start[0] = LERP(la->cascade_fade, cascade_data->split_end[cascade_nbr-1], prev_split);
679
680         /* For each cascade */
681         for (int c = 0; c < cascade_nbr; ++c) {
682                 /* Given 8 frustum corners */
683                 float corners[8][4] = {
684                         /* Near Cap */
685                         {-1.0f, -1.0f, splits_start_ndc[c], 1.0f},
686                         { 1.0f, -1.0f, splits_start_ndc[c], 1.0f},
687                         {-1.0f,  1.0f, splits_start_ndc[c], 1.0f},
688                         { 1.0f,  1.0f, splits_start_ndc[c], 1.0f},
689                         /* Far Cap */
690                         {-1.0f, -1.0f, splits_end_ndc[c], 1.0f},
691                         { 1.0f, -1.0f, splits_end_ndc[c], 1.0f},
692                         {-1.0f,  1.0f, splits_end_ndc[c], 1.0f},
693                         { 1.0f,  1.0f, splits_end_ndc[c], 1.0f}
694                 };
695
696                 /* Transform them into world space */
697                 for (int i = 0; i < 8; ++i)     {
698                         mul_m4_v4(persinv, corners[i]);
699                         mul_v3_fl(corners[i], 1.0f / corners[i][3]);
700                         corners[i][3] = 1.0f;
701                 }
702
703
704                 /* Project them into light space */
705                 invert_m4_m4(viewmat, ob->obmat);
706                 normalize_v3(viewmat[0]);
707                 normalize_v3(viewmat[1]);
708                 normalize_v3(viewmat[2]);
709
710                 for (int i = 0; i < 8; ++i)     {
711                         mul_m4_v4(viewmat, corners[i]);
712                 }
713
714                 float center[3];
715                 frustum_min_bounding_sphere(corners, center, &(sh_data->radius[c]));
716
717                 /* Snap projection center to nearest texel to cancel shimmering. */
718                 float shadow_origin[2], shadow_texco[2];
719                 mul_v2_v2fl(shadow_origin, center, linfo->shadow_size / (2.0f * sh_data->radius[c])); /* Light to texture space. */
720
721                 /* Find the nearest texel. */
722                 shadow_texco[0] = round(shadow_origin[0]);
723                 shadow_texco[1] = round(shadow_origin[1]);
724
725                 /* Compute offset. */
726                 sub_v2_v2(shadow_texco, shadow_origin);
727                 mul_v2_fl(shadow_texco, (2.0f * sh_data->radius[c]) / linfo->shadow_size); /* Texture to light space. */
728
729                 /* Apply offset. */
730                 add_v2_v2(center, shadow_texco);
731
732                 /* Expand the projection to cover frustum range */
733                 orthographic_m4(projmat,
734                                 center[0] - sh_data->radius[c],
735                                 center[0] + sh_data->radius[c],
736                                 center[1] - sh_data->radius[c],
737                                 center[1] + sh_data->radius[c],
738                                 la->clipsta, la->clipend);
739
740                 mul_m4_m4m4(sh_data->viewprojmat[c], projmat, viewmat);
741                 mul_m4_m4m4(cascade_data->shadowmat[c], texcomat, sh_data->viewprojmat[c]);
742         }
743
744         ubo_data->bias = 0.05f * la->bias;
745         ubo_data->near = la->clipsta;
746         ubo_data->far = la->clipend;
747         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
748
749         evli->shadowid = (float)(sh_data->shadow_id);
750         ubo_data->shadow_start = (float)(sh_data->layer_id);
751         ubo_data->data_start = (float)(sh_data->cascade_id);
752         ubo_data->multi_shadow_count = (float)(sh_nbr);
753 }
754
755 /* Used for checking if object is inside the shadow volume. */
756 static bool cube_bbox_intersect(const float cube_center[3], float cube_half_dim, const BoundBox *bb, float (*obmat)[4])
757 {
758         float min[3], max[4], tmp[4][4];
759         unit_m4(tmp);
760         translate_m4(tmp, -cube_center[0], -cube_center[1], -cube_center[2]);
761         mul_m4_m4m4(tmp, tmp, obmat);
762
763         /* Just simple AABB intersection test in world space. */
764         INIT_MINMAX(min, max);
765         for (int i = 0; i < 8; ++i) {
766                 float vec[3];
767                 copy_v3_v3(vec, bb->vec[i]);
768                 mul_m4_v3(tmp, vec);
769                 minmax_v3v3_v3(min, max, vec);
770         }
771
772     if (MAX3(max[0], max[1], max[2]) < -cube_half_dim) return false;
773     if (MIN3(min[0], min[1], min[2]) >  cube_half_dim) return false;
774
775         return true;
776 }
777
778 static ShadowCaster *search_object_in_list(ListBase *list, Object *ob)
779 {
780         for (ShadowCaster *ldata = list->first; ldata; ldata = ldata->next) {
781                 if (ldata->ob == ob)
782                         return ldata;
783         }
784
785         return NULL;
786 }
787
788 static void delete_pruned_shadowcaster(EEVEE_LampEngineData *led)
789 {
790         ShadowCaster *next;
791         for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = next) {
792                 next = ldata->next;
793                 if (ldata->prune == true) {
794                         led->need_update = true;
795                         BLI_freelinkN(&led->shadow_caster_list, ldata);
796                 }
797         }
798 }
799
800 static void light_tag_shadow_update(Object *lamp, Object *ob)
801 {
802         Lamp *la = lamp->data;
803         EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
804
805         bool is_inside_range = cube_bbox_intersect(lamp->obmat[3], la->clipend, BKE_object_boundbox_get(ob), ob->obmat);
806         ShadowCaster *ldata = search_object_in_list(&led->shadow_caster_list, ob);
807
808         if (is_inside_range) {
809                 if (ldata == NULL) {
810                         /* Object was not a shadow caster previously but is now. Add it. */
811                         ldata = MEM_callocN(sizeof(ShadowCaster), "ShadowCaster");
812                         ldata->ob = ob;
813                         BLI_addtail(&led->shadow_caster_list, ldata);
814                         led->need_update = true;
815                 }
816                 else {
817                         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_get(ob);
818                         if (oedata->need_update) {
819                                 led->need_update = true;
820                         }
821                 }
822                 ldata->prune = false;
823         }
824         else if (ldata != NULL) {
825                 /* Object was a shadow caster previously and is not anymore. Remove it. */
826                 led->need_update = true;
827                 BLI_freelinkN(&led->shadow_caster_list, ldata);
828         }
829 }
830
831 static void eevee_lights_shcaster_updated(EEVEE_SceneLayerData *sldata, Object *ob)
832 {
833         Object *lamp;
834         EEVEE_LampsInfo *linfo = sldata->lamps;
835
836         /* Iterate over all shadow casting lamps to see if
837          * each of them needs update because of this object */
838         for (int i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
839                 light_tag_shadow_update(lamp, ob);
840         }
841 }
842
843 void EEVEE_lights_update(EEVEE_SceneLayerData *sldata)
844 {
845         EEVEE_LampsInfo *linfo = sldata->lamps;
846         Object *ob;
847         int i;
848
849         /* Prune shadow casters to remove if object does not exists anymore (unprune them if object exists) */
850         Object *lamp;
851         for (i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
852                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
853
854                 if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
855                         led->need_update = true;
856                 }
857
858                 for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = ldata->next) {
859                         ldata->prune = true;
860                 }
861         }
862
863         for (LinkData *ldata = sldata->shadow_casters.first; ldata; ldata = ldata->next) {
864                 eevee_lights_shcaster_updated(sldata, ldata->data);
865         }
866
867         for (i = 0; (ob = linfo->light_ref[i]) && (i < MAX_LIGHT); i++) {
868                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
869                 eevee_light_setup(ob, linfo, led);
870         }
871
872         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
873                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
874                 eevee_shadow_cube_setup(ob, linfo, led);
875                 delete_pruned_shadowcaster(led);
876         }
877 }
878
879 /* this refresh lamps shadow buffers */
880 void EEVEE_draw_shadows(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
881 {
882         EEVEE_LampsInfo *linfo = sldata->lamps;
883         Object *ob;
884         int i;
885         float clear_col[4] = {FLT_MAX};
886
887         /* Cube Shadow Maps */
888         DRW_stats_group_start("Cube Shadow Maps");
889         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cube_target, 0, 0);
890         /* Render each shadow to one layer of the array */
891         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
892                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
893                 Lamp *la = (Lamp *)ob->data;
894
895                 float cube_projmat[4][4];
896                 perspective_m4(cube_projmat, -la->clipsta, la->clipsta, -la->clipsta, la->clipsta, la->clipsta, la->clipend);
897
898                 if (led->need_update) {
899                         EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
900                         EEVEE_ShadowCubeData *evscd = (EEVEE_ShadowCubeData *)led->storage;
901
902                         srd->clip_near = la->clipsta;
903                         srd->clip_far = la->clipend;
904                         copy_v3_v3(srd->position, ob->obmat[3]);
905                         for (int j = 0; j < 6; j++) {
906                                 float tmp[4][4];
907
908                                 unit_m4(tmp);
909                                 negate_v3_v3(tmp[3], ob->obmat[3]);
910                                 mul_m4_m4m4(srd->viewmat[j], cubefacemat[j], tmp);
911
912                                 mul_m4_m4m4(srd->shadowmat[j], cube_projmat, srd->viewmat[j]);
913                         }
914                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
915
916                         DRW_framebuffer_bind(sldata->shadow_target_fb);
917                         DRW_framebuffer_clear(true, true, false, clear_col, 1.0f);
918
919                         /* Render shadow cube */
920                         DRW_draw_pass(psl->shadow_cube_pass);
921
922                         /* 0.001f is arbitrary, but it should be relatively small so that filter size is not too big. */
923                         float filter_texture_size = la->soft * 0.001f;
924                         float filter_pixel_size = ceil(filter_texture_size / linfo->shadow_render_data.cube_texel_size);
925                         linfo->filter_size = linfo->shadow_render_data.cube_texel_size * ((filter_pixel_size > 1.0f) ? 1.5f : 0.0f);
926
927                         /* TODO: OPTI: Filter all faces in one/two draw call */
928                         for (linfo->current_shadow_face = 0;
929                              linfo->current_shadow_face < 6;
930                              linfo->current_shadow_face++)
931                         {
932                                 /* Copy using a small 3x3 box filter */
933                                 DRW_framebuffer_cubeface_attach(sldata->shadow_store_fb, sldata->shadow_cube_blur, 0, linfo->current_shadow_face, 0);
934                                 DRW_framebuffer_bind(sldata->shadow_store_fb);
935                                 DRW_draw_pass(psl->shadow_cube_copy_pass);
936                                 DRW_framebuffer_texture_detach(sldata->shadow_cube_blur);
937                         }
938
939                         /* Push it to shadowmap array */
940
941                         /* Adjust constants if concentric samples change. */
942                         const float max_filter_size = 7.5f;
943                         const float previous_box_filter_size = 9.0f; /* Dunno why but that works. */
944                         const int max_sample = 256;
945
946                         if (filter_pixel_size > 2.0f) {
947                                 linfo->filter_size = linfo->shadow_render_data.cube_texel_size * max_filter_size * previous_box_filter_size;
948                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
949                                 /* Compute number of concentric samples. Depends directly on filter size. */
950                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
951                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
952                         }
953                         else {
954                                 linfo->filter_size = 0.0f;
955                                 srd->shadow_samples_ct = 4;
956                         }
957                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
958                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
959
960                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, evscd->layer_id, 0);
961                         DRW_framebuffer_bind(sldata->shadow_store_fb);
962                         DRW_draw_pass(psl->shadow_cube_store_pass);
963
964                         led->need_update = false;
965                 }
966         }
967         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
968
969         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
970         DRW_stats_group_end();
971
972         /* Cascaded Shadow Maps */
973         DRW_stats_group_start("Cascaded Shadow Maps");
974         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cascade_target, 0, 0);
975         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
976                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
977                 Lamp *la = (Lamp *)ob->data;
978
979                 EEVEE_ShadowCascadeData *evscd = (EEVEE_ShadowCascadeData *)led->storage;
980                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
981
982                 eevee_shadow_cascade_setup(ob, linfo, led);
983
984                 srd->clip_near = la->clipsta;
985                 srd->clip_far = la->clipend;
986                 for (int j = 0; j < la->cascade_count; ++j) {
987                         copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
988                 }
989                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
990
991                 DRW_framebuffer_bind(sldata->shadow_target_fb);
992                 DRW_framebuffer_clear(false, true, false, NULL, 1.0);
993
994                 /* Render shadow cascades */
995                 DRW_draw_pass(psl->shadow_cascade_pass);
996
997                 /* TODO: OPTI: Filter all cascade in one/two draw call */
998                 for (linfo->current_shadow_cascade = 0;
999                      linfo->current_shadow_cascade < la->cascade_count;
1000                      ++linfo->current_shadow_cascade)
1001                 {
1002                         /* 0.01f factor to convert to percentage */
1003                         float filter_texture_size = la->soft * 0.01f / evscd->radius[linfo->current_shadow_cascade];
1004                         float filter_pixel_size = ceil(linfo->shadow_size * filter_texture_size);
1005
1006                         /* Copy using a small 3x3 box filter */
1007                         linfo->filter_size = linfo->shadow_render_data.stored_texel_size * ((filter_pixel_size > 1.0f) ? 1.0f : 0.0f);
1008                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_cascade_blur, 0, linfo->current_shadow_cascade, 0);
1009                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1010                         DRW_draw_pass(psl->shadow_cascade_copy_pass);
1011                         DRW_framebuffer_texture_detach(sldata->shadow_cascade_blur);
1012
1013                         /* Push it to shadowmap array and blur more */
1014
1015                         /* Adjust constants if concentric samples change. */
1016                         const float max_filter_size = 7.5f;
1017                         const float previous_box_filter_size = 3.2f; /* Arbitrary: less banding */
1018                         const int max_sample = 256;
1019
1020                         if (filter_pixel_size > 2.0f) {
1021                                 linfo->filter_size = linfo->shadow_render_data.stored_texel_size * max_filter_size * previous_box_filter_size;
1022                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
1023                                 /* Compute number of concentric samples. Depends directly on filter size. */
1024                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
1025                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
1026                         }
1027                         else {
1028                                 linfo->filter_size = 0.0f;
1029                                 srd->shadow_samples_ct = 4;
1030                         }
1031                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
1032                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1033
1034                         int layer = evscd->layer_id + linfo->current_shadow_cascade;
1035                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, layer, 0);
1036                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1037                         DRW_draw_pass(psl->shadow_cascade_store_pass);
1038                 }
1039         }
1040
1041         DRW_framebuffer_texture_detach(sldata->shadow_cascade_target);
1042         DRW_stats_group_end();
1043
1044         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
1045         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_data); /* Update all data at once */
1046 }
1047
1048 void EEVEE_lights_free(void)
1049 {
1050         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
1051         for (int i = 0; i < SHADOW_METHOD_MAX; ++i) {
1052                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_sh[i]);
1053                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_sh[i]);
1054                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cube_sh[i]);
1055                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cascade_sh[i]);
1056         }
1057 }