Skip to content

Code-first video & image, rendered natively on WebGPU.

24.1 KB
Raw Blame
/**
 * WebGPU WGSL shaders for 3D static and skinned meshes.
 * Supports GPU Linear Blend Skinning,
 * the shared 3D surface shading (Blinn-Phong, or physical GGX + image-based light
 * in scenes with an environment) or toon shading, shadow maps, emissive,
 * alpha-cutoff (glTF MASK) materials,
 * Material parameters, normal transformations, and linear depth MRT output for Bokeh DoF.
 */

import { lighting3dWgsl, lightsBindingsWgsl } from "./lighting3d.js";
import { matte3dWgsl } from "./matte3d.js";

/** Mesh uniform, skinning, instance and vertex input structs (shared by the mesh passes). */
export const meshStructsWgsl = `
struct ModelUniforms {
    modelMatrix          : mat4x4<f32>,
    normalMatrix         : mat4x4<f32>,
    colorTint            : vec4<f32>,
    params               : vec4<f32>, // x = opacity, y = twoSided, z = isSkinned, w = flags (bit 0 instanced, bit 1 map UVs, bit 2 matrix instances)
    materialParams       : vec4<f32>, // x = shininess, y = specularIntensity, z = ambientIntensity, w = materialMode (0=unlit, 1=lit, 2=toon)
    shade                : vec4<f32>, // rgb = toon shadow-side color multiplier, a = alpha cutoff (0 = none)
    pbr                  : vec4<f32>, // x = roughness (<0 = default), y = metallic
    emissive             : vec4<f32>, // rgb = sRGB emissive color, w = strength
    toonShadow           : vec4<f32>, // rgb shadow-side multiplier, w diffuse modelling
    toonLight            : vec4<f32>, // rgb lit-side multiplier, w terminator threshold
    toonParams           : vec4<f32>, // x terminator softness, y outline participation, z sheenRoughness, w triplanarSharpness
    substrateClearcoat   : vec4<f32>, // x = clearcoat, y = clearcoatRoughness, z = anisotropy, w = anisotropyRotationRad
    substrateSubsurface  : vec4<f32>, // x = subsurface, yzw = subsurfaceColor (sRGB)
    substrateSheen       : vec4<f32>, // x = sheen, yzw = sheenColor (sRGB)
    substrateIridescence : vec4<f32>, // x = iridescence, y = thicknessNm, z = filmIor, w = triplanarUvFreq
    maps                 : vec4<f32>, // x = normal scale (0 = no map), y = occlusion strength, z = has metallic-roughness map, w = has emissive map
    uvRect               : vec4<f32>, // base-color uv' = xy + uv * zw
    wind                 : vec4<f32>, // x = amplitude rad (0 = calm), y = angular frequency, z = wave number per px, w = time s
    windFrame            : vec4<f32>, // xy = downwind (x, z), z = mesh base y, w = 1 / mesh height
    crowd                : vec4<f32>, // x = time s, z = joints per baked frame
};

struct SkinningUniforms {
    jointMatrices : array<mat4x4<f32>>,
};

struct InstanceData {
    posScale : vec4<f32>, // xyz = translation, w = scale
    quat     : vec4<f32>, // xyzw = unit rotation quaternion
    color    : vec4<f32>, // rgba = color multiplier
    emissive : vec4<f32>, // rgb = sRGB emissive color, w = emissiveIntensity
};

struct VertexInput {
    @location(0) position : vec3<f32>,
    @location(1) uv       : vec2<f32>,
    @location(2) normal   : vec3<f32>,
    @location(3) joints   : vec4<f32>,
    @location(4) weights  : vec4<f32>,
    @location(5) color    : vec4<f32>, // vertex color (display / sRGB), white when absent
    @location(6) normalUv : vec2<f32>,
    @location(7) mrUv     : vec2<f32>,
    @location(8) aoUv     : vec2<f32>,
    @location(9) emissiveUv : vec2<f32>,
    @location(10) joints1  : vec4<f32>,
    @location(11) weights1 : vec4<f32>,
};

`;

/** The deformed vertex in mesh space (before the model matrix). */
export const meshDeformStructWgsl = `
struct MeshDeform {
    localPos     : vec3<f32>,
    localNorm    : vec3<f32>,
    instColor    : vec4<f32>,
    instEmissive : vec4<f32>,
};
`;

