Step 6 GLSL

step_06.glsl
1#define N 500
2
3// x, y position of the light
4uniform vec2 lightPosition;
5// Size of light in pixels
6uniform float lightSize;
7
8float terrain(vec2 samplePoint)
9{
10 float samplePointAlpha = texture(iChannel0, samplePoint).a;
11 float sampleStepped = step(0.1, samplePointAlpha);
12 float returnValue = 1.0 - sampleStepped;
13
14 // Soften the shadows. Comment out for hard shadows.
15 // The closer the first number is to 1.0, the softer the shadows.
16 returnValue = mix(0.98, 1.0, returnValue);
17
18 return returnValue;
19}
20
21void mainImage( out vec4 fragColor, in vec2 fragCoord )
22{
23 // Distance in pixels to the light
24 float distanceToLight = length(lightPosition - fragCoord);
25
26 // Normalize the fragment coordinate from (0.0, 0.0) to (1.0, 1.0)
27 vec2 normalizedFragCoord = fragCoord/iResolution.xy;
28 vec2 normalizedLightCoord = lightPosition.xy/iResolution.xy;
29
30 // Start our mixing variable at 1.0
31 float lightAmount = 1.0;
32 for(float i = 0.0; i < N; i++)
33 {
34 // A 0.0 - 1.0 ratio between where our current pixel is, and where the light is
35 float t = i / N;
36 // Grab a coordinate between where we are and the light
37 vec2 samplePoint = mix(normalizedFragCoord, normalizedLightCoord, t);
38 // Is there something there? If so, we'll assume we are in shadow
39 float shadowAmount = terrain(samplePoint);
40 // Multiply the light amount.
41 // (Multiply in case we want to upgrade to soft shadows)
42 lightAmount *= shadowAmount;
43 }
44
45 // Find out how much light we have based on the distance to our light
46 lightAmount *= 1.0 - smoothstep(0.0, lightSize, distanceToLight);
47
48 // We'll alternate our display between black and whatever is in channel 1
49 vec4 blackColor = vec4(0.0, 0.0, 0.0, 1.0);
50
51 // Our fragment color will be somewhere between black and channel 1
52 // dependent on the value of b.
53 fragColor = mix(blackColor, texture(iChannel1, normalizedFragCoord), lightAmount);
54}