Eevee: Add Cascaded Shadow Map support with filtering.
[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 "BKE_object.h"
29
30 #include "eevee_engine.h"
31 #include "eevee_private.h"
32
33 /* Theses are the structs stored inside Objects.
34  * It works with even if the object is in multiple layers
35  * because we don't get the same "Object *" for each layer. */
36 typedef struct EEVEE_LightData {
37         short light_id, shadow_id;
38 } EEVEE_LightData;
39
40 typedef struct EEVEE_ShadowCubeData {
41         short light_id, shadow_id, cube_id, layer_id;
42 } EEVEE_ShadowCubeData;
43
44 typedef struct EEVEE_ShadowCascadeData {
45         short light_id, shadow_id, cascade_id, layer_id;
46         float viewprojmat[MAX_CASCADE_NUM][4][4]; /* World->Lamp->NDC : used for rendering the shadow map. */
47         float radius[MAX_CASCADE_NUM];
48 } EEVEE_ShadowCascadeData;
49
50 typedef struct ShadowCaster {
51         struct ShadowCaster *next, *prev;
52         void *ob;
53         bool prune;
54 } ShadowCaster;
55
56 static struct {
57         struct GPUShader *shadow_sh;
58         struct GPUShader *shadow_store_cube_sh[SHADOW_METHOD_MAX];
59         struct GPUShader *shadow_store_cascade_sh[SHADOW_METHOD_MAX];
60 } e_data = {NULL}; /* Engine data */
61
62 extern char datatoc_shadow_vert_glsl[];
63 extern char datatoc_shadow_geom_glsl[];
64 extern char datatoc_shadow_frag_glsl[];
65 extern char datatoc_shadow_store_frag_glsl[];
66
67 /* *********** FUNCTIONS *********** */
68
69 void EEVEE_lights_init(EEVEE_SceneLayerData *sldata)
70 {
71         const unsigned int shadow_ubo_size = sizeof(EEVEE_Shadow) * MAX_SHADOW +
72                                              sizeof(EEVEE_ShadowCube) * MAX_SHADOW_CUBE +
73                                              sizeof(EEVEE_ShadowCascade) * MAX_SHADOW_CASCADE;
74
75         const DRWContextState *draw_ctx = DRW_context_state_get();
76         SceneLayer *scene_layer = draw_ctx->scene_layer;
77         IDProperty *props = BKE_scene_layer_engine_evaluated_get(scene_layer, COLLECTION_MODE_NONE, RE_engine_id_BLENDER_EEVEE);
78
79         if (!e_data.shadow_sh) {
80                 e_data.shadow_sh = DRW_shader_create(
81                         datatoc_shadow_vert_glsl, datatoc_shadow_geom_glsl, datatoc_shadow_frag_glsl, NULL);
82
83                 e_data.shadow_store_cube_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_store_frag_glsl, "#define ESM\n");
84                 e_data.shadow_store_cascade_sh[SHADOW_ESM] = DRW_shader_create_fullscreen(datatoc_shadow_store_frag_glsl, "#define ESM\n"
85                                                                                                                           "#define CSM\n");
86
87                 e_data.shadow_store_cube_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_store_frag_glsl, "#define VSM\n");
88                 e_data.shadow_store_cascade_sh[SHADOW_VSM] = DRW_shader_create_fullscreen(datatoc_shadow_store_frag_glsl, "#define VSM\n"
89                                                                                                                           "#define CSM\n");
90         }
91
92         if (!sldata->lamps) {
93                 sldata->lamps              = MEM_callocN(sizeof(EEVEE_LampsInfo), "EEVEE_LampsInfo");
94                 sldata->light_ubo          = DRW_uniformbuffer_create(sizeof(EEVEE_Light) * MAX_LIGHT, NULL);
95                 sldata->shadow_ubo         = DRW_uniformbuffer_create(shadow_ubo_size, NULL);
96                 sldata->shadow_render_ubo  = DRW_uniformbuffer_create(sizeof(EEVEE_ShadowRender), NULL);
97         }
98
99         int sh_method = BKE_collection_engine_property_value_get_int(props, "shadow_method");
100         int sh_size = BKE_collection_engine_property_value_get_int(props, "shadow_size");
101         int sh_high_bitdepth = BKE_collection_engine_property_value_get_int(props, "shadow_high_bitdepth");
102
103         EEVEE_LampsInfo *linfo = sldata->lamps;
104         if ((linfo->shadow_size != sh_size) ||
105                 (linfo->shadow_method != sh_method) ||
106                 (linfo->shadow_high_bitdepth != sh_high_bitdepth))
107         {
108                 BLI_assert((sh_size > 0) && (sh_size <= 8192));
109                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
110                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cube_target);
111                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_cascade_target);
112
113                 linfo->shadow_high_bitdepth = sh_high_bitdepth;
114                 linfo->shadow_method = sh_method;
115                 linfo->shadow_size = sh_size;
116                 linfo->shadow_render_data.stored_texel_size = 1.0 / (float)linfo->shadow_size;
117
118                 /* Compute adequate size for the cubemap render target.
119                  * The 3.0f factor is here to make sure there is no under sampling between
120                  * the octahedron mapping and the cubemap. */
121                 int new_cube_target_size = (int)ceil(sqrt((float)(sh_size * sh_size) / 6.0f) * 3.0f);
122
123                 CLAMP(new_cube_target_size, 1, 4096);
124
125                 linfo->shadow_cube_target_size = new_cube_target_size;
126                 linfo->shadow_render_data.cube_texel_size = 1.0 / (float)linfo->shadow_cube_target_size;
127         }
128 }
129
130 void EEVEE_lights_cache_init(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
131 {
132         EEVEE_LampsInfo *linfo = sldata->lamps;
133
134         linfo->num_light = 0;
135         linfo->num_layer = 0;
136         linfo->gpu_cube_ct = linfo->gpu_cascade_ct = linfo->gpu_shadow_ct = 0;
137         linfo->cpu_cube_ct = linfo->cpu_cascade_ct = 0;
138         memset(linfo->light_ref, 0, sizeof(linfo->light_ref));
139         memset(linfo->shadow_cube_ref, 0, sizeof(linfo->shadow_cube_ref));
140         memset(linfo->shadow_cascade_ref, 0, sizeof(linfo->shadow_cascade_ref));
141
142         {
143                 psl->shadow_cube_store_pass = DRW_pass_create("Shadow Storage Pass", DRW_STATE_WRITE_COLOR);
144
145                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cube_sh[linfo->shadow_method], psl->shadow_cube_store_pass);
146                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cube_target);
147                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
148                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
149                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
150         }
151
152         {
153                 psl->shadow_cascade_store_pass = DRW_pass_create("Shadow Cascade Storage Pass", DRW_STATE_WRITE_COLOR);
154
155                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_cascade_sh[linfo->shadow_method], psl->shadow_cascade_store_pass);
156                 DRW_shgroup_uniform_buffer(grp, "shadowTexture", &sldata->shadow_cascade_target);
157                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
158                 DRW_shgroup_uniform_int(grp, "cascadeId", &linfo->current_shadow_cascade, 1);
159                 DRW_shgroup_uniform_float(grp, "shadowFilterSize", &linfo->filter_size, 1);
160                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
161         }
162
163         {
164                 psl->shadow_cube_pass = DRW_pass_create("Shadow Cube Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
165         }
166
167         {
168                 psl->shadow_cascade_pass = DRW_pass_create("Shadow Cascade Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
169         }
170
171         /* Reset shadow casters list */
172         BLI_freelistN(&sldata->shadow_casters);
173 }
174
175 void EEVEE_lights_cache_add(EEVEE_SceneLayerData *sldata, Object *ob)
176 {
177         EEVEE_LampsInfo *linfo = sldata->lamps;
178
179         /* Step 1 find all lamps in the scene and setup them */
180         if (linfo->num_light > MAX_LIGHT) {
181                 printf("Too much lamps in the scene !!!\n");
182                 linfo->num_light = MAX_LIGHT;
183         }
184         else {
185                 Lamp *la = (Lamp *)ob->data;
186                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
187
188                 if ((ob->deg_update_flag & DEG_RUNTIME_DATA_UPDATE) != 0) {
189                         led->need_update = true;
190                 }
191
192                 MEM_SAFE_FREE(led->storage);
193
194                 if (la->mode & (LA_SHAD_BUF | LA_SHAD_RAY)) {
195                         if (la->type == LA_SUN) {
196                                 int sh_nbr = 1; /* TODO : MSM */
197                                 int cascade_nbr = MAX_CASCADE_NUM; /* TODO : Custom cascade number */
198
199                                 if ((linfo->gpu_cascade_ct + sh_nbr) <= MAX_SHADOW_CASCADE) {
200                                         /* Save Light object. */
201                                         linfo->shadow_cascade_ref[linfo->cpu_cascade_ct] = ob;
202
203                                         /* Create storage and store indices. */
204                                         EEVEE_ShadowCascadeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCascadeData), "EEVEE_ShadowCascadeData");
205                                         data->shadow_id = linfo->gpu_shadow_ct;
206                                         data->cascade_id = linfo->gpu_cascade_ct;
207                                         data->layer_id = linfo->num_layer;
208                                         led->storage = data;
209
210                                         /* Increment indices. */
211                                         linfo->gpu_shadow_ct += 1;
212                                         linfo->gpu_cascade_ct += sh_nbr;
213                                         linfo->num_layer += sh_nbr * cascade_nbr;
214
215                                         linfo->cpu_cascade_ct += 1;
216                                 }
217                         }
218                         else if (la->type == LA_SPOT || la->type == LA_LOCAL || la->type == LA_AREA) {
219                                 int sh_nbr = 1; /* TODO : MSM */
220
221                                 if ((linfo->gpu_cube_ct + sh_nbr) <= MAX_SHADOW_CUBE) {
222                                         /* Save Light object. */
223                                         linfo->shadow_cube_ref[linfo->cpu_cube_ct] = ob;
224
225                                         /* Create storage and store indices. */
226                                         EEVEE_ShadowCubeData *data = MEM_mallocN(sizeof(EEVEE_ShadowCubeData), "EEVEE_ShadowCubeData");
227                                         data->shadow_id = linfo->gpu_shadow_ct;
228                                         data->cube_id = linfo->gpu_cube_ct;
229                                         data->layer_id = linfo->num_layer;
230                                         led->storage = data;
231
232                                         /* Increment indices. */
233                                         linfo->gpu_shadow_ct += 1;
234                                         linfo->gpu_cube_ct += sh_nbr;
235                                         linfo->num_layer += sh_nbr;
236
237                                         linfo->cpu_cube_ct += 1;
238                                 }
239                         }
240                 }
241
242                 /* Default light without shadows */
243                 if (!led->storage) {
244                         led->storage = MEM_mallocN(sizeof(EEVEE_LightData), "EEVEE_LightData");
245                         ((EEVEE_LightData *)led->storage)->shadow_id = -1;
246                 }
247
248                 ((EEVEE_LightData *)led->storage)->light_id = linfo->num_light;
249                 linfo->light_ref[linfo->num_light] = ob;
250                 linfo->num_light++;
251         }
252 }
253
254 /* Add a shadow caster to the shadowpasses */
255 void EEVEE_lights_cache_shcaster_add(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct Gwn_Batch *geom, float (*obmat)[4])
256 {
257         DRWShadingGroup *grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cube_pass, geom);
258         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
259         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
260
261         for (int i = 0; i < 6; ++i)
262                 DRW_shgroup_call_dynamic_add_empty(grp);
263
264         grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cascade_pass, geom);
265         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
266         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
267
268         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
269                 DRW_shgroup_call_dynamic_add_empty(grp);
270 }
271
272 void EEVEE_lights_cache_shcaster_material_add(
273         EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct GPUMaterial *gpumat, struct Gwn_Batch *geom, float (*obmat)[4], float *alpha_threshold)
274 {
275         DRWShadingGroup *grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cube_pass, geom);
276
277         if (grp == NULL) return;
278
279         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
280         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
281
282         if (alpha_threshold != NULL)
283                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
284
285         for (int i = 0; i < 6; ++i)
286                 DRW_shgroup_call_dynamic_add_empty(grp);
287
288         grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cascade_pass, geom);
289         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
290         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
291
292         if (alpha_threshold != NULL)
293                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
294
295         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
296                 DRW_shgroup_call_dynamic_add_empty(grp);
297 }
298
299 void EEVEE_lights_cache_finish(EEVEE_SceneLayerData *sldata)
300 {
301         EEVEE_LampsInfo *linfo = sldata->lamps;
302         DRWTextureFormat shadow_pool_format;
303
304         /* Setup enough layers. */
305         /* Free textures if number mismatch. */
306         if (linfo->num_layer != linfo->cache_num_layer) {
307                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_pool);
308                 linfo->cache_num_layer = linfo->num_layer;
309                 linfo->update_flag |= LIGHT_UPDATE_SHADOW_CUBE;
310         }
311
312         switch (linfo->shadow_method) {
313                 case SHADOW_ESM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_R_32 : DRW_TEX_R_16); break;
314                 case SHADOW_VSM: shadow_pool_format = ((linfo->shadow_high_bitdepth) ? DRW_TEX_RG_32 : DRW_TEX_RG_16); break;
315                 default:
316                         BLI_assert(!"Incorrect Shadow Method");
317                         break;
318         }
319
320         if (!sldata->shadow_cube_target) {
321                 /* TODO render everything on the same 2d render target using clip planes and no Geom Shader. */
322                 /* Cubemaps */
323                 sldata->shadow_cube_target = DRW_texture_create_cube(linfo->shadow_cube_target_size, DRW_TEX_DEPTH_24, 0, NULL);
324         }
325
326         if (!sldata->shadow_cascade_target) {
327                 /* CSM */
328                 sldata->shadow_cascade_target = DRW_texture_create_2D_array(
329                         linfo->shadow_size, linfo->shadow_size, MAX_CASCADE_NUM, DRW_TEX_DEPTH_24, 0, NULL);
330         }
331
332         /* Initialize Textures Array first so DRW_framebuffer_init just bind them. */
333         if (!sldata->shadow_pool) {
334                 /* All shadows fit in this array */
335                 sldata->shadow_pool = DRW_texture_create_2D_array(
336                         linfo->shadow_size, linfo->shadow_size, max_ff(1, linfo->num_layer),
337                         shadow_pool_format, DRW_TEX_FILTER, NULL);
338         }
339
340         /* Render FB */
341         DRWFboTexture tex_cascade = {&sldata->shadow_cube_target, DRW_TEX_DEPTH_24, 0};
342         DRW_framebuffer_init(&sldata->shadow_target_fb, &draw_engine_eevee_type,
343                              linfo->shadow_size, linfo->shadow_size,
344                              &tex_cascade, 1);
345
346         /* Storage FB */
347         DRWFboTexture tex_pool = {&sldata->shadow_pool, shadow_pool_format, DRW_TEX_FILTER};
348         DRW_framebuffer_init(&sldata->shadow_store_fb, &draw_engine_eevee_type,
349                              linfo->shadow_size, linfo->shadow_size,
350                              &tex_pool, 1);
351
352         /* Restore */
353         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
354
355         /* Update Lamps UBOs. */
356         EEVEE_lights_update(sldata);
357 }
358
359 /* Update buffer with lamp data */
360 static void eevee_light_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
361 {
362         /* TODO only update if data changes */
363         EEVEE_LightData *evld = led->storage;
364         EEVEE_Light *evli = linfo->light_data + evld->light_id;
365         Lamp *la = (Lamp *)ob->data;
366         float mat[4][4], scale[3], power;
367
368         /* Position */
369         copy_v3_v3(evli->position, ob->obmat[3]);
370
371         /* Color */
372         copy_v3_v3(evli->color, &la->r);
373
374         /* Influence Radius */
375         evli->dist = la->dist;
376
377         /* Vectors */
378         normalize_m4_m4_ex(mat, ob->obmat, scale);
379         copy_v3_v3(evli->forwardvec, mat[2]);
380         normalize_v3(evli->forwardvec);
381         negate_v3(evli->forwardvec);
382
383         copy_v3_v3(evli->rightvec, mat[0]);
384         normalize_v3(evli->rightvec);
385
386         copy_v3_v3(evli->upvec, mat[1]);
387         normalize_v3(evli->upvec);
388
389         /* Spot size & blend */
390         if (la->type == LA_SPOT) {
391                 evli->sizex = scale[0] / scale[2];
392                 evli->sizey = scale[1] / scale[2];
393                 evli->spotsize = cosf(la->spotsize * 0.5f);
394                 evli->spotblend = (1.0f - evli->spotsize) * la->spotblend;
395                 evli->radius = max_ff(0.001f, la->area_size);
396         }
397         else if (la->type == LA_AREA) {
398                 evli->sizex = max_ff(0.0001f, la->area_size * scale[0] * 0.5f);
399                 if (la->area_shape == LA_AREA_RECT) {
400                         evli->sizey = max_ff(0.0001f, la->area_sizey * scale[1] * 0.5f);
401                 }
402                 else {
403                         evli->sizey = max_ff(0.0001f, la->area_size * scale[1] * 0.5f);
404                 }
405         }
406         else {
407                 evli->radius = max_ff(0.001f, la->area_size);
408         }
409
410         /* Make illumination power constant */
411         if (la->type == LA_AREA) {
412                 power = 1.0f / (evli->sizex * evli->sizey * 4.0f * M_PI) /* 1/(w*h*Pi) */
413                         * 80.0f; /* XXX : Empirical, Fit cycles power */
414         }
415         else if (la->type == LA_SPOT || la->type == LA_LOCAL) {
416                 power = 1.0f / (4.0f * evli->radius * evli->radius * M_PI * M_PI) /* 1/(4*r²*Pi²) */
417                         * M_PI * M_PI * M_PI * 10.0; /* XXX : Empirical, Fit cycles power */
418
419                 /* for point lights (a.k.a radius == 0.0) */
420                 // power = M_PI * M_PI * 0.78; /* XXX : Empirical, Fit cycles power */
421         }
422         else {
423                 power = 1.0f;
424         }
425         mul_v3_fl(evli->color, power * la->energy);
426
427         /* Lamp Type */
428         evli->lamptype = (float)la->type;
429
430         /* No shadow by default */
431         evli->shadowid = -1.0f;
432 }
433
434 static void eevee_shadow_cube_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
435 {
436         EEVEE_ShadowCubeData *sh_data = (EEVEE_ShadowCubeData *)led->storage;
437         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
438         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
439         EEVEE_ShadowCube *cube_data = linfo->shadow_cube_data + sh_data->cube_id;
440         Lamp *la = (Lamp *)ob->data;
441
442         int sh_nbr = 1; /* TODO: MSM */
443
444         for (int i = 0; i < sh_nbr; ++i) {
445                 /* TODO : choose MSM sample point here. */
446                 copy_v3_v3(cube_data->position, ob->obmat[3]);
447         }
448
449         ubo_data->bias = 0.05f * la->bias;
450         ubo_data->near = la->clipsta;
451         ubo_data->far = la->clipend;
452         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
453
454         evli->shadowid = (float)(sh_data->shadow_id);
455         ubo_data->shadow_start = (float)(sh_data->layer_id);
456         ubo_data->data_start = (float)(sh_data->cube_id);
457         ubo_data->multi_shadow_count = (float)(sh_nbr);
458 }
459
460 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
461
462 static void frustum_min_bounding_sphere(const float corners[8][4], float r_center[3], float *r_radius)
463 {
464 #if 0 /* Simple solution but waist too much space. */
465         float minvec[3], maxvec[3];
466
467         /* compute the bounding box */
468         INIT_MINMAX(minvec, maxvec);
469         for (int i = 0; i < 8; ++i)     {
470                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
471         }
472
473         /* compute the bounding sphere of this box */
474         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
475         add_v3_v3v3(r_center, minvec, maxvec);
476         mul_v3_fl(r_center, 0.5f);
477 #else
478         /* Make the bouding sphere always centered on the front diagonal */
479         add_v3_v3v3(r_center, corners[4], corners[7]);
480         mul_v3_fl(r_center, 0.5f);
481         *r_radius = len_v3v3(corners[0], r_center);
482
483         /* Search the largest distance between the sphere center
484          * and the front plane corners. */
485         for (int i = 0; i < 4; ++i) {
486                 float rad = len_v3v3(corners[4+i], r_center);
487                 if (rad > *r_radius) {
488                         *r_radius = rad;
489                 }
490         }
491 #endif
492 }
493
494 static void eevee_shadow_cascade_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
495 {
496         /* Camera Matrices */
497         float persmat[4][4], persinv[4][4];
498         float viewprojmat[4][4], projinv[4][4];
499         float near, far;
500         float near_v[4] = {0.0f, 0.0f, -1.0f, 1.0f};
501         float far_v[4] = {0.0f, 0.0f,  1.0f, 1.0f};
502         bool is_persp = DRW_viewport_is_persp_get();
503         DRW_viewport_matrix_get(persmat, DRW_MAT_PERS);
504         invert_m4_m4(persinv, persmat);
505         /* FIXME : Get near / far from Draw manager? */
506         DRW_viewport_matrix_get(viewprojmat, DRW_MAT_WIN);
507         invert_m4_m4(projinv, viewprojmat);
508         mul_m4_v4(projinv, near_v);
509         mul_m4_v4(projinv, far_v);
510         near = near_v[2];
511         far = far_v[2]; /* TODO: Should be a shadow parameter */
512         if (is_persp) {
513                 near /= near_v[3];
514                 far /= far_v[3];
515         }
516
517         /* Lamps Matrices */
518         float viewmat[4][4], projmat[4][4];
519         int sh_nbr = 1; /* TODO : MSM */
520         int cascade_nbr = MAX_CASCADE_NUM; /* TODO : Custom cascade number */
521
522         EEVEE_ShadowCascadeData *sh_data = (EEVEE_ShadowCascadeData *)led->storage;
523         EEVEE_Light *evli = linfo->light_data + sh_data->light_id;
524         EEVEE_Shadow *ubo_data = linfo->shadow_data + sh_data->shadow_id;
525         EEVEE_ShadowCascade *cascade_data = linfo->shadow_cascade_data + sh_data->cascade_id;
526         Lamp *la = (Lamp *)ob->data;
527
528         /* The technique consists into splitting
529          * the view frustum into several sub-frustum
530          * that are individually receiving one shadow map */
531
532         /* init near/far */
533         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
534                 cascade_data->split[c] = far;
535         }
536
537         /* Compute split planes */
538         float splits_ndc[MAX_CASCADE_NUM + 1];
539         splits_ndc[0] = -1.0f;
540         splits_ndc[cascade_nbr] = 1.0f;
541         for (int c = 1; c < cascade_nbr; ++c) {
542                 const float lambda = 0.8f; /* TODO : Parameter */
543
544                 /* View Space */
545                 float linear_split = LERP(((float)(c) / (float)cascade_nbr), near, far);
546                 float exp_split = near * powf(far / near, (float)(c) / (float)cascade_nbr);
547
548                 if (is_persp) {
549                         cascade_data->split[c-1] = LERP(lambda, linear_split, exp_split);
550                 }
551                 else {
552                         cascade_data->split[c-1] = linear_split;
553                 }
554
555                 /* NDC Space */
556                 float p[4] = {1.0f, 1.0f, cascade_data->split[c-1], 1.0f};
557                 mul_m4_v4(viewprojmat, p);
558                 splits_ndc[c] = p[2];
559
560                 if (is_persp) {
561                         splits_ndc[c] /= p[3];
562                 }
563         }
564
565         /* For each cascade */
566         for (int c = 0; c < cascade_nbr; ++c) {
567                 /* Given 8 frustum corners */
568                 float corners[8][4] = {
569                         /* Near Cap */
570                         {-1.0f, -1.0f, splits_ndc[c], 1.0f},
571                         { 1.0f, -1.0f, splits_ndc[c], 1.0f},
572                         {-1.0f,  1.0f, splits_ndc[c], 1.0f},
573                         { 1.0f,  1.0f, splits_ndc[c], 1.0f},
574                         /* Far Cap */
575                         {-1.0f, -1.0f, splits_ndc[c+1], 1.0f},
576                         { 1.0f, -1.0f, splits_ndc[c+1], 1.0f},
577                         {-1.0f,  1.0f, splits_ndc[c+1], 1.0f},
578                         { 1.0f,  1.0f, splits_ndc[c+1], 1.0f}
579                 };
580
581                 /* Transform them into world space */
582                 for (int i = 0; i < 8; ++i)     {
583                         mul_m4_v4(persinv, corners[i]);
584                         mul_v3_fl(corners[i], 1.0f / corners[i][3]);
585                         corners[i][3] = 1.0f;
586                 }
587
588                 /* Project them into light space */
589                 invert_m4_m4(viewmat, ob->obmat);
590                 normalize_v3(viewmat[0]);
591                 normalize_v3(viewmat[1]);
592                 normalize_v3(viewmat[2]);
593
594                 for (int i = 0; i < 8; ++i)     {
595                         mul_m4_v4(viewmat, corners[i]);
596                 }
597
598                 float center[3];
599                 frustum_min_bounding_sphere(corners, center, &(sh_data->radius[c]));
600
601                 /* Snap projection center to nearest texel to cancel shimmering. */
602                 float shadow_origin[2], shadow_texco[2];
603                 mul_v2_v2fl(shadow_origin, center, linfo->shadow_size / (2.0f * sh_data->radius[c])); /* Light to texture space. */
604
605                 /* Find the nearest texel. */
606                 shadow_texco[0] = round(shadow_origin[0]);
607                 shadow_texco[1] = round(shadow_origin[1]);
608
609                 /* Compute offset. */
610                 sub_v2_v2(shadow_texco, shadow_origin);
611                 mul_v2_fl(shadow_texco, (2.0f * sh_data->radius[c]) / linfo->shadow_size); /* Texture to light space. */
612
613                 /* Apply offset. */
614                 add_v2_v2(center, shadow_texco);
615
616                 /* Expand the projection to cover frustum range */
617                 orthographic_m4(projmat,
618                                 center[0] - sh_data->radius[c],
619                                 center[0] + sh_data->radius[c],
620                                 center[1] - sh_data->radius[c],
621                                 center[1] + sh_data->radius[c],
622                                 la->clipsta, la->clipend);
623
624                 mul_m4_m4m4(sh_data->viewprojmat[c], projmat, viewmat);
625                 mul_m4_m4m4(cascade_data->shadowmat[c], texcomat, sh_data->viewprojmat[c]);
626         }
627
628         ubo_data->bias = 0.05f * la->bias;
629         ubo_data->near = la->clipsta;
630         ubo_data->far = la->clipend;
631         ubo_data->exp = (linfo->shadow_method == SHADOW_VSM) ? la->bleedbias : la->bleedexp;
632
633         evli->shadowid = (float)(sh_data->shadow_id);
634         ubo_data->shadow_start = (float)(sh_data->layer_id);
635         ubo_data->data_start = (float)(sh_data->cascade_id);
636         ubo_data->multi_shadow_count = (float)(sh_nbr);
637 }
638
639 /* Used for checking if object is inside the shadow volume. */
640 static bool cube_bbox_intersect(const float cube_center[3], float cube_half_dim, const BoundBox *bb, float (*obmat)[4])
641 {
642         float min[3], max[4], tmp[4][4];
643         unit_m4(tmp);
644         translate_m4(tmp, -cube_center[0], -cube_center[1], -cube_center[2]);
645         mul_m4_m4m4(tmp, tmp, obmat);
646
647         /* Just simple AABB intersection test in world space. */
648         INIT_MINMAX(min, max);
649         for (int i = 0; i < 8; ++i) {
650                 float vec[3];
651                 copy_v3_v3(vec, bb->vec[i]);
652                 mul_m4_v3(tmp, vec);
653                 minmax_v3v3_v3(min, max, vec);
654         }
655
656     if (MAX3(max[0], max[1], max[2]) < -cube_half_dim) return false;
657     if (MIN3(min[0], min[1], min[2]) >  cube_half_dim) return false;
658
659         return true;
660 }
661
662 static ShadowCaster *search_object_in_list(ListBase *list, Object *ob)
663 {
664         for (ShadowCaster *ldata = list->first; ldata; ldata = ldata->next) {
665                 if (ldata->ob == ob)
666                         return ldata;
667         }
668
669         return NULL;
670 }
671
672 static void delete_pruned_shadowcaster(EEVEE_LampEngineData *led)
673 {
674         ShadowCaster *next;
675         for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = next) {
676                 next = ldata->next;
677                 if (ldata->prune == true) {
678                         led->need_update = true;
679                         BLI_freelinkN(&led->shadow_caster_list, ldata);
680                 }
681         }
682 }
683
684 static void light_tag_shadow_update(Object *lamp, Object *ob)
685 {
686         Lamp *la = lamp->data;
687         EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
688
689         bool is_inside_range = cube_bbox_intersect(lamp->obmat[3], la->clipend, BKE_object_boundbox_get(ob), ob->obmat);
690         ShadowCaster *ldata = search_object_in_list(&led->shadow_caster_list, ob);
691
692         if (is_inside_range) {
693                 if (ldata == NULL) {
694                         /* Object was not a shadow caster previously but is now. Add it. */
695                         ldata = MEM_callocN(sizeof(ShadowCaster), "ShadowCaster");
696                         ldata->ob = ob;
697                         BLI_addtail(&led->shadow_caster_list, ldata);
698                         led->need_update = true;
699                 }
700                 else {
701                         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_get(ob);
702                         if (oedata->need_update) {
703                                 led->need_update = true;
704                         }
705                 }
706                 ldata->prune = false;
707         }
708         else if (ldata != NULL) {
709                 /* Object was a shadow caster previously and is not anymore. Remove it. */
710                 led->need_update = true;
711                 BLI_freelinkN(&led->shadow_caster_list, ldata);
712         }
713 }
714
715 static void eevee_lights_shcaster_updated(EEVEE_SceneLayerData *sldata, Object *ob)
716 {
717         Object *lamp;
718         EEVEE_LampsInfo *linfo = sldata->lamps;
719
720         /* Iterate over all shadow casting lamps to see if
721          * each of them needs update because of this object */
722         for (int i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
723                 light_tag_shadow_update(lamp, ob);
724         }
725 }
726
727 void EEVEE_lights_update(EEVEE_SceneLayerData *sldata)
728 {
729         EEVEE_LampsInfo *linfo = sldata->lamps;
730         Object *ob;
731         int i;
732
733         /* Prune shadow casters to remove if object does not exists anymore (unprune them if object exists) */
734         Object *lamp;
735         for (i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
736                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
737
738                 if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
739                         led->need_update = true;
740                 }
741
742                 for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = ldata->next) {
743                         ldata->prune = true;
744                 }
745         }
746
747         for (LinkData *ldata = sldata->shadow_casters.first; ldata; ldata = ldata->next) {
748                 eevee_lights_shcaster_updated(sldata, ldata->data);
749         }
750
751         for (i = 0; (ob = linfo->light_ref[i]) && (i < MAX_LIGHT); i++) {
752                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
753                 eevee_light_setup(ob, linfo, led);
754         }
755
756         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
757                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
758                 eevee_shadow_cube_setup(ob, linfo, led);
759                 delete_pruned_shadowcaster(led);
760         }
761
762         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
763                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
764                 eevee_shadow_cascade_setup(ob, linfo, led);
765         }
766
767         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
768         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_data); /* Update all data at once */
769 }
770
771 /* this refresh lamps shadow buffers */
772 void EEVEE_draw_shadows(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
773 {
774         EEVEE_LampsInfo *linfo = sldata->lamps;
775         Object *ob;
776         int i;
777         float clear_col[4] = {FLT_MAX};
778
779         /* Cube Shadow Maps */
780         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cube_target, 0, 0);
781         /* Render each shadow to one layer of the array */
782         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
783                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
784                 Lamp *la = (Lamp *)ob->data;
785
786                 float cube_projmat[4][4];
787                 perspective_m4(cube_projmat, -la->clipsta, la->clipsta, -la->clipsta, la->clipsta, la->clipsta, la->clipend);
788
789                 if (led->need_update) {
790                         EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
791
792                         srd->shadow_samples_ct = 32.0f;
793                         srd->shadow_inv_samples_ct = 1.0f / srd->shadow_samples_ct;
794                         srd->clip_near = la->clipsta;
795                         srd->clip_far = la->clipend;
796                         linfo->filter_size = la->soft * 0.0005f;
797                         copy_v3_v3(srd->position, ob->obmat[3]);
798                         for (int j = 0; j < 6; j++) {
799                                 float tmp[4][4];
800
801                                 unit_m4(tmp);
802                                 negate_v3_v3(tmp[3], ob->obmat[3]);
803                                 mul_m4_m4m4(srd->viewmat[j], cubefacemat[j], tmp);
804
805                                 mul_m4_m4m4(srd->shadowmat[j], cube_projmat, srd->viewmat[j]);
806                         }
807                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, srd);
808
809                         DRW_framebuffer_bind(sldata->shadow_target_fb);
810                         DRW_framebuffer_clear(true, true, false, clear_col, 1.0f);
811
812                         /* Render shadow cube */
813                         DRW_draw_pass(psl->shadow_cube_pass);
814
815                         /* Push it to shadowmap array */
816                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, i, 0);
817                         DRW_framebuffer_bind(sldata->shadow_store_fb);
818                         DRW_draw_pass(psl->shadow_cube_store_pass);
819
820                         led->need_update = false;
821                 }
822         }
823         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
824
825         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
826
827         /* Cascaded Shadow Maps */
828         DRW_framebuffer_texture_attach(sldata->shadow_target_fb, sldata->shadow_cascade_target, 0, 0);
829         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
830                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
831                 Lamp *la = (Lamp *)ob->data;
832
833                 EEVEE_ShadowCascadeData *evscd = (EEVEE_ShadowCascadeData *)led->storage;
834                 EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
835
836                 srd->shadow_samples_ct = 32.0f;
837                 srd->shadow_inv_samples_ct = 1.0f / srd->shadow_samples_ct;
838                 srd->clip_near = la->clipsta;
839                 srd->clip_far = la->clipend;
840                 for (int j = 0; j < MAX_CASCADE_NUM; ++j) {
841                         copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
842                 }
843                 DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
844
845                 DRW_framebuffer_bind(sldata->shadow_target_fb);
846                 DRW_framebuffer_clear(false, true, false, NULL, 1.0);
847
848                 /* Render shadow cascades */
849                 DRW_draw_pass(psl->shadow_cascade_pass);
850
851                 for (linfo->current_shadow_cascade = 0;
852                      linfo->current_shadow_cascade < MAX_CASCADE_NUM;
853                      ++linfo->current_shadow_cascade)
854                 {
855                         linfo->filter_size = la->soft * 0.0005f / (evscd->radius[linfo->current_shadow_cascade] * 0.05f);
856
857                         /* Push it to shadowmap array */
858                         int layer = evscd->layer_id + linfo->current_shadow_cascade;
859                         DRW_framebuffer_texture_layer_attach(sldata->shadow_store_fb, sldata->shadow_pool, 0, layer, 0);
860                         DRW_framebuffer_bind(sldata->shadow_store_fb);
861                         DRW_draw_pass(psl->shadow_cascade_store_pass);
862                 }
863         }
864
865         DRW_framebuffer_texture_detach(sldata->shadow_cube_target);
866 }
867
868 void EEVEE_lights_free(void)
869 {
870         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
871         for (int i = 0; i < SHADOW_METHOD_MAX; ++i) {
872                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cube_sh[i]);
873                 DRW_SHADER_FREE_SAFE(e_data.shadow_store_cascade_sh[i]);
874         }
875 }