/**
 * WGSL for the mesh vertex deformation (skinning, skinned crowds,
 * instancing, wind) as \`fn deform${n}(in, instanceIndex) -> MeshDeform\`,
 * reading the named model uniform, skinning and instance bindings. The
 * color pass and the velocity pass (current and previous frame) share it.
 */
export function meshDeformWgsl(
	n: string,
	model: string,
	skin: string,
	inst: string,
): string {
	return `
// Wind lean in radians at a plant rooted at ground point root: a steady
// push plus a traveling wave and a faster flutter, so neighbors sway together
// and the far field lags the near one.
fn windAngle${n}(root: vec2<f32>) -> f32 {
    let w = ${model}.wind;
    let phase = dot(root, ${model}.windFrame.xy) * w.z - w.w * w.y;
    return w.x * (0.55 + 0.35 * sin(phase) + 0.1 * sin(phase * 2.7 + 1.3));
}

// Bends a vertex (mesh space, scale s) downwind: the base stays put,
// the tip leans furthest, along an arc so the stem keeps its length.
fn windBend${n}(local: vec3<f32>, angle: f32, s: f32) -> vec3<f32> {
    let h = max(${model}.windFrame.z - local.y, 0.0);
    let k = clamp(h * ${model}.windFrame.w, 0.0, 1.0);
    let a = angle * k * k;
    let downwind = vec3<f32>(${model}.windFrame.x, 0.0, ${model}.windFrame.y);
    return downwind * (sin(a) * h * s) + vec3<f32>(0.0, (1.0 - cos(a)) * h * s, 0.0);
}

// A crowd joint: two baked frames of the palette, blended.
fn crowdJoint${n}(base0: u32, base1: u32, t: f32, joint: u32) -> mat4x4<f32> {
    return ${skin}.jointMatrices[base0 + joint] * (1.0 - t) +
        ${skin}.jointMatrices[base1 + joint] * t;
}

fn deform${n}(in: VertexInput, instanceIndex: u32) -> MeshDeform {
    var localPos = in.position;
    var localNorm = in.normal;

    // Crowd instances (flag bit 3) carry a second record: (clip's first
    // baked frame, its frames per loop, phase in frames, frames per second), and skin from a
    // baked joint palette at their own point in their own clip.
    let flags = u32(${model}.params.w);
    let crowd = (flags & 8u) != 0u;
    var palette0 = 0u;
    var palette1 = 0u;
    var paletteT = 0.0;
    if (crowd) {
        let anim = ${inst}[instanceIndex * 2u + 1u].posScale;
        let count = max(anim.y, 1.0);
        let f = anim.z + ${model}.crowd.x * anim.w;
        let wrapped = f - floor(f / count) * count;
        let f0 = floor(wrapped);
        let jc = u32(${model}.crowd.z);
        palette0 = (u32(anim.x) + u32(f0)) * jc;
        // Each clip bakes count + 1 samples (its end too): no wrap inside a loop.
        palette1 = (u32(anim.x) + u32(f0) + 1u) * jc;
        paletteT = wrapped - f0;
    }

    // Linear Blend Skinning (LBS) on GPU
    if (${model}.params.z > 0.5) {
        let j0 = u32(in.joints.x);
        let j1 = u32(in.joints.y);
        let j2 = u32(in.joints.z);
        let j3 = u32(in.joints.w);

        let w0 = in.weights.x;
        let w1 = in.weights.y;
        let w2 = in.weights.z;
        let w3 = in.weights.w;

        // A second set of four influences (glTF JOINTS_1 / WEIGHTS_1), when flagged.
        let eight = (u32(${model}.params.w) & 16u) != 0u;
        let wb = select(vec4<f32>(0.0), in.weights1, eight);
        let jb = vec4<u32>(select(vec4<f32>(0.0), in.joints1, eight));

        let totalWeight = w0 + w1 + w2 + w3 + wb.x + wb.y + wb.z + wb.w;
        var skinMat = mat4x4<f32>();
        if (crowd) {
            // A node-attached (rigid) mesh bakes its node as joint 0.
            if (totalWeight <= 0.001) {
                skinMat = crowdJoint${n}(palette0, palette1, paletteT, 0u);
            } else {
                skinMat = crowdJoint${n}(palette0, palette1, paletteT, j0) * w0 +
                    crowdJoint${n}(palette0, palette1, paletteT, j1) * w1 +
                    crowdJoint${n}(palette0, palette1, paletteT, j2) * w2 +
                    crowdJoint${n}(palette0, palette1, paletteT, j3) * w3;
                if (eight) {
                    skinMat += crowdJoint${n}(palette0, palette1, paletteT, jb.x) * wb.x +
                        crowdJoint${n}(palette0, palette1, paletteT, jb.y) * wb.y +
                        crowdJoint${n}(palette0, palette1, paletteT, jb.z) * wb.z +
                        crowdJoint${n}(palette0, palette1, paletteT, jb.w) * wb.w;
                }
            }
        } else if (totalWeight > 0.001) {
            skinMat = ${skin}.jointMatrices[j0] * w0 +
                      ${skin}.jointMatrices[j1] * w1 +
                      ${skin}.jointMatrices[j2] * w2 +
                      ${skin}.jointMatrices[j3] * w3;
            if (eight) {
                skinMat += ${skin}.jointMatrices[jb.x] * wb.x +
                           ${skin}.jointMatrices[jb.y] * wb.y +
                           ${skin}.jointMatrices[jb.z] * wb.z +
                           ${skin}.jointMatrices[jb.w] * wb.w;
            }
        }
        if (crowd || totalWeight > 0.001) {
            let pos4 = skinMat * vec4<f32>(in.position, 1.0);
            localPos = pos4.xyz;

            let norm4 = skinMat * vec4<f32>(in.normal, 0.0);
            localNorm = normalize(norm4.xyz);
        }
    }

    // Hardware instancing: transform local vertex by instance transform
    // Static read prevents Tint from dropping the storage buffer binding
    let dummyInst = ${inst}[0].posScale.x;
    var instColor = vec4<f32>(1.0);
    var instEmissive = vec4<f32>(0.0);

    let windy = ${model}.wind.x != 0.0;
    if ((u32(${model}.params.w) & 4u) != 0u) {
        let a = ${inst}[instanceIndex * 2u];
        let b = ${inst}[instanceIndex * 2u + 1u];
        let instanceModel = mat4x4<f32>(a.posScale, a.quat, a.color, a.emissive);
        let instanceNormal = mat4x4<f32>(b.posScale, b.quat, b.color, b.emissive);
        localPos = (instanceModel * vec4<f32>(localPos, 1.0)).xyz;
        localNorm = (instanceNormal * vec4<f32>(localNorm, 0.0)).xyz;
    } else if ((u32(${model}.params.w) & 1u) != 0u) {
        let inst = ${inst}[select(instanceIndex, instanceIndex * 2u, crowd)];
        let scaledPos = localPos * inst.posScale.w;
        var bend = vec3<f32>(0.0);
        if (windy) {
            bend = windBend${n}(localPos, windAngle${n}(inst.posScale.xz), inst.posScale.w);
        }
        localPos = rotateVecByQuat(scaledPos, inst.quat) + inst.posScale.xyz + bend;
        localNorm = rotateVecByQuat(localNorm, inst.quat);
        instColor = inst.color;
        instEmissive = inst.emissive;
    } else {
        localPos.x += dummyInst * 0.0;
        if (windy) {
            localPos += windBend${n}(localPos, windAngle${n}(vec2<f32>(0.0)), 1.0);
        }
    }

    return MeshDeform(localPos, localNorm, instColor, instEmissive);
}
`;
}

export const mesh3dWgsl = `
${lighting3dWgsl}

${meshStructsWgsl}
@group(0) @binding(0) var<uniform> cam      : CameraUniforms;
@group(1) @binding(0) var<uniform> model    : ModelUniforms;
@group(1) @binding(1) var<storage, read> skinning : SkinningUniforms;
${matte3dWgsl(1, 2)}@group(1) @binding(3) var backdropTex : texture_2d<f32>;
@group(1) @binding(4) var<storage, read> instances : array<InstanceData>;
@group(2) @binding(0) var texSampler        : sampler;
@group(2) @binding(1) var mainTex           : texture_2d<f32>;
@group(2) @binding(2) var normalTex         : texture_2d<f32>;
@group(2) @binding(3) var metalRoughTex     : texture_2d<f32>;
@group(2) @binding(4) var occlusionTex      : texture_2d<f32>;
@group(2) @binding(5) var emissiveTex       : texture_2d<f32>;
@group(2) @binding(6) var normalSampler     : sampler;
@group(2) @binding(7) var metalRoughSampler : sampler;
@group(2) @binding(8) var occlusionSampler  : sampler;
@group(2) @binding(9) var emissiveSampler   : sampler;
${lightsBindingsWgsl}

struct VertexOutput {
    @builtin(position) clipPos     : vec4<f32>,
    @location(0)       uv          : vec2<f32>,
    @location(1)       worldPos    : vec3<f32>,
    @location(2)       worldNormal : vec3<f32>,
    @location(3)       linearDepth : f32,
    @location(4)       color       : vec4<f32>,
    @location(5)       normalUv    : vec2<f32>,
    @location(6)       mrUv        : vec2<f32>,
    @location(7)       aoUv        : vec2<f32>,
    @location(8)       emissiveUv  : vec2<f32>,
    @location(9)       emissive    : vec4<f32>,
};

fn rotateVecByQuat(v: vec3<f32>, q: vec4<f32>) -> vec3<f32> {
    let t = 2.0 * cross(q.xyz, v);
    return v + q.w * t + cross(q.xyz, t);
}

${meshDeformStructWgsl}
${meshDeformWgsl("", "model", "skinning", "instances")}
@vertex
fn vs_main(
    in: VertexInput,
    @builtin(instance_index) instanceIndex: u32,
) -> VertexOutput {
    var out: VertexOutput;

    let deformed = deform(in, instanceIndex);
    let localPos = deformed.localPos;
    let localNorm = deformed.localNorm;
    let instColor = deformed.instColor;
    let instEmissive = deformed.instEmissive;

    let worldPos4 = model.modelMatrix * vec4<f32>(localPos, 1.0);
    out.worldPos = worldPos4.xyz;

    let norm4 = model.normalMatrix * vec4<f32>(localNorm, 0.0);
    out.worldNormal = normalize(norm4.xyz);

    out.clipPos = cam.viewProjMatrix * worldPos4;
    out.uv = model.uvRect.xy + in.uv * model.uvRect.zw;
    let hasMapUvs = (u32(model.params.w) & 2u) != 0u;
    out.normalUv = select(in.uv, in.normalUv, hasMapUvs);
    out.mrUv = select(in.uv, in.mrUv, hasMapUvs);
    out.aoUv = select(in.uv, in.aoUv, hasMapUvs);
    out.emissiveUv = select(in.uv, in.emissiveUv, hasMapUvs);
    out.color = in.color * instColor;
    out.emissive = instEmissive;

    out.linearDepth = dot(worldPos4.xyz - cam.cameraPos.xyz, cam.cameraDir.xyz);
    return out;
}

struct MeshFragment {
    color : vec4<f32>, // premultiplied display color
    hdr   : vec4<f32>, // premultiplied scene radiance (bloom source)
};

// Normal mapping without tangents: a cotangent frame from screen-space
// derivatives (Schüler, "Followup: Normal Mapping Without Precomputed Tangents").
fn perturbNormal(N: vec3<f32>, p: vec3<f32>, uv: vec2<f32>, tn: vec3<f32>, dp1: vec3<f32>, dp2: vec3<f32>, duv1: vec2<f32>, duv2: vec2<f32>) -> vec3<f32> {
    let dp2perp = cross(dp2, N);
    let dp1perp = cross(N, dp1);
    // The derivation assumes cross(dp1, dp2) points along N; with this
    // engine's y-down view basis it can point away, mirroring the frame.
    let handed = select(1.0, -1.0, dot(cross(dp1, dp2), N) < 0.0);
    let T = (dp2perp * duv1.x + dp1perp * duv2.x) * handed;
    let B = (dp2perp * duv1.y + dp1perp * duv2.y) * handed;
    let invmax = inverseSqrt(max(max(dot(T, T), dot(B, B)), 1e-20));
    // glTF maps are +Y up while v grows down the image: green points along -B.
    return normalize(T * (tn.x * invmax) - B * (tn.y * invmax) + N * tn.z);
}

// Glass: what is behind the 3D batch on screen (backdrop), bent by
// refraction along the surface normal with a red/blue split, frosted by a
// disc blur, tinted by the color, under Fresnel-weighted reflections.
// shade.rgb = (dispersion, thickness px, frost), pbr.w = ior.
fn backdropAt(uv: vec2<f32>) -> vec3<f32> {
    return textureSampleLevel(backdropTex, texSampler, clamp(uv, vec2<f32>(0.001), vec2<f32>(0.999)), 0.0).rgb;
}

// rimWidth: how much 1 - N·V changes across this pixel (fwidth, taken in
// uniform control flow by the caller). Rim effects narrower than a pixel are
// faded out, or per-pixel shading turns them into stair-stepped lines that
// MSAA (coverage only) cannot smooth.
fn shadeGlass(in: VertexOutput, Nin: vec3<f32>, tint: vec3<f32>, alpha: f32, rimWidth: f32) -> MeshFragment {
    let V = normalize(cam.cameraPos.xyz - in.worldPos);
    var N = Nin;
    if (dot(N, V) < 0.0) { N = -N; }
    let NdotV = clamp(dot(N, V), 0.0, 1.0);
    // Also fade toward edge-on: a face seen at a grazing angle is a sliver
    // under a pixel tall (a slab's bottom), which would alias the same way.
    let rimAA = clamp(1.0 - rimWidth * 2.5, 0.0, 1.0) * smoothstep(0.03, 0.22, NdotV);
    let rim = (1.0 - NdotV) * rimAA;
    let ior = max(model.pbr.w, 1.0001);
    let screen = max(cam.screenParams.xy, vec2<f32>(1.0));
    let uv = in.clipPos.xy / screen;
    // Screen-space bend. A world thickness (model files, stored negative):
    // where the refracted ray leaves the material, projected, against where
    // the straight ray would; it scales with distance like the object does.
    // Otherwise a bend in px: the normal's in-plane part, stronger toward the rim.
    var bend = N.xy * model.shade.g * (1.0 - 1.0 / ior) * (0.6 + rim) * rimAA / screen;
    if (model.shade.g < 0.0) {
        let t = -model.shade.g;
        let exitW = in.worldPos + refract(-V, N, 1.0 / ior) * t;
        let straightW = in.worldPos - V * t;
        let a = cam.viewProjMatrix * vec4<f32>(exitW, 1.0);
        let b = cam.viewProjMatrix * vec4<f32>(straightW, 1.0);
        let dNdc = a.xy / a.w - b.xy / b.w;
        bend = -vec2<f32>(dNdc.x * 0.5, -dNdc.y * 0.5);
    }
    let disp = model.shade.r;
    let frost = model.shade.b * 22.0 / screen;
    var col = vec3<f32>(0.0);
    let taps = select(1, 8, model.shade.b > 0.001);
    for (var i = 0; i < taps; i++) {
        let a = f32(i) * 2.399963;
        let r = sqrt((f32(i) + 0.5) / f32(taps));
        let o = select(vec2<f32>(0.0), vec2<f32>(cos(a), sin(a)) * r * frost, taps > 1);
        col += vec3<f32>(
            backdropAt(uv - bend * (1.0 + disp * 6.0) + o).r,
            backdropAt(uv - bend + o).g,
            backdropAt(uv - bend * (1.0 - disp * 6.0) + o).b,
        );
    }
    col /= f32(taps);
    // Light travels further through the glass toward the rim: the tint
    // deepens and the body darkens there, which is what outlines glass.
    let depthTint = mix(vec3<f32>(1.0), tint, 0.55 + 0.45 * rim);
    let transmitted = col * depthTint * (1.0 - 0.45 * rim * rim);
    let f0 = pow((ior - 1.0) / (ior + 1.0), 2.0);
    let F = f0 + (1.0 - f0) * pow(rim, 5.0);
    let lit = shadeSurfaceFull(in.worldPos, N, vec3<f32>(0.0), model.materialParams, vec4<f32>(model.pbr.x, 0.0, 0.0, 0.0), vec4<f32>(0.0), model.toonShadow, model.toonLight, model.toonParams);
    // Grazing faces mirror the room; keep that faint so dark scenes stay dark
    // and the studio highlights below carry the shape.
    let sheen = vec3<f32>(0.9, 0.94, 1.0) * F * 0.22 + tint * 0.05 * (0.4 + rim);
    // A studio in the reflection: a sharp key and two strip softboxes, which
    // is most of what makes glass read as glass.
    let R = reflect(-V, N);
    // Tight: a flat face only flashes as it turns through the light.
    let key = pow(max(dot(R, normalize(vec3<f32>(-0.45, -0.75, -0.5))), 0.0), 600.0) * 1.8;
    // Two tall softboxes: narrow bands in the reflection, brightest above.
    let strips = (1.0 - smoothstep(0.03, 0.07, abs(R.x + 0.45))) * smoothstep(0.3, -0.5, R.y) * 1.1
        + (1.0 - smoothstep(0.02, 0.05, abs(R.x - 0.6))) * smoothstep(0.4, -0.3, R.y) * 0.7;
    let studio = vec3<f32>(1.0, 0.98, 0.95) * (key + strips * (0.25 + F));
    // A thin bright line where the surface turns away: glass silhouettes.
    let edge = vec3<f32>(1.0, 0.99, 0.97) * smoothstep(0.8, 0.97, rim) * 0.55;
    let rgb = transmitted * (1.0 - F) + lit.display + sheen + studio + edge;
    var out: MeshFragment;
    out.color = vec4<f32>(rgb * alpha, alpha);
    out.hdr = vec4<f32>(srgbToLinear(transmitted * (1.0 - F)) * alpha + lit.hdr * alpha + srgbToLinear(sheen + studio + edge) * alpha, alpha);
    return out;
}

fn sampleTriplanar4(tex: texture_2d<f32>, p: vec3<f32>, dp1: vec3<f32>, dp2: vec3<f32>, weights: vec3<f32>) -> vec4<f32> {
    let sx = textureSampleGrad(tex, texSampler, fract(p.zy), dp1.zy, dp2.zy);
    let sy = textureSampleGrad(tex, texSampler, fract(p.xz), dp1.xz, dp2.xz);
    let sz = textureSampleGrad(tex, texSampler, fract(p.xy), dp1.xy, dp2.xy);
    return sx * weights.x + sy * weights.y + sz * weights.z;
}

fn shadeMesh(in: VertexOutput, isFront: bool) -> MeshFragment {
    // Every sample and derivative up front, in uniform control flow.
    measureSpecularFilter(in.worldNormal);
    var texColor = textureSample(mainTex, texSampler, in.uv);
    var normalSample = textureSample(normalTex, normalSampler, in.normalUv).xyz;
    var mrSample = textureSample(metalRoughTex, metalRoughSampler, in.mrUv);
    var aoSample = textureSample(occlusionTex, occlusionSampler, in.aoUv).r;
    var emissiveSample = textureSample(emissiveTex, emissiveSampler, in.emissiveUv).rgb;
    let dp1 = dpdx(in.worldPos);
    let dp2 = dpdy(in.worldPos);
    let duv1 = dpdx(in.normalUv);
    let duv2 = dpdy(in.normalUv);
    let rimWidth = fwidth(1.0 - abs(dot(normalize(in.worldNormal), normalize(cam.cameraPos.xyz - in.worldPos))));

    let triFreq = model.substrateIridescence.w;
    if (triFreq > 0.0) {
        let sharpness = max(1.0, model.toonParams.w);
        let absN = max(abs(normalize(in.worldNormal)), vec3<f32>(1e-4));
        let wPow = pow(absN, vec3<f32>(sharpness));
        let wTri = wPow / max(wPow.x + wPow.y + wPow.z, 1e-5);
        let pTri = in.worldPos * triFreq;
        let dp1Tri = dp1 * triFreq;
        let dp2Tri = dp2 * triFreq;
        texColor = sampleTriplanar4(mainTex, pTri, dp1Tri, dp2Tri, wTri);
        if (model.maps.x > 0.0) {
            normalSample = sampleTriplanar4(normalTex, pTri, dp1Tri, dp2Tri, wTri).xyz;
        }
        if (model.maps.z > 0.5) {
            mrSample = sampleTriplanar4(metalRoughTex, pTri, dp1Tri, dp2Tri, wTri);
        }
        if (model.maps.y > 0.0) {
            aoSample = sampleTriplanar4(occlusionTex, pTri, dp1Tri, dp2Tri, wTri).r;
        }
        if (model.maps.w > 0.5) {
            emissiveSample = sampleTriplanar4(emissiveTex, pTri, dp1Tri, dp2Tri, wTri).rgb;
        }
    }

    if (!isFront && model.params.y < 0.5) {
        discard;
    }
    if (texColor.a < model.shade.a) {
        discard;
    }
    let alpha = texColor.a * in.color.a * model.params.x * model.colorTint.a * matteCoverage(in.clipPos.xy);
    if (alpha <= 0.001) {
        discard;
    }

    let baseRgb = texColor.rgb * in.color.rgb * model.colorTint.rgb;
    var out: MeshFragment;
    var N = normalize(in.worldNormal);
    if (model.maps.x > 0.0) {
        var tn = normalSample * 2.0 - 1.0;
        tn = vec3<f32>(tn.xy * model.maps.x, tn.z);
        // The frame follows the surface side the camera sees.
        var Nf = N;
        if (dot(Nf, cam.cameraPos.xyz - in.worldPos) < 0.0) {
            Nf = -Nf;
        }
        N = perturbNormal(Nf, in.worldPos, in.normalUv, tn, dp1, dp2, duv1, duv2);
    }
    var pbr = model.pbr;
    if (model.maps.z > 0.5) {
        pbr.x = select(pbr.x, 1.0, pbr.x < 0.0) * mrSample.g;
        pbr.y = pbr.y * mrSample.b;
    }
    if (model.pbr.z > 0.5) {
        return shadeGlass(in, N, baseRgb, alpha, rimWidth);
    }
    var material = model.materialParams;
    material.z = material.z * mix(1.0, aoSample, clamp(model.maps.y, 0.0, 1.0));
    var emissive = model.emissive;
    if (model.maps.w > 0.5) {
        // Linear multiply in display space is close enough for an 8-bit map.
        emissive = vec4<f32>(emissive.rgb * emissiveSample, emissive.w);
    }
    if (model.params.w > 0.5 && (in.emissive.w > 0.0 || dot(in.emissive.rgb, in.emissive.rgb) > 0.0)) {
        emissive = in.emissive;
    }
    let substrate = SubstrateParams(
        model.substrateClearcoat,
        model.substrateSubsurface,
        model.substrateSheen,
        model.substrateIridescence,
    );
    let shaded = shadeSurfaceSubstrate(in.worldPos, N, baseRgb, material, pbr, emissive, model.toonShadow, model.toonLight, model.toonParams, substrate);
    out.color = vec4<f32>(shaded.display * alpha, alpha);
    out.hdr = vec4<f32>(shaded.hdr * alpha, alpha);
    return out;
}

struct MrtOutput {
    @location(0) color : vec4<f32>,
    @location(1) depth : vec4<f32>,
};

struct BloomOutput {
    @location(0) color : vec4<f32>,
    @location(1) hdr   : vec4<f32>,
};

struct MrtBloomOutput {
    @location(0) color : vec4<f32>,
    @location(1) depth : vec4<f32>,
    @location(2) hdr   : vec4<f32>,
};

@fragment
fn fs_single(in: VertexOutput, @builtin(front_facing) isFront: bool) -> @location(0) vec4<f32> {
    return shadeMesh(in, isFront).color;
}

@fragment
fn fs_mrt(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtOutput {
    var out: MrtOutput;
    out.color = shadeMesh(in, isFront).color;
    out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);
    return out;
}

@fragment
fn fs_single_bloom(in: VertexOutput, @builtin(front_facing) isFront: bool) -> BloomOutput {
    let f = shadeMesh(in, isFront);
    var out: BloomOutput;
    out.color = f.color;
    out.hdr = f.hdr;
    return out;
}

@fragment
fn fs_mrt_bloom(in: VertexOutput, @builtin(front_facing) isFront: bool) -> MrtBloomOutput {
    let f = shadeMesh(in, isFront);
    var out: MrtBloomOutput;
    out.color = f.color;
    out.depth = geometryPixel(in.linearDepth, in.worldNormal, model.toonParams.y);
    out.hdr = f.hdr;
    return out;
}
`;