summaryrefslogtreecommitdiffstats
path: root/src/datavis3d/engine/shaders/fragmentShadow
blob: 309c63fb1367514fb5b308c8c1a7cd3997440dcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
varying highp vec4 shadowCoord;
varying highp vec2 UV;
varying highp vec3 position_wrld;
varying highp vec3 normal_cmr;
varying highp vec3 eyeDirection_cmr;
varying highp vec3 lightDirection_cmr;

uniform highp float lightStrength;
uniform highp float ambientStrength;
uniform highp vec3 lightPosition_wrld;
uniform sampler2D textureSampler;
uniform sampler2DShadow shadowMap;

//float random(vec3 seed, int i){
//    vec4 seed4 = vec4(seed,i);
//    float dot_product = dot(seed4, vec4(12.9898, 78.233, 45.164, 94.673));
//    return fract(sin(dot_product) * 43758.5453);
//}

void main() {
    highp vec3 materialDiffuseColor = texture2D(textureSampler, UV).rgb;
    highp vec3 materialAmbientColor = vec3(ambientStrength, ambientStrength, ambientStrength) * materialDiffuseColor;
    highp vec3 materialSpecularColor = vec3(1.0, 1.0, 1.0);

    highp vec3 n = normalize(normal_cmr);
    highp vec3 l = normalize(lightDirection_cmr);
    highp float cosTheta = dot(n, l);
    if (cosTheta < 0.0) { cosTheta = 0.0; }
    if (cosTheta > 1.0) { cosTheta = 1.0; }

    highp vec3 E = normalize(eyeDirection_cmr);
    highp vec3 R = reflect(-l, n);
    highp float cosAlpha = dot(E, R);
    if (cosAlpha < 0.0) { cosAlpha = 0.0; }
    if (cosAlpha > 1.0) { cosAlpha = 1.0; }

    highp float visibility = 1.0;
    highp float bias = 0.005;
    //highp bias = 0.005 * tan(acos(cosTheta));
    //if (bias < 0.0) { bias = 0.0; }
    //if (bias > 0.01) { bias = 0.01; }

    //for (int i = 0; i < 4; i++) {
        // use either :
        //  - Always the same samples.
        //    Gives a fixed pattern in the shadow, but no noise
        //int index = i;
        //  - A random sample, based on the pixel's screen location.
        //    No banding, but the shadow moves with the camera, which looks weird.
        // int index = int(16.0*random(gl_FragCoord.xyy, i))%16;
        //  - A random sample, based on the pixel's position in world space.
        //    The position is rounded to the millimeter to avoid too much aliasing
        // int index = int(16.0*random(floor(Position_worldspace.xyz*1000.0), i))%16;

        // being fully in the shadow will eat up 4*0.2 = 0.8
        // 0.2 potentially remain, which is quite dark.
        visibility -= 0.8 * (1.0 - shadow2D(shadowMap, vec3(shadowCoord.xy, (shadowCoord.z - bias) / shadowCoord.w)).r);
    //}

    gl_FragColor.rgb =
        materialAmbientColor +
        visibility * materialDiffuseColor * lightStrength * cosTheta +
        visibility * materialSpecularColor * lightStrength * (cosAlpha * cosAlpha * cosAlpha * cosAlpha * cosAlpha);
    gl_FragColor.a = 1.0;
}