Merge branch 'master' into blender2.8
[blender.git] / source / blender / draw / engines / eevee / eevee_lights.c
1 /*
2  * Copyright 2016, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Blender Institute
19  *
20  */
21
22 /** \file eevee_lights.c
23  *  \ingroup DNA
24  */
25
26 #include "DRW_render.h"
27
28 #include "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;
42         float viewprojmat[6][4][4];
43 } EEVEE_ShadowCubeData;
44
45 typedef struct EEVEE_ShadowMapData {
46         short light_id, shadow_id;
47         float viewprojmat[4][4]; /* World->Lamp->NDC : used for rendering the shadow map. */
48 } EEVEE_ShadowMapData;
49
50 typedef struct EEVEE_ShadowCascadeData {
51         short light_id, shadow_id;
52         float viewprojmat[MAX_CASCADE_NUM][4][4]; /* World->Lamp->NDC : used for rendering the shadow map. */
53 } EEVEE_ShadowCascadeData;
54
55 typedef struct ShadowCaster {
56         struct ShadowCaster *next, *prev;
57         void *ob;
58         bool prune;
59 } ShadowCaster;
60
61 static struct {
62         struct GPUShader *shadow_sh;
63         struct GPUShader *shadow_store_sh;
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_vert_glsl[];
70 extern char datatoc_shadow_store_geom_glsl[];
71 extern char datatoc_shadow_store_frag_glsl[];
72
73 /* *********** FUNCTIONS *********** */
74
75 void EEVEE_lights_init(EEVEE_SceneLayerData *sldata)
76 {
77         const unsigned int shadow_ubo_size = sizeof(EEVEE_ShadowCube) * MAX_SHADOW_CUBE +
78                                              sizeof(EEVEE_ShadowMap) * MAX_SHADOW_MAP +
79                                              sizeof(EEVEE_ShadowCascade) * MAX_SHADOW_CASCADE;
80
81         if (!e_data.shadow_sh) {
82                 e_data.shadow_sh = DRW_shader_create(
83                         datatoc_shadow_vert_glsl, datatoc_shadow_geom_glsl, datatoc_shadow_frag_glsl, NULL);
84
85                 e_data.shadow_store_sh = DRW_shader_create(
86                         datatoc_shadow_store_vert_glsl, datatoc_shadow_store_geom_glsl, datatoc_shadow_store_frag_glsl, NULL);
87         }
88
89         if (!sldata->lamps) {
90                 sldata->lamps              = MEM_callocN(sizeof(EEVEE_LampsInfo), "EEVEE_LampsInfo");
91                 sldata->light_ubo          = DRW_uniformbuffer_create(sizeof(EEVEE_Light) * MAX_LIGHT, NULL);
92                 sldata->shadow_ubo         = DRW_uniformbuffer_create(shadow_ubo_size, NULL);
93                 sldata->shadow_render_ubo  = DRW_uniformbuffer_create(sizeof(EEVEE_ShadowRender), NULL);
94         }
95 }
96
97 void EEVEE_lights_cache_init(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
98 {
99         EEVEE_LampsInfo *linfo = sldata->lamps;
100
101         linfo->num_light = linfo->num_cube = linfo->num_map = linfo->num_cascade = 0;
102         memset(linfo->light_ref, 0, sizeof(linfo->light_ref));
103         memset(linfo->shadow_cube_ref, 0, sizeof(linfo->shadow_cube_ref));
104         memset(linfo->shadow_map_ref, 0, sizeof(linfo->shadow_map_ref));
105         memset(linfo->shadow_cascade_ref, 0, sizeof(linfo->shadow_cascade_ref));
106
107         {
108                 psl->shadow_cube_store_pass = DRW_pass_create("Shadow Storage Pass", DRW_STATE_WRITE_COLOR);
109
110                 DRWShadingGroup *grp = DRW_shgroup_create(e_data.shadow_store_sh, psl->shadow_cube_store_pass);
111                 DRW_shgroup_uniform_buffer(grp, "shadowCube", &sldata->shadow_color_cube_target);
112                 DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
113                 DRW_shgroup_call_add(grp, DRW_cache_fullscreen_quad_get(), NULL);
114         }
115
116         {
117                 psl->shadow_cube_pass = DRW_pass_create("Shadow Cube Pass", DRW_STATE_WRITE_COLOR | DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
118         }
119
120         {
121                 psl->shadow_cascade_pass = DRW_pass_create("Shadow Cascade Pass", DRW_STATE_WRITE_DEPTH | DRW_STATE_DEPTH_LESS);
122         }
123
124         /* Reset shadow casters list */
125         BLI_freelistN(&sldata->shadow_casters);
126 }
127
128 void EEVEE_lights_cache_add(EEVEE_SceneLayerData *sldata, Object *ob)
129 {
130         EEVEE_LampsInfo *linfo = sldata->lamps;
131
132         /* Step 1 find all lamps in the scene and setup them */
133         if (linfo->num_light > MAX_LIGHT) {
134                 printf("Too much lamps in the scene !!!\n");
135                 linfo->num_light = MAX_LIGHT;
136         }
137         else {
138                 Lamp *la = (Lamp *)ob->data;
139                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
140
141                 if ((ob->deg_update_flag & DEG_RUNTIME_DATA_UPDATE) != 0) {
142                         led->need_update = true;
143                 }
144
145                 MEM_SAFE_FREE(led->storage);
146
147 #if 1 /* TODO Waiting for notified refresh. only on scene change. Else too much perf cost. */
148                 if (la->mode & (LA_SHAD_BUF | LA_SHAD_RAY)) {
149                         if (la->type == LA_SUN && linfo->num_cascade < MAX_SHADOW_CASCADE) {
150 #if 0 /* TODO filter cascaded shadow map */
151                                 led->storage = MEM_mallocN(sizeof(EEVEE_ShadowCascadeData), "EEVEE_ShadowCascadeData");
152                                 ((EEVEE_ShadowCascadeData *)led->storage)->shadow_id = linfo->num_cascade;
153                                 linfo->shadow_cascade_ref[linfo->num_cascade] = ob;
154                                 linfo->num_cascade++;
155 #endif
156                         }
157                         else if ((la->type == LA_SPOT || la->type == LA_LOCAL || la->type == LA_AREA)
158                                   && linfo->num_cube < MAX_SHADOW_CUBE) {
159                                 led->storage = MEM_mallocN(sizeof(EEVEE_ShadowCubeData), "EEVEE_ShadowCubeData");
160                                 ((EEVEE_ShadowCubeData *)led->storage)->shadow_id = linfo->num_cube;
161                                 linfo->shadow_cube_ref[linfo->num_cube] = ob;
162                                 linfo->num_cube++;
163                         }
164
165                 }
166 #else
167                 UNUSED_VARS(la);
168 #endif
169                 /* Default light without shadows */
170                 if (!led->storage) {
171                         led->storage = MEM_mallocN(sizeof(EEVEE_LightData), "EEVEE_LightData");
172                         ((EEVEE_LightData *)led->storage)->shadow_id = -1;
173                 }
174
175                 ((EEVEE_LightData *)led->storage)->light_id = linfo->num_light;
176                 linfo->light_ref[linfo->num_light] = ob;
177                 linfo->num_light++;
178         }
179 }
180
181 /* Add a shadow caster to the shadowpasses */
182 void EEVEE_lights_cache_shcaster_add(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct Gwn_Batch *geom, float (*obmat)[4])
183 {
184         DRWShadingGroup *grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cube_pass, geom);
185         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
186         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
187
188         for (int i = 0; i < 6; ++i)
189                 DRW_shgroup_call_dynamic_add_empty(grp);
190
191         grp = DRW_shgroup_instance_create(e_data.shadow_sh, psl->shadow_cascade_pass, geom);
192         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
193         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
194
195         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
196                 DRW_shgroup_call_dynamic_add_empty(grp);
197 }
198
199 void EEVEE_lights_cache_shcaster_material_add(
200         EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl, struct GPUMaterial *gpumat, struct Gwn_Batch *geom, float (*obmat)[4], float *alpha_threshold)
201 {
202         DRWShadingGroup *grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cube_pass, geom);
203
204         if (grp == NULL) return;
205
206         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
207         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
208
209         if (alpha_threshold != NULL)
210                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
211
212         for (int i = 0; i < 6; ++i)
213                 DRW_shgroup_call_dynamic_add_empty(grp);
214
215         grp = DRW_shgroup_material_instance_create(gpumat, psl->shadow_cascade_pass, geom);
216         DRW_shgroup_uniform_block(grp, "shadow_render_block", sldata->shadow_render_ubo);
217         DRW_shgroup_uniform_mat4(grp, "ShadowModelMatrix", (float *)obmat);
218
219         if (alpha_threshold != NULL)
220                 DRW_shgroup_uniform_float(grp, "alphaThreshold", alpha_threshold, 1);
221
222         for (int i = 0; i < MAX_CASCADE_NUM; ++i)
223                 DRW_shgroup_call_dynamic_add_empty(grp);
224 }
225
226 void EEVEE_lights_cache_finish(EEVEE_SceneLayerData *sldata)
227 {
228         EEVEE_LampsInfo *linfo = sldata->lamps;
229
230         /* Setup enough layers. */
231         /* Free textures if number mismatch. */
232         if (linfo->num_cube != linfo->cache_num_cube) {
233                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_depth_cube_pool);
234                 linfo->cache_num_cube = linfo->num_cube;
235                 linfo->update_flag |= LIGHT_UPDATE_SHADOW_CUBE;
236         }
237         if (linfo->num_map != linfo->cache_num_map) {
238                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_depth_map_pool);
239                 linfo->cache_num_map = linfo->num_map;
240         }
241         if (linfo->num_cascade != linfo->cache_num_cascade) {
242                 DRW_TEXTURE_FREE_SAFE(sldata->shadow_depth_cascade_pool);
243                 linfo->cache_num_cascade = linfo->num_cascade;
244         }
245
246         /* Initialize Textures Arrays first so DRW_framebuffer_init just bind them. */
247         if (!sldata->shadow_depth_cube_target) {
248                 /* Render Cubemap */
249                 sldata->shadow_depth_cube_target = DRW_texture_create_cube(512, DRW_TEX_DEPTH_24, 0, NULL);
250                 sldata->shadow_color_cube_target = DRW_texture_create_cube(512, DRW_TEX_R_32, DRW_TEX_FILTER, NULL);
251                 if (sldata->shadow_cube_fb) {
252                         DRW_framebuffer_texture_attach(sldata->shadow_cube_fb, sldata->shadow_depth_cube_target, 0, 0);
253                         DRW_framebuffer_texture_attach(sldata->shadow_cube_fb, sldata->shadow_color_cube_target, 0, 0);
254                 }
255         }
256         if (!sldata->shadow_depth_cube_pool) {
257                 /* Cubemap / octahedral map pool */
258                 /* TODO Cubemap array */
259                 sldata->shadow_depth_cube_pool = DRW_texture_create_2D_array(
260                         512, 512, max_ff(1, linfo->num_cube), DRW_TEX_R_16,
261                         DRW_TEX_FILTER | DRW_TEX_COMPARE, NULL);
262                 if (sldata->shadow_cube_fb) {
263                         DRW_framebuffer_texture_attach(sldata->shadow_cube_fb, sldata->shadow_depth_cube_pool, 0, 0);
264                 }
265         }
266         if (!sldata->shadow_depth_map_pool) {
267                 sldata->shadow_depth_map_pool = DRW_texture_create_2D_array(
268                         512, 512, max_ff(1, linfo->num_map), DRW_TEX_DEPTH_24,
269                         DRW_TEX_FILTER | DRW_TEX_COMPARE, NULL);
270                 if (sldata->shadow_map_fb) {
271                         DRW_framebuffer_texture_attach(sldata->shadow_map_fb, sldata->shadow_depth_map_pool, 0, 0);
272                 }
273         }
274         if (!sldata->shadow_depth_cascade_pool) {
275                 sldata->shadow_depth_cascade_pool = DRW_texture_create_2D_array(
276                         512, 512, max_ff(1, linfo->num_cascade * MAX_CASCADE_NUM), DRW_TEX_DEPTH_24,
277                         DRW_TEX_FILTER | DRW_TEX_COMPARE, NULL);
278                 if (sldata->shadow_cascade_fb) {
279                         DRW_framebuffer_texture_attach(sldata->shadow_cascade_fb, sldata->shadow_depth_map_pool, 0, 0);
280                 }
281         }
282
283         DRWFboTexture tex_cube_target[2] = {
284                 {&sldata->shadow_depth_cube_target, DRW_TEX_DEPTH_24, 0},
285                 {&sldata->shadow_color_cube_target, DRW_TEX_R_16, DRW_TEX_FILTER}};
286         DRW_framebuffer_init(&sldata->shadow_cube_target_fb, &draw_engine_eevee_type, 512, 512, tex_cube_target, 2);
287
288         DRWFboTexture tex_cube = {&sldata->shadow_depth_cube_pool, DRW_TEX_R_16, DRW_TEX_FILTER};
289         DRW_framebuffer_init(&sldata->shadow_cube_fb, &draw_engine_eevee_type, 512, 512, &tex_cube, 1);
290
291         DRWFboTexture tex_cascade = {&sldata->shadow_depth_cascade_pool, DRW_TEX_DEPTH_24, DRW_TEX_FILTER | DRW_TEX_COMPARE};
292         DRW_framebuffer_init(&sldata->shadow_cascade_fb, &draw_engine_eevee_type, 512, 512, &tex_cascade, 1);
293
294         /* Update Lamps UBOs. */
295         EEVEE_lights_update(sldata);
296 }
297
298 /* Update buffer with lamp data */
299 static void eevee_light_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
300 {
301         /* TODO only update if data changes */
302         EEVEE_LightData *evld = led->storage;
303         EEVEE_Light *evli = linfo->light_data + evld->light_id;
304         Lamp *la = (Lamp *)ob->data;
305         float mat[4][4], scale[3], power;
306
307         /* Position */
308         copy_v3_v3(evli->position, ob->obmat[3]);
309
310         /* Color */
311         copy_v3_v3(evli->color, &la->r);
312
313         /* Influence Radius */
314         evli->dist = la->dist;
315
316         /* Vectors */
317         normalize_m4_m4_ex(mat, ob->obmat, scale);
318         copy_v3_v3(evli->forwardvec, mat[2]);
319         normalize_v3(evli->forwardvec);
320         negate_v3(evli->forwardvec);
321
322         copy_v3_v3(evli->rightvec, mat[0]);
323         normalize_v3(evli->rightvec);
324
325         copy_v3_v3(evli->upvec, mat[1]);
326         normalize_v3(evli->upvec);
327
328         /* Spot size & blend */
329         if (la->type == LA_SPOT) {
330                 evli->sizex = scale[0] / scale[2];
331                 evli->sizey = scale[1] / scale[2];
332                 evli->spotsize = cosf(la->spotsize * 0.5f);
333                 evli->spotblend = (1.0f - evli->spotsize) * la->spotblend;
334                 evli->radius = max_ff(0.001f, la->area_size);
335         }
336         else if (la->type == LA_AREA) {
337                 evli->sizex = max_ff(0.0001f, la->area_size * scale[0] * 0.5f);
338                 if (la->area_shape == LA_AREA_RECT) {
339                         evli->sizey = max_ff(0.0001f, la->area_sizey * scale[1] * 0.5f);
340                 }
341                 else {
342                         evli->sizey = max_ff(0.0001f, la->area_size * scale[1] * 0.5f);
343                 }
344         }
345         else {
346                 evli->radius = max_ff(0.001f, la->area_size);
347         }
348
349         /* Make illumination power constant */
350         if (la->type == LA_AREA) {
351                 power = 1.0f / (evli->sizex * evli->sizey * 4.0f * M_PI) /* 1/(w*h*Pi) */
352                         * 80.0f; /* XXX : Empirical, Fit cycles power */
353         }
354         else if (la->type == LA_SPOT || la->type == LA_LOCAL) {
355                 power = 1.0f / (4.0f * evli->radius * evli->radius * M_PI * M_PI) /* 1/(4*r²*Pi²) */
356                         * M_PI * M_PI * M_PI * 10.0; /* XXX : Empirical, Fit cycles power */
357
358                 /* for point lights (a.k.a radius == 0.0) */
359                 // power = M_PI * M_PI * 0.78; /* XXX : Empirical, Fit cycles power */
360         }
361         else {
362                 power = 1.0f;
363         }
364         mul_v3_fl(evli->color, power * la->energy);
365
366         /* Lamp Type */
367         evli->lamptype = (float)la->type;
368
369         /* No shadow by default */
370         evli->shadowid = -1.0f;
371 }
372
373 static void eevee_shadow_cube_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
374 {
375         float projmat[4][4];
376
377         EEVEE_ShadowCubeData *evsmp = (EEVEE_ShadowCubeData *)led->storage;
378         EEVEE_Light *evli = linfo->light_data + evsmp->light_id;
379         EEVEE_ShadowCube *evsh = linfo->shadow_cube_data + evsmp->shadow_id;
380         Lamp *la = (Lamp *)ob->data;
381
382         perspective_m4(projmat, -la->clipsta, la->clipsta, -la->clipsta, la->clipsta, la->clipsta, la->clipend);
383
384         for (int i = 0; i < 6; ++i) {
385                 float tmp[4][4];
386                 unit_m4(tmp);
387                 negate_v3_v3(tmp[3], ob->obmat[3]);
388                 mul_m4_m4m4(tmp, cubefacemat[i], tmp);
389                 mul_m4_m4m4(evsmp->viewprojmat[i], projmat, tmp);
390         }
391
392         evsh->bias = 0.05f * la->bias;
393         evsh->near = la->clipsta;
394         evsh->far = la->clipend;
395         evsh->exp = la->bleedexp;
396
397         evli->shadowid = (float)(evsmp->shadow_id);
398 }
399
400 static void eevee_shadow_map_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
401 {
402         float viewmat[4][4], projmat[4][4];
403
404         EEVEE_ShadowMapData *evsmp = (EEVEE_ShadowMapData *)led->storage;
405         EEVEE_Light *evli = linfo->light_data + evsmp->light_id;
406         EEVEE_ShadowMap *evsh = linfo->shadow_map_data + evsmp->shadow_id;
407         Lamp *la = (Lamp *)ob->data;
408
409         invert_m4_m4(viewmat, ob->obmat);
410         normalize_v3(viewmat[0]);
411         normalize_v3(viewmat[1]);
412         normalize_v3(viewmat[2]);
413
414         float wsize = la->shadow_frustum_size;
415         orthographic_m4(projmat, -wsize, wsize, -wsize, wsize, la->clipsta, la->clipend);
416
417         mul_m4_m4m4(evsmp->viewprojmat, projmat, viewmat);
418         mul_m4_m4m4(evsh->shadowmat, texcomat, evsmp->viewprojmat);
419
420         evsh->bias = 0.005f * la->bias;
421
422         evli->shadowid = (float)(MAX_SHADOW_CUBE + evsmp->shadow_id);
423 }
424
425 #define LERP(t, a, b) ((a) + (t) * ((b) - (a)))
426
427 static void frustum_min_bounding_sphere(const float corners[8][4], float r_center[3], float *r_radius)
428 {
429 #if 0 /* Simple solution but waist too much space. */
430         float minvec[3], maxvec[3];
431
432         /* compute the bounding box */
433         INIT_MINMAX(minvec, maxvec);
434         for (int i = 0; i < 8; ++i)     {
435                 minmax_v3v3_v3(minvec, maxvec, corners[i]);
436         }
437
438         /* compute the bounding sphere of this box */
439         r_radius = len_v3v3(minvec, maxvec) * 0.5f;
440         add_v3_v3v3(r_center, minvec, maxvec);
441         mul_v3_fl(r_center, 0.5f);
442 #else
443         /* Make the bouding sphere always centered on the front diagonal */
444         add_v3_v3v3(r_center, corners[4], corners[7]);
445         mul_v3_fl(r_center, 0.5f);
446         *r_radius = len_v3v3(corners[0], r_center);
447
448         /* Search the largest distance between the sphere center
449          * and the front plane corners. */
450         for (int i = 0; i < 4; ++i) {
451                 float rad = len_v3v3(corners[4+i], r_center);
452                 if (rad > *r_radius) {
453                         *r_radius = rad;
454                 }
455         }
456 #endif
457 }
458
459 static void eevee_shadow_cascade_setup(Object *ob, EEVEE_LampsInfo *linfo, EEVEE_LampEngineData *led)
460 {
461         /* Camera Matrices */
462         float persmat[4][4], persinv[4][4];
463         float viewprojmat[4][4], projinv[4][4];
464         float near, far;
465         float near_v[4] = {0.0f, 0.0f, -1.0f, 1.0f};
466         float far_v[4] = {0.0f, 0.0f,  1.0f, 1.0f};
467         bool is_persp = DRW_viewport_is_persp_get();
468         DRW_viewport_matrix_get(persmat, DRW_MAT_PERS);
469         invert_m4_m4(persinv, persmat);
470         /* FIXME : Get near / far from Draw manager? */
471         DRW_viewport_matrix_get(viewprojmat, DRW_MAT_WIN);
472         invert_m4_m4(projinv, viewprojmat);
473         mul_m4_v4(projinv, near_v);
474         mul_m4_v4(projinv, far_v);
475         near = near_v[2];
476         far = far_v[2]; /* TODO: Should be a shadow parameter */
477         if (is_persp) {
478                 near /= near_v[3];
479                 far /= far_v[3];
480         }
481
482         /* Lamps Matrices */
483         float viewmat[4][4], projmat[4][4];
484         int cascade_ct = MAX_CASCADE_NUM;
485         float shadow_res = 512.0f; /* TODO parameter */
486
487         EEVEE_ShadowCascadeData *evscp = (EEVEE_ShadowCascadeData *)led->storage;
488         EEVEE_Light *evli = linfo->light_data + evscp->light_id;
489         EEVEE_ShadowCascade *evsh = linfo->shadow_cascade_data + evscp->shadow_id;
490         Lamp *la = (Lamp *)ob->data;
491
492         /* The technique consists into splitting
493          * the view frustum into several sub-frustum
494          * that are individually receiving one shadow map */
495
496         /* init near/far */
497         for (int c = 0; c < MAX_CASCADE_NUM; ++c) {
498                 evsh->split[c] = far;
499         }
500
501         /* Compute split planes */
502         float splits_ndc[MAX_CASCADE_NUM + 1];
503         splits_ndc[0] = -1.0f;
504         splits_ndc[cascade_ct] = 1.0f;
505         for (int c = 1; c < cascade_ct; ++c) {
506                 const float lambda = 0.8f; /* TODO : Parameter */
507
508                 /* View Space */
509                 float linear_split = LERP(((float)(c) / (float)cascade_ct), near, far);
510                 float exp_split = near * powf(far / near, (float)(c) / (float)cascade_ct);
511
512                 if (is_persp) {
513                         evsh->split[c-1] = LERP(lambda, linear_split, exp_split);
514                 }
515                 else {
516                         evsh->split[c-1] = linear_split;
517                 }
518
519                 /* NDC Space */
520                 float p[4] = {1.0f, 1.0f, evsh->split[c-1], 1.0f};
521                 mul_m4_v4(viewprojmat, p);
522                 splits_ndc[c] = p[2];
523
524                 if (is_persp) {
525                         splits_ndc[c] /= p[3];
526                 }
527         }
528
529         /* For each cascade */
530         for (int c = 0; c < cascade_ct; ++c) {
531                 /* Given 8 frustrum corners */
532                 float corners[8][4] = {
533                         /* Near Cap */
534                         {-1.0f, -1.0f, splits_ndc[c], 1.0f},
535                         { 1.0f, -1.0f, splits_ndc[c], 1.0f},
536                         {-1.0f,  1.0f, splits_ndc[c], 1.0f},
537                         { 1.0f,  1.0f, splits_ndc[c], 1.0f},
538                         /* Far Cap */
539                         {-1.0f, -1.0f, splits_ndc[c+1], 1.0f},
540                         { 1.0f, -1.0f, splits_ndc[c+1], 1.0f},
541                         {-1.0f,  1.0f, splits_ndc[c+1], 1.0f},
542                         { 1.0f,  1.0f, splits_ndc[c+1], 1.0f}
543                 };
544
545                 /* Transform them into world space */
546                 for (int i = 0; i < 8; ++i)     {
547                         mul_m4_v4(persinv, corners[i]);
548                         mul_v3_fl(corners[i], 1.0f / corners[i][3]);
549                         corners[i][3] = 1.0f;
550                 }
551
552                 /* Project them into light space */
553                 invert_m4_m4(viewmat, ob->obmat);
554                 normalize_v3(viewmat[0]);
555                 normalize_v3(viewmat[1]);
556                 normalize_v3(viewmat[2]);
557
558                 for (int i = 0; i < 8; ++i)     {
559                         mul_m4_v4(viewmat, corners[i]);
560                 }
561
562                 float center[3], radius;
563                 frustum_min_bounding_sphere(corners, center, &radius);
564
565                 /* Snap projection center to nearest texel to cancel shimering. */
566                 float shadow_origin[2], shadow_texco[2];
567                 mul_v2_v2fl(shadow_origin, center, shadow_res / (2.0f * radius)); /* Light to texture space. */
568
569                 /* Find the nearest texel. */
570                 shadow_texco[0] = round(shadow_origin[0]);
571                 shadow_texco[1] = round(shadow_origin[1]);
572
573                 /* Compute offset. */
574                 sub_v2_v2(shadow_texco, shadow_origin);
575                 mul_v2_fl(shadow_texco, (2.0f * radius) / shadow_res); /* Texture to light space. */
576
577                 /* Apply offset. */
578                 add_v2_v2(center, shadow_texco);
579
580                 /* Expand the projection to cover frustum range */
581                 orthographic_m4(projmat,
582                                 center[0] - radius,
583                                 center[0] + radius,
584                                 center[1] - radius,
585                                 center[1] + radius,
586                                 la->clipsta, la->clipend);
587
588                 mul_m4_m4m4(evscp->viewprojmat[c], projmat, viewmat);
589                 mul_m4_m4m4(evsh->shadowmat[c], texcomat, evscp->viewprojmat[c]);
590
591                 /* TODO modify bias depending on the cascade radius */
592                 evsh->bias[c] = 0.005f * la->bias;
593         }
594
595         evli->shadowid = (float)(MAX_SHADOW_CUBE + MAX_SHADOW_MAP + evscp->shadow_id);
596 }
597
598 /* Used for checking if object is inside the shadow volume. */
599 static bool cube_bbox_intersect(const float cube_center[3], float cube_half_dim, const BoundBox *bb, float (*obmat)[4])
600 {
601         float min[3], max[4], tmp[4][4];
602         unit_m4(tmp);
603         translate_m4(tmp, -cube_center[0], -cube_center[1], -cube_center[2]);
604         mul_m4_m4m4(tmp, tmp, obmat);
605
606         /* Just simple AABB intersection test in world space. */
607         INIT_MINMAX(min, max);
608         for (int i = 0; i < 8; ++i) {
609                 float vec[3];
610                 copy_v3_v3(vec, bb->vec[i]);
611                 mul_m4_v3(tmp, vec);
612                 minmax_v3v3_v3(min, max, vec);
613         }
614
615     if (MAX3(max[0], max[1], max[2]) < -cube_half_dim) return false;
616     if (MIN3(min[0], min[1], min[2]) >  cube_half_dim) return false;
617
618         return true;
619 }
620
621 static ShadowCaster *search_object_in_list(ListBase *list, Object *ob)
622 {
623         for (ShadowCaster *ldata = list->first; ldata; ldata = ldata->next) {
624                 if (ldata->ob == ob)
625                         return ldata;
626         }
627
628         return NULL;
629 }
630
631 static void delete_pruned_shadowcaster(EEVEE_LampEngineData *led)
632 {
633         ShadowCaster *next;
634         for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = next) {
635                 next = ldata->next;
636                 if (ldata->prune == true) {
637                         led->need_update = true;
638                         BLI_freelinkN(&led->shadow_caster_list, ldata);
639                 }
640         }
641 }
642
643 static void light_tag_shadow_update(Object *lamp, Object *ob)
644 {
645         Lamp *la = lamp->data;
646         EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
647
648         bool is_inside_range = cube_bbox_intersect(lamp->obmat[3], la->clipend, BKE_object_boundbox_get(ob), ob->obmat);
649         ShadowCaster *ldata = search_object_in_list(&led->shadow_caster_list, ob);
650
651         if (is_inside_range) {
652                 if (ldata == NULL) {
653                         /* Object was not a shadow caster previously but is now. Add it. */
654                         ldata = MEM_callocN(sizeof(ShadowCaster), "ShadowCaster");
655                         ldata->ob = ob;
656                         BLI_addtail(&led->shadow_caster_list, ldata);
657                         led->need_update = true;
658                 }
659                 else {
660                         EEVEE_ObjectEngineData *oedata = EEVEE_object_data_get(ob);
661                         if (oedata->need_update) {
662                                 led->need_update = true;
663                         }
664                 }
665                 ldata->prune = false;
666         }
667         else if (ldata != NULL) {
668                 /* Object was a shadow caster previously and is not anymore. Remove it. */
669                 led->need_update = true;
670                 BLI_freelinkN(&led->shadow_caster_list, ldata);
671         }
672 }
673
674 static void eevee_lights_shcaster_updated(EEVEE_SceneLayerData *sldata, Object *ob)
675 {
676         Object *lamp;
677         EEVEE_LampsInfo *linfo = sldata->lamps;
678
679         /* Iterate over all shadow casting lamps to see if
680          * each of them needs update because of this object */
681         for (int i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
682                 light_tag_shadow_update(lamp, ob);
683         }
684 }
685
686 void EEVEE_lights_update(EEVEE_SceneLayerData *sldata)
687 {
688         EEVEE_LampsInfo *linfo = sldata->lamps;
689         Object *ob;
690         int i;
691
692         /* Prune shadow casters to remove if object does not exists anymore (unprune them if object exists) */
693         Object *lamp;
694         for (i = 0; (lamp = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
695                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(lamp);
696
697                 if ((linfo->update_flag & LIGHT_UPDATE_SHADOW_CUBE) != 0) {
698                         led->need_update = true;
699                 }
700
701                 for (ShadowCaster *ldata = led->shadow_caster_list.first; ldata; ldata = ldata->next) {
702                         ldata->prune = true;
703                 }
704         }
705
706         for (LinkData *ldata = sldata->shadow_casters.first; ldata; ldata = ldata->next) {
707                 eevee_lights_shcaster_updated(sldata, ldata->data);
708         }
709
710         for (i = 0; (ob = linfo->light_ref[i]) && (i < MAX_LIGHT); i++) {
711                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
712                 eevee_light_setup(ob, linfo, led);
713         }
714
715         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
716                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
717                 eevee_shadow_cube_setup(ob, linfo, led);
718                 delete_pruned_shadowcaster(led);
719         }
720
721         for (i = 0; (ob = linfo->shadow_map_ref[i]) && (i < MAX_SHADOW_MAP); i++) {
722                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
723                 eevee_shadow_map_setup(ob, linfo, led);
724         }
725
726         for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
727                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
728                 eevee_shadow_cascade_setup(ob, linfo, led);
729         }
730
731         DRW_uniformbuffer_update(sldata->light_ubo, &linfo->light_data);
732         DRW_uniformbuffer_update(sldata->shadow_ubo, &linfo->shadow_cube_data); /* Update all data at once */
733 }
734
735 /* this refresh lamps shadow buffers */
736 void EEVEE_draw_shadows(EEVEE_SceneLayerData *sldata, EEVEE_PassList *psl)
737 {
738         EEVEE_LampsInfo *linfo = sldata->lamps;
739         Object *ob;
740         int i;
741         float clear_color[4] = {FLT_MAX, FLT_MAX, FLT_MAX, 0.0f};
742
743         /* Cube Shadow Maps */
744         /* Render each shadow to one layer of the array */
745         for (i = 0; (ob = linfo->shadow_cube_ref[i]) && (i < MAX_SHADOW_CUBE); i++) {
746                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
747                 Lamp *la = (Lamp *)ob->data;
748
749                 if (led->need_update) {
750                         EEVEE_ShadowCubeData *evscd = (EEVEE_ShadowCubeData *)led->storage;
751                         EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
752
753                         srd->layer = i;
754                         srd->exponent = la->bleedexp;
755                         copy_v3_v3(srd->position, ob->obmat[3]);
756                         for (int j = 0; j < 6; j++) {
757                                 float tmp[4][4];
758
759                                 unit_m4(tmp);
760                                 negate_v3_v3(tmp[3], ob->obmat[3]);
761                                 mul_m4_m4m4(srd->viewmat[j], cubefacemat[j], tmp);
762
763                                 copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
764                         }
765                         DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
766
767                         DRW_framebuffer_bind(sldata->shadow_cube_target_fb);
768                         DRW_framebuffer_clear(true, true, false, clear_color, 1.0f);
769                         /* Render shadow cube */
770                         DRW_draw_pass(psl->shadow_cube_pass);
771
772                         /* Push it to shadowmap array */
773                         DRW_framebuffer_bind(sldata->shadow_cube_fb);
774                         DRW_draw_pass(psl->shadow_cube_store_pass);
775
776                         led->need_update = false;
777                 }
778         }
779         linfo->update_flag &= ~LIGHT_UPDATE_SHADOW_CUBE;
780
781 #if 0
782         /* Standard Shadow Maps */
783         DRW_framebuffer_bind(fbl->shadow_map_fb);
784         DRW_framebuffer_clear(false, true, false, NULL, 1.0);
785
786         /* Render each shadow to one layer of the array */
787         for (i = 0; (ob = linfo->shadow_map_ref[i]) && (i < MAX_SHADOW_MAP); i++) {
788                 EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
789                 EEVEE_ShadowMapData *evsmd = (EEVEE_ShadowMapData *)led->storage;
790
791                 linfo->layer = i;
792                 copy_m4_m4(linfo->shadowmat, evsmd->viewprojmat);
793                 DRW_draw_pass(vedata->psl->shadow_pass);
794         }
795 #endif
796
797         /* Cascaded Shadow Maps */
798 //      DRW_framebuffer_bind(fbl->shadow_cascade_fb);
799 //      DRW_framebuffer_clear(false, true, false, NULL, 1.0);
800
801 //      /* Render each shadow to one layer of the array */
802 //      for (i = 0; (ob = linfo->shadow_cascade_ref[i]) && (i < MAX_SHADOW_CASCADE); i++) {
803 //              EEVEE_LampEngineData *led = EEVEE_lamp_data_get(ob);
804 //              EEVEE_ShadowCascadeData *evscd = (EEVEE_ShadowCascadeData *)led->storage;
805 //              EEVEE_ShadowRender *srd = &linfo->shadow_render_data;
806
807 //              srd->layer = i;
808 //              for (int j = 0; j < MAX_CASCADE_NUM; ++j) {
809 //                      copy_m4_m4(srd->shadowmat[j], evscd->viewprojmat[j]);
810 //              }
811 //              DRW_uniformbuffer_update(sldata->shadow_render_ubo, &linfo->shadow_render_data);
812
813 //              DRW_draw_pass(psl->shadow_cascade_pass);
814 //      }
815 }
816
817 void EEVEE_lights_free(void)
818 {
819         DRW_SHADER_FREE_SAFE(e_data.shadow_sh);
820         DRW_SHADER_FREE_SAFE(e_data.shadow_store_sh);
821 }