shaders/depthPack.tstypescript
import { ShaderProgram } from "../webgl/ShaderProgram";

export function depthPack(): ShaderProgram {
    return new ShaderProgram("depthPack", {
        uniforms: {
            frustumTexture: "sampler2D",
            depthTexture: "sampler2D"
        },
        attributes: {
            corners: "vec2"
        },
        vertexShader: `#version 300 es

            in vec2 corners;

            void main(void) {
                gl_Position = vec4(corners, 0.0, 1.0);
            }`,
        fragmentShader: `#version 300 es

            precision highp float;
            precision highp int;

            uniform sampler2D frustumTexture;
            uniform sampler2D depthTexture;

            layout(location = 0) out vec4 fragColor;

            void main(void) {
                ivec2 p = ivec2(gl_FragCoord.xy);

                float d = clamp(texelFetch(depthTexture, p, 0).r, 0.0, 1.0);
                float f = texelFetch(frustumTexture, p, 0).r;

                // RGBA16F values in [0, 1) are multiples of 2^-24, so the 2^24 scale packs them exactly;
                // d = 1.0 would give 2^24, it is clamped
                uint u = min(uint(d * 16777216.0 + 0.5), 16777215u);

                fragColor = vec4(
                    float((u >> 16u) & 255u),
                    float((u >> 8u) & 255u),
                    float(u & 255u),
                    floor(f * 255.0 + 0.5)
                ) / 255.0;
            }`
    });
}