1uniform sampler2D ntex;
2uniform sampler2D dtex;
3uniform sampler2DArrayShadow shadowtex;
4
5uniform float split0;
6uniform float split1;
7uniform float split2;
8uniform float splitmax;
9uniform float shadow_res;
10
11uniform vec3 sundirection;
12uniform vec3 sun_color;
13
14in vec2 uv;
15#ifdef GL_ES
16layout (location = 0) out vec4 Diff;
17layout (location = 1) out vec4 Spec;
18#else
19out vec4 Diff;
20out vec4 Spec;
21#endif
22
23#stk_include "utils/decodeNormal.frag"
24#stk_include "utils/SpecularBRDF.frag"
25#stk_include "utils/DiffuseBRDF.frag"
26#stk_include "utils/getPosFromUVDepth.frag"
27#stk_include "utils/SunMRP.frag"
28
29float getShadowFactor(vec3 pos, int index)
30{
31    vec4 shadowcoord = (u_shadow_projection_view_matrices[index] * u_inverse_view_matrix * vec4(pos, 1.0));
32    shadowcoord.xy /= shadowcoord.w;
33    vec2 shadowtexcoord = shadowcoord.xy * 0.5 + 0.5;
34    //float d = .5 * shadowcoord.z + .5;
35    float d = .5 * shadowcoord.z + .5 - 1. / (shadow_res * 5.);
36
37    float result = 0.;
38
39    for (float i = -1.; i <= 1.; i += 1.)
40    {
41        for (float j = -1.; j <= 1.; j += 1.)
42        {
43            result += texture(shadowtex, vec4(shadowtexcoord + vec2(i,j) / shadow_res, float(index), d));
44        }
45    }
46
47    return result / 9.;
48}
49
50void main() {
51    vec2 uv = gl_FragCoord.xy / u_screen;
52    float z = texture(dtex, uv).x;
53    vec4 xpos = getPosFromUVDepth(vec3(uv, z), u_inverse_projection_matrix);
54
55    vec3 norm = normalize(DecodeNormal(2. * texture(ntex, uv).xy - 1.));
56    float roughness =texture(ntex, uv).z;
57    vec3 eyedir = -normalize(xpos.xyz);
58
59    vec3 Lightdir = SunMRP(norm, eyedir);
60    float NdotL = clamp(dot(norm, Lightdir), 0., 1.);
61
62    vec3 Specular = SpecularBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
63    vec3 Diffuse = DiffuseBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
64
65    // Shadows
66    float factor;
67    if (xpos.z < split0)
68        factor = getShadowFactor(xpos.xyz, 0);
69    else if (xpos.z < split1)
70        factor = getShadowFactor(xpos.xyz, 1);
71    else if (xpos.z < split2)
72        factor = getShadowFactor(xpos.xyz, 2);
73    else if (xpos.z < splitmax)
74        factor = getShadowFactor(xpos.xyz, 3);
75    else
76        factor = 1.;
77
78    Diff = vec4(factor * NdotL * Diffuse * sun_color, 1.);
79    Spec = vec4(factor * NdotL * Specular * sun_color, 1.);
80}
81