UNPKG

2.58 kBPlain TextView Raw
1uniform sampler2D u_image;
2varying vec2 v_pos;
3
4uniform vec2 u_latrange;
5uniform vec2 u_light;
6uniform vec4 u_shadow;
7uniform vec4 u_highlight;
8uniform vec4 u_accent;
9
10#define PI 3.141592653589793
11
12void main() {
13 vec4 pixel = texture2D(u_image, v_pos);
14
15 vec2 deriv = ((pixel.rg * 2.0) - 1.0);
16
17 // We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude
18 // to account for mercator projection distortion. see #4807 for details
19 float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));
20 // We also multiply the slope by an arbitrary z-factor of 1.25
21 float slope = atan(1.25 * length(deriv) / scaleFactor);
22 float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);
23
24 float intensity = u_light.x;
25 // We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal
26 // position property to account for 0deg corresponding to north/the top of the viewport in the style spec
27 // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.
28 float azimuth = u_light.y + PI;
29
30 // We scale the slope exponentially based on intensity, using a calculation similar to
31 // the exponential interpolation function in the style spec:
32 // src/style-spec/expression/definitions/interpolate.js#L217-L228
33 // so that higher intensity values create more opaque hillshading.
34 float base = 1.875 - intensity * 1.75;
35 float maxValue = 0.5 * PI;
36 float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;
37
38 // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine
39 // so that the accent color's rate of change eases in while the shade color's eases out.
40 float accent = cos(scaledSlope);
41 // We multiply both the accent and shade color by a clamped intensity value
42 // so that intensities >= 0.5 do not additionally affect the color values
43 // while intensity values < 0.5 make the overall color more transparent.
44 vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);
45 float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);
46 vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);
47 gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;
48
49#ifdef OVERDRAW_INSPECTOR
50 gl_FragColor = vec4(1.0);
51#endif
52}