Eevee: Shadows: Add Contact Shadows
[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         ubo_data->contact_dist = (la->mode & LA_SHAD_CONTACT) ? la->contact_dist : 0.0f;
514         ubo_data->contact_bias = 0.05f * la->contact_bias;
515         ubo_data->contact_spread = la->contact_spread;
516         ubo_data->contact_thickness = la->contact_thickness;
517 }
518
519 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
520
521 static void frustum_min_bounding_sphere(const float corners[8][4], float r_center[3], float *r_radius)
522 {
523 #if 0 /* Simple solution but waist too much space. */
524         float minvec[3], maxvec[3];
525
526         /* compute the bounding box */
527         INIT_MINMAX(minvec, maxvec);
528         for (int i = 0; i < 8; ++i)     {
529                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
530         }
531
532         /* compute the bounding sphere of this box */
533         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
534         add_v3_v3v3(r_center, minvec, maxvec);
535         mul_v3_fl(r_center, 0.5f);
536 #else
537         /* Make the bouding sphere always centered on the front diagonal */
538         add_v3_v3v3(r_center, corners[4], corners[7]);
539         mul_v3_fl(r_center, 0.5f);
540         *r_radius = len_v3v3(corners[0], r_center);
541
542         /* Search the largest distance between the sphere center
543          * and the front plane corners. */
544         for (int i = 0; i < 4; ++i) {
545                 float rad = len_v3v3(corners[4+i], r_center);
546                 if (rad > *r_radius) {
547                         *r_radius = rad;
548                 }
549         }
550 #endif
551 }
552
553 static void eevee_shadow_cascade_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
554 {
555         Lamp *la = (Lamp *)ob->data;
556
557         /* Camera Matrices */
558         float persmat[4][4], persinv[4][4];
559         float viewprojmat[4][4], projinv[4][4];
560         float view_near, view_far;
561         float near_v[4] = {0.0f, 0.0f, -1.0f, 1.0f};
562         float far_v[4] = {0.0f, 0.0f,  1.0f, 1.0f};
563         bool is_persp = DRW_viewport_is_persp_get();
564         DRW_viewport_matrix_get(persmat, DRW_MAT_PERS);
565         invert_m4_m4(persinv, persmat);
566         /* FIXME : Get near / far from Draw manager? */
567         DRW_viewport_matrix_get(viewprojmat, DRW_MAT_WIN);
568         invert_m4_m4(projinv, viewprojmat);
569         mul_m4_v4(projinv, near_v);
570         mul_m4_v4(projinv, far_v);
571         view_near = near_v[2];
572         view_far = far_v[2]; /* TODO: Should be a shadow parameter */
573         if (is_persp) {
574                 view_near /= near_v[3];
575                 view_far /= far_v[3];
576         }
577
578         /* Lamps Matrices */
579         float viewmat[4][4], projmat[4][4];
580         int sh_nbr = 1; /* TODO : MSM */
581         int cascade_nbr = la->cascade_count;
582
583         EEVEE_ShadowCascadeData *sh_data = (EEVEE_ShadowCascadeData *)led->storage;
584         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
585         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
586         EEVEE_ShadowCascade *cascade_data = linfo->shadow_cascade_data + sh_data->cascade_id;
587
588         /* The technique consists into splitting
589          * the view frustum into several sub-frustum
590          * that are individually receiving one shadow map */
591
592         float csm_start, csm_end;
593
594         if (is_persp) {
595                 csm_start = view_near;
596                 csm_end = max_ff(view_far, -la->cascade_max_dist);
597                 /* Avoid artifacts */
598                 csm_end = min_ff(view_near, csm_end);
599         }
600         else {
601                 csm_start = -view_far;
602                 csm_end = view_far;
603         }
604
605         /* init near/far */
606         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
607                 cascade_data->split_start[c] = csm_end;
608                 cascade_data->split_end[c] = csm_end;
609         }
610
611         /* Compute split planes */
612         float splits_start_ndc[MAX_CASCADE_NUM];
613         float splits_end_ndc[MAX_CASCADE_NUM];
614
615         {
616                 /* Nearest plane */
617                 float p[4] = {1.0f, 1.0f, csm_start, 1.0f};
618                 /* TODO: we don't need full m4 multiply here */
619                 mul_m4_v4(viewprojmat, p);
620                 splits_start_ndc[0] = p[2];
621                 if (is_persp) {
622                         splits_start_ndc[0] /= p[3];
623                 }
624         }
625
626         {
627                 /* Farthest plane */
628                 float p[4] = {1.0f, 1.0f, csm_end, 1.0f};
629                 /* TODO: we don't need full m4 multiply here */
630                 mul_m4_v4(viewprojmat, p);
631                 splits_end_ndc[cascade_nbr - 1] = p[2];
632                 if (is_persp) {
633                         splits_end_ndc[cascade_nbr - 1] /= p[3];
634                 }
635         }
636
637         cascade_data->split_start[0] = csm_start;
638         cascade_data->split_end[cascade_nbr - 1] = csm_end;
639
640         for (int c = 1; c < cascade_nbr; ++c) {
641                 /* View Space */
642                 float linear_split = LERP(((float)(c) / (float)cascade_nbr), csm_start, csm_end);
643                 float exp_split = csm_start * powf(csm_end / csm_start, (float)(c) / (float)cascade_nbr);
644
645                 if (is_persp) {
646                         cascade_data->split_start[c] = LERP(la->cascade_exponent, linear_split, exp_split);
647                 }
648                 else {
649                         cascade_data->split_start[c] = linear_split;
650                 }
651                 cascade_data->split_end[c-1] = cascade_data->split_start[c];
652
653                 /* Add some overlap for smooth transition */
654                 cascade_data->split_start[c] = LERP(la->cascade_fade, cascade_data->split_end[c-1],
655                                                     (c > 1) ? cascade_data->split_end[c-2] : cascade_data->split_start[0]);
656
657                 /* NDC Space */
658                 {
659                         float p[4] = {1.0f, 1.0f, cascade_data->split_start[c], 1.0f};
660                         /* TODO: we don't need full m4 multiply here */
661                         mul_m4_v4(viewprojmat, p);
662                         splits_start_ndc[c] = p[2];
663
664                         if (is_persp) {
665                                 splits_start_ndc[c] /= p[3];
666                         }
667                 }
668
669                 {
670                         float p[4] = {1.0f, 1.0f, cascade_data->split_end[c-1], 1.0f};
671                         /* TODO: we don't need full m4 multiply here */
672                         mul_m4_v4(viewprojmat, p);
673                         splits_end_ndc[c-1] = p[2];
674
675                         if (is_persp) {
676                                 splits_end_ndc[c-1] /= p[3];
677                         }
678                 }
679         }
680
681         /* Set last cascade split fade distance into the first split_start. */
682         float prev_split = (cascade_nbr > 1) ? cascade_data->split_end[cascade_nbr-2] : cascade_data->split_start[0];
683         cascade_data->split_start[0] = LERP(la->cascade_fade, cascade_data->split_end[cascade_nbr-1], prev_split);
684
685         /* For each cascade */
686         for (int c = 0; c < cascade_nbr; ++c) {
687                 /* Given 8 frustum corners */
688                 float corners[8][4] = {
689                         /* Near Cap */
690                         {-1.0f, -1.0f, splits_start_ndc[c], 1.0f},
691                         { 1.0f, -1.0f, splits_start_ndc[c], 1.0f},
692                         {-1.0f,  1.0f, splits_start_ndc[c], 1.0f},
693                         { 1.0f,  1.0f, splits_start_ndc[c], 1.0f},
694                         /* Far Cap */
695                         {-1.0f, -1.0f, splits_end_ndc[c], 1.0f},
696                         { 1.0f, -1.0f, splits_end_ndc[c], 1.0f},
697                         {-1.0f,  1.0f, splits_end_ndc[c], 1.0f},
698                         { 1.0f,  1.0f, splits_end_ndc[c], 1.0f}
699                 };
700
701                 /* Transform them into world space */
702                 for (int i = 0; i < 8; ++i)     {
703                         mul_m4_v4(persinv, corners[i]);
704                         mul_v3_fl(corners[i], 1.0f / corners[i][3]);
705                         corners[i][3] = 1.0f;
706                 }
707
708
709                 /* Project them into light space */
710                 invert_m4_m4(viewmat, ob->obmat);
711                 normalize_v3(viewmat[0]);
712                 normalize_v3(viewmat[1]);
713                 normalize_v3(viewmat[2]);
714
715                 for (int i = 0; i < 8; ++i)     {
716                         mul_m4_v4(viewmat, corners[i]);
717                 }
718
719                 float center[3];
720                 frustum_min_bounding_sphere(corners, center, &(sh_data->radius[c]));
721
722                 /* Snap projection center to nearest texel to cancel shimmering. */
723                 float shadow_origin[2], shadow_texco[2];
724                 mul_v2_v2fl(shadow_origin, center, linfo->shadow_size / (2.0f * sh_data->radius[c])); /* Light to texture space. */
725
726                 /* Find the nearest texel. */
727                 shadow_texco[0] = round(shadow_origin[0]);
728                 shadow_texco[1] = round(shadow_origin[1]);
729
730                 /* Compute offset. */
731                 sub_v2_v2(shadow_texco, shadow_origin);
732                 mul_v2_fl(shadow_texco, (2.0f * sh_data->radius[c]) / linfo->shadow_size); /* Texture to light space. */
733
734                 /* Apply offset. */
735                 add_v2_v2(center, shadow_texco);
736
737                 /* Expand the projection to cover frustum range */
738                 orthographic_m4(projmat,
739                                 center[0] - sh_data->radius[c],
740                                 center[0] + sh_data->radius[c],
741                                 center[1] - sh_data->radius[c],
742                                 center[1] + sh_data->radius[c],
743                                 la->clipsta, la->clipend);
744
745                 mul_m4_m4m4(sh_data->viewprojmat[c], projmat, viewmat);
746                 mul_m4_m4m4(cascade_data->shadowmat[c], texcomat, sh_data->viewprojmat[c]);
747         }
748
749         ubo_data->bias = 0.05f * la->bias;
750         ubo_data->near = la->clipsta;
751         ubo_data->far = la->clipend;
752         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
753
754         evli->shadowid = (float)(sh_data->shadow_id);
755         ubo_data->shadow_start = (float)(sh_data->layer_id);
756         ubo_data->data_start = (float)(sh_data->cascade_id);
757         ubo_data->multi_shadow_count = (float)(sh_nbr);
758
759         ubo_data->contact_dist = (la->mode & LA_SHAD_CONTACT) ? la->contact_dist : 0.0f;
760         ubo_data->contact_bias = 0.05f * la->contact_bias;
761         ubo_data->contact_spread = la->contact_spread;
762         ubo_data->contact_thickness = la->contact_thickness;
763 }
764
765 /* Used for checking if object is inside the shadow volume. */
766 static bool cube_bbox_intersect(const float cube_center[3], float cube_half_dim, const BoundBox *bb, float (*obmat)[4])
767 {
768         float min[3], max[4], tmp[4][4];
769         unit_m4(tmp);
770         translate_m4(tmp, -cube_center[0], -cube_center[1], -cube_center[2]);
771         mul_m4_m4m4(tmp, tmp, obmat);
772
773         /* Just simple AABB intersection test in world space. */
774         INIT_MINMAX(min, max);
775         for (int i = 0; i < 8; ++i) {
776                 float vec[3];
777                 copy_v3_v3(vec, bb->vec[i]);
778                 mul_m4_v3(tmp, vec);
779                 minmax_v3v3_v3(min, max, vec);
780         }
781
782     if (MAX3(max[0], max[1], max[2]) < -cube_half_dim) return false;
783     if (MIN3(min[0], min[1], min[2]) >  cube_half_dim) return false;
784
785         return true;
786 }
787
788 static ShadowCaster *search_object_in_list(ListBase *list, Object *ob)
789 {
790         for (ShadowCaster *ldata = list->first; ldata; ldata = ldata->next) {
791                 if (ldata->ob == ob)
792                         return ldata;
793         }
794
795         return NULL;
796 }
797
798 static void delete_pruned_shadowcaster(EEVEE_LampEngineData *led)
799 {
800         ShadowCaster *next;
801         for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = next) {
802                 next = ldata->next;
803                 if (ldata->prune == true) {
804                         led->need_update = true;
805                         BLI_freelinkN(&led->shadow_caster_list, ldata);
806                 }
807         }
808 }
809
810 static void light_tag_shadow_update(Object *lamp, Object *ob)
811 {
812         Lamp *la = lamp->data;
813         EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
814
815         bool is_inside_range = cube_bbox_intersect(lamp->obmat[3], la->clipend, BKE_object_boundbox_get(ob), ob->obmat);
816         ShadowCaster *ldata = search_object_in_list(&led->shadow_caster_list, ob);
817
818         if (is_inside_range) {
819                 if (ldata == NULL) {
820                         /* Object was not a shadow caster previously but is now. Add it. */
821                         ldata = MEM_callocN(sizeof(ShadowCaster), "ShadowCaster");
822                         ldata->ob = ob;
823                         BLI_addtail(&led->shadow_caster_list, ldata);
824                         led->need_update = true;
825                 }
826                 else {
827                         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_get(ob);
828                         if (oedata->need_update) {
829                                 led->need_update = true;
830                         }
831                 }
832                 ldata->prune = false;
833         }
834         else if (ldata != NULL) {
835                 /* Object was a shadow caster previously and is not anymore. Remove it. */
836                 led->need_update = true;
837                 BLI_freelinkN(&led->shadow_caster_list, ldata);
838         }
839 }
840
841 static void eevee_lights_shcaster_updated(EEVEE_SceneLayerData *sldata, Object *ob)
842 {
843         Object *lamp;
844         EEVEE_LampsInfo *linfo = sldata->lamps;
845
846         /* Iterate over all shadow casting lamps to see if
847          * each of them needs update because of this object */
848         for (int i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
849                 light_tag_shadow_update(lamp, ob);
850         }
851 }
852
853 void EEVEE_lights_update(EEVEE_SceneLayerData *sldata)
854 {
855         EEVEE_LampsInfo *linfo = sldata->lamps;
856         Object *ob;
857         int i;
858
859         /* Prune shadow casters to remove if object does not exists anymore (unprune them if object exists) */
860         Object *lamp;
861         for (i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
862                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
863
864                 if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
865                         led->need_update = true;
866                 }
867
868                 for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = ldata->next) {
869                         ldata->prune = true;
870                 }
871         }
872
873         for (LinkData *ldata = sldata->shadow_casters.first; ldata; ldata = ldata->next) {
874                 eevee_lights_shcaster_updated(sldata, ldata->data);
875         }
876
877         for (i = 0; (ob = linfo->light_ref[i]) && (i < MAX_LIGHT); i++) {
878                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
879                 eevee_light_setup(ob, linfo, led);
880         }
881
882         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
883                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
884                 eevee_shadow_cube_setup(ob, linfo, led);
885                 delete_pruned_shadowcaster(led);
886         }
887 }
888
889 /* this refresh lamps shadow buffers */
890 void EEVEE_draw_shadows(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
891 {
892         EEVEE_LampsInfo *linfo = sldata->lamps;
893         Object *ob;
894         int i;
895         float clear_col[4] = {FLT_MAX};
896
897         /* Cube Shadow Maps */
898         DRW_stats_group_start("Cube Shadow Maps");
899         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cube_target, 0, 0);
900         /* Render each shadow to one layer of the array */
901         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
902                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
903                 Lamp *la = (Lamp *)ob->data;
904
905                 float cube_projmat[4][4];
906                 perspective_m4(cube_projmat, -la->clipsta, la->clipsta, -la->clipsta, la->clipsta, la->clipsta, la->clipend);
907
908                 if (led->need_update) {
909                         EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
910                         EEVEE_ShadowCubeData *evscd = (EEVEE_ShadowCubeData *)led->storage;
911
912                         srd->clip_near = la->clipsta;
913                         srd->clip_far = la->clipend;
914                         copy_v3_v3(srd->position, ob->obmat[3]);
915                         for (int j = 0; j < 6; j++) {
916                                 float tmp[4][4];
917
918                                 unit_m4(tmp);
919                                 negate_v3_v3(tmp[3], ob->obmat[3]);
920                                 mul_m4_m4m4(srd->viewmat[j], cubefacemat[j], tmp);
921
922                                 mul_m4_m4m4(srd->shadowmat[j], cube_projmat, srd->viewmat[j]);
923                         }
924                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
925
926                         DRW_framebuffer_bind(sldata->shadow_target_fb);
927                         DRW_framebuffer_clear(true, true, false, clear_col, 1.0f);
928
929                         /* Render shadow cube */
930                         DRW_draw_pass(psl->shadow_cube_pass);
931
932                         /* 0.001f is arbitrary, but it should be relatively small so that filter size is not too big. */
933                         float filter_texture_size = la->soft * 0.001f;
934                         float filter_pixel_size = ceil(filter_texture_size / linfo->shadow_render_data.cube_texel_size);
935                         linfo->filter_size = linfo->shadow_render_data.cube_texel_size * ((filter_pixel_size > 1.0f) ? 1.5f : 0.0f);
936
937                         /* TODO: OPTI: Filter all faces in one/two draw call */
938                         for (linfo->current_shadow_face = 0;
939                              linfo->current_shadow_face < 6;
940                              linfo->current_shadow_face++)
941                         {
942                                 /* Copy using a small 3x3 box filter */
943                                 DRW_framebuffer_cubeface_attach(sldata->shadow_store_fb, sldata->shadow_cube_blur, 0, linfo->current_shadow_face, 0);
944                                 DRW_framebuffer_bind(sldata->shadow_store_fb);
945                                 DRW_draw_pass(psl->shadow_cube_copy_pass);
946                                 DRW_framebuffer_texture_detach(sldata->shadow_cube_blur);
947                         }
948
949                         /* Push it to shadowmap array */
950
951                         /* Adjust constants if concentric samples change. */
952                         const float max_filter_size = 7.5f;
953                         const float previous_box_filter_size = 9.0f; /* Dunno why but that works. */
954                         const int max_sample = 256;
955
956                         if (filter_pixel_size > 2.0f) {
957                                 linfo->filter_size = linfo->shadow_render_data.cube_texel_size * max_filter_size * previous_box_filter_size;
958                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
959                                 /* Compute number of concentric samples. Depends directly on filter size. */
960                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
961                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
962                         }
963                         else {
964                                 linfo->filter_size = 0.0f;
965                                 srd->shadow_samples_ct = 4;
966                         }
967                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
968                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
969
970                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, evscd->layer_id, 0);
971                         DRW_framebuffer_bind(sldata->shadow_store_fb);
972                         DRW_draw_pass(psl->shadow_cube_store_pass);
973
974                         led->need_update = false;
975                 }
976         }
977         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
978
979         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
980         DRW_stats_group_end();
981
982         /* Cascaded Shadow Maps */
983         DRW_stats_group_start("Cascaded Shadow Maps");
984         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cascade_target, 0, 0);
985         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
986                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
987                 Lamp *la = (Lamp *)ob->data;
988
989                 EEVEE_ShadowCascadeData *evscd = (EEVEE_ShadowCascadeData *)led->storage;
990                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
991
992                 eevee_shadow_cascade_setup(ob, linfo, led);
993
994                 srd->clip_near = la->clipsta;
995                 srd->clip_far = la->clipend;
996                 for (int j = 0; j < la->cascade_count; ++j) {
997                         copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
998                 }
999                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1000
1001                 DRW_framebuffer_bind(sldata->shadow_target_fb);
1002                 DRW_framebuffer_clear(false, true, false, NULL, 1.0);
1003
1004                 /* Render shadow cascades */
1005                 DRW_draw_pass(psl->shadow_cascade_pass);
1006
1007                 /* TODO: OPTI: Filter all cascade in one/two draw call */
1008                 for (linfo->current_shadow_cascade = 0;
1009                      linfo->current_shadow_cascade < la->cascade_count;
1010                      ++linfo->current_shadow_cascade)
1011                 {
1012                         /* 0.01f factor to convert to percentage */
1013                         float filter_texture_size = la->soft * 0.01f / evscd->radius[linfo->current_shadow_cascade];
1014                         float filter_pixel_size = ceil(linfo->shadow_size * filter_texture_size);
1015
1016                         /* Copy using a small 3x3 box filter */
1017                         linfo->filter_size = linfo->shadow_render_data.stored_texel_size * ((filter_pixel_size > 1.0f) ? 1.0f : 0.0f);
1018                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_cascade_blur, 0, linfo->current_shadow_cascade, 0);
1019                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1020                         DRW_draw_pass(psl->shadow_cascade_copy_pass);
1021                         DRW_framebuffer_texture_detach(sldata->shadow_cascade_blur);
1022
1023                         /* Push it to shadowmap array and blur more */
1024
1025                         /* Adjust constants if concentric samples change. */
1026                         const float max_filter_size = 7.5f;
1027                         const float previous_box_filter_size = 3.2f; /* Arbitrary: less banding */
1028                         const int max_sample = 256;
1029
1030                         if (filter_pixel_size > 2.0f) {
1031                                 linfo->filter_size = linfo->shadow_render_data.stored_texel_size * max_filter_size * previous_box_filter_size;
1032                                 filter_pixel_size = max_ff(0.0f, filter_pixel_size - 3.0f);
1033                                 /* Compute number of concentric samples. Depends directly on filter size. */
1034                                 float pix_size_sqr = filter_pixel_size * filter_pixel_size;
1035                                 srd->shadow_samples_ct = min_ii(max_sample, 4 + 8 * (int)filter_pixel_size + 4 * (int)(pix_size_sqr));
1036                         }
1037                         else {
1038                                 linfo->filter_size = 0.0f;
1039                                 srd->shadow_samples_ct = 4;
1040                         }
1041                         srd->shadow_inv_samples_ct = 1.0f / (float)srd->shadow_samples_ct;
1042                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
1043
1044                         int layer = evscd->layer_id + linfo->current_shadow_cascade;
1045                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, layer, 0);
1046                         DRW_framebuffer_bind(sldata->shadow_store_fb);
1047                         DRW_draw_pass(psl->shadow_cascade_store_pass);
1048                 }
1049         }
1050
1051         DRW_framebuffer_texture_detach(sldata->shadow_cascade_target);
1052         DRW_stats_group_end();
1053
1054         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
1055         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_data); /* Update all data at once */
1056 }
1057
1058 void EEVEE_lights_free(void)
1059 {
1060         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
1061         for (int i = 0; i < SHADOW_METHOD_MAX; ++i) {
1062                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_sh[i]);
1063                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_sh[i]);
1064                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cube_sh[i]);
1065                 DRW_SHADER_FREE_SAFE(e_data.shadow_copy_cascade_sh[i]);
1066         }
1067 }