Metallic Flake Clearcoat shader

metallic-flake-clearcoat.glsl · 765 lines · GLSL ES 3.00 · MIT

Metallic Flake ClearcoatMetals & Armor
Metallic Flake Clearcoat WebGL2 procedural shader preview
FPS 60BUFFER 960×540SOURCE 765 linesSPEC GLSL ES 3.00

Seamless PNG Texture Baker
1-Click Engine Shader Export
WebGL2 .glsl
.glsl
Godot 4 .gdshader
Three.js GLSL3

Engine shader code & wrappers

Industrial Metals
metallic-flake-clearcoat.glsl (765 lines)
#version 300 es
// Metallic Flake Clearcoat (metallic-flake-clearcoat.glsl)
// Upstream study: https://github.com/gokayfem/glsl-studies/blob/main/metals/lib/03_metallic_flake_clearcoat_car_paint.glsl
// License: MIT (Copyright 2026 Gokay Aydogan) + MIT/CC0 helpers — https://pixelfx.io/LICENSE-SHADERS.txt
// Uniforms: uResolution (vec2), uTime (float), uOpen (0..1), uLightMode (0..3), uCamMode (0..1)
precision highp float;
precision highp int;

uniform vec2 uResolution;
uniform float uTime;
uniform float uOpen;
uniform int uLightMode;
uniform int uCamMode;

out vec4 fragColor;

// -----------------------------------------------------------------------------
// Constants & Helpers
// -----------------------------------------------------------------------------
const float PI = 3.14159265359;
const float INV_PI = 0.31830988618;
const float MAX_DIST = 24.0;

mat2 rot2(float a) {
    float c = cos(a);
    float s = sin(a);
    return mat2(c, -s, s, c);
}

float smin(float a, float b, float k) {
    float h = max(k - abs(a - b), 0.0) / k;
    return min(a, b) - h * h * k * 0.25;
}

float smax(float a, float b, float k) {
    return -smin(-a, -b, k);
}

float sdEllipsoid(vec3 p, vec3 r) {
    float k0 = length(p / r);
    float k1 = length(p / (r * r));
    return k0 * (k0 - 1.0) / max(k1, 1e-5);
}

// Fast deterministic 3D hashes for micro-flakes & subtle studio surface grain
vec3 hash33(vec3 p) {
    p = vec3(
        dot(p, vec3(127.1, 311.7, 74.7)),
        dot(p, vec3(269.5, 183.3, 246.1)),
        dot(p, vec3(113.5, 271.9, 124.6))
    );
    return fract(sin(p) * 43758.5453123);
}

float hash12(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * 0.1031);
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.x + p3.y) * p3.z);
}

float valueNoise3D(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    vec3 u = f * f * (3.0 - 2.0 * f);

    float n000 = fract(sin(dot(i + vec3(0,0,0), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n100 = fract(sin(dot(i + vec3(1,0,0), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n010 = fract(sin(dot(i + vec3(0,1,0), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n110 = fract(sin(dot(i + vec3(1,1,0), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n001 = fract(sin(dot(i + vec3(0,0,1), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n101 = fract(sin(dot(i + vec3(1,0,1), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n011 = fract(sin(dot(i + vec3(0,1,1), vec3(127.1, 311.7, 74.7))) * 43758.5453);
    float n111 = fract(sin(dot(i + vec3(1,1,1), vec3(127.1, 311.7, 74.7))) * 43758.5453);

    float nx00 = mix(n000, n100, u.x);
    float nx10 = mix(n010, n110, u.x);
    float nx01 = mix(n001, n101, u.x);
    float nx11 = mix(n011, n111, u.x);

    float nxy0 = mix(nx00, nx10, u.y);
    float nxy1 = mix(nx01, nx11, u.y);
    return mix(nxy0, nxy1, u.z);
}

// -----------------------------------------------------------------------------
// Geometry: 3D Sculpted Automotive Speed-Shape ("Paint Display Frog")
// -----------------------------------------------------------------------------
vec3 toHeroLocal(vec3 p) {
    // Classic 3/4 automotive studio yaw orientation on the bench
    vec3 q = p;
    q.xz = rot2(-0.32) * q.xz;
    return q;
}

float mapHero(vec3 p) {
    vec3 q = toHeroLocal(p);

    // Quick bounding sphere rejection for speed
    float bound = length(q - vec3(0.0, 0.34, 0.0)) - 1.85;
    if (bound > 0.35) return bound;

    // Mirror Z for bilateral automotive symmetry
    vec3 qs = vec3(q.x, q.y, abs(q.z));

    // 1. Main low-slung aerodynamic fuselage with subtle forward nose taper
    vec3 pBody = q - vec3(0.02, 0.14, 0.0);
    // Gentle camber arch along X
    pBody.y -= 0.06 * cos(clamp(q.x * 1.05, -PI, PI));
    // Subtle front taper & wider rear stance
    float widthScale = 1.0 - 0.14 * smoothstep(-0.2, 1.35, q.x) + 0.08 * smoothstep(-0.2, -1.25, q.x);
    pBody.z /= widthScale;
    float dBody = sdEllipsoid(pBody, vec3(1.42, 0.40, 0.68));

    // 2. Sweeping fastback cockpit canopy / central greenhouse dome
    vec3 pCanopy = q - vec3(-0.18, 0.44, 0.0);
    pCanopy.y += 0.05 * q.x; // rake forward into windshield/hood flow
    float dCanopy = sdEllipsoid(pCanopy, vec3(0.86, 0.36, 0.44));

    // 3. Sculpted hood power-bulge flowing forward from canopy
    vec3 pHood = q - vec3(0.46, 0.28, 0.0);
    pHood.y += 0.14 * (q.x - 0.46); // downward aerodynamic nose dive
    float dHood = sdEllipsoid(pHood, vec3(0.76, 0.24, 0.42));

    // 4. Muscular front fender haunches (mirror-symmetric)
    vec3 pFrontFender = qs - vec3(0.62, 0.25, 0.44);
    pFrontFender.xy = rot2(-0.14) * pFrontFender.xy;
    float dFrontFender = sdEllipsoid(pFrontFender, vec3(0.56, 0.25, 0.27));

    // 5. Broad rear fender haunches (classic sports-car hip swell)
    vec3 pRearFender = qs - vec3(-0.62, 0.30, 0.47);
    pRearFender.xy = rot2(0.10) * pRearFender.xy;
    float dRearFender = sdEllipsoid(pRearFender, vec3(0.62, 0.29, 0.31));

    // Smoothly fuse primary sculpted volumes
    float d = smin(dBody, dCanopy, 0.24);
    d = smin(d, dHood, 0.20);
    d = smin(d, dFrontFender, 0.18);
    d = smin(d, dRearFender, 0.20);

    // 6. Subtle concave door-waist scallop between front & rear haunches
    // Gives dramatic S-curve clearcoat reflections along the flank
    vec3 pWaist = qs - vec3(-0.02, 0.23, 0.86);
    float dWaistCut = sdEllipsoid(pWaist, vec3(0.56, 0.24, 0.28));
    d = smax(d, -dWaistCut, 0.12);

    // 7. Subtle aerodynamic hood twin-crease & shoulder character line
    float hoodMask = smoothstep(0.05, 0.55, q.x) * smoothstep(1.32, 0.78, q.x) * smoothstep(0.15, 0.38, q.y);
    float creaseZ = abs(qs.z - 0.24);
    float hoodCrease = exp(-creaseZ * creaseZ * 140.0) * hoodMask * 0.010;
    d -= hoodCrease;

    // 8. Crisp lower base trim sitting cleanly flush on the studio bench (y = 0.0)
    // Slight chamfered tuck right above the bench for realistic molded speed-shape lip
    float dBottom = -q.y;
    d = smax(d, dBottom, 0.022);

    // Conservative Lipschitz safety factor for smooth raymarching on warped ellipsoids
    return d * 0.78;
}

float mapScene(vec3 p) {
    float dHero = mapHero(p);
    float dBench = p.y;
    return min(dHero, dBench);
}

// Rule 1: Unit-weight tetrahedral normals
vec3 calcNormal(vec3 p) {
    const float h = 0.0005;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapScene(p + k.xyy * h) +
        k.yyx * mapScene(p + k.yyx * h) +
        k.yxy * mapScene(p + k.yxy * h) +
        k.xxx * mapScene(p + k.xxx * h)
    );
}

// Rule 3: Clean hero-only soft shadow (no ph, bias p+N*0.014, tMin=0.025, step max(h,0.015))
float softShadow(vec3 ro, vec3 rd, float tMax, float k) {
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 48; i++) {
        float h = mapHero(ro + rd * t);
        if (h < 0.0004) return 0.0;
        res = min(res, k * h / t);
        t += max(h, 0.015);
        if (t > tMax) break;
    }
    return clamp(res, 0.0, 1.0);
}

float calcAO(vec3 p, vec3 n) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 0; i < 5; i++) {
        float h = 0.018 + 0.085 * float(i);
        float d = mapScene(p + n * h);
        occ += (h - d) * sca;
        sca *= 0.72;
    }
    return clamp(1.0 - 2.3 * occ, 0.12, 1.0);
}

// -----------------------------------------------------------------------------
// High-Contrast Automotive Studio Environment (Softboxes + Negative-Fill Flags)
// -----------------------------------------------------------------------------
float softboxRect(vec2 uv, vec2 halfSize, float edge) {
    vec2 d = abs(uv) - halfSize;
    float dist = length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
    return 1.0 - smoothstep(-edge, edge, dist);
}

vec3 evalStudioEnv(vec3 rd, float rough) {
    vec3 d = normalize(rd);
    float blur = mix(0.018, 0.42, clamp(rough, 0.0, 1.0));

    // Base dark architectural studio cyclorama (high contrast for automotive clearcoat)
    float up = clamp(d.y, 0.0, 1.0);
    float down = clamp(-d.y, 0.0, 1.0);

    vec3 col = mix(vec3(0.055, 0.062, 0.075), vec3(0.028, 0.032, 0.040), pow(up, 0.65));
    col = mix(col, vec3(0.022, 0.024, 0.028), pow(down, 0.5));

    // Subtle luminous studio horizon seam
    float horizonGlow = exp(-abs(d.y) * mix(16.0, 4.5, rough));
    col += vec3(0.09, 0.10, 0.12) * horizonGlow;

    // Light color palettes per uLightMode
    vec3 tintMain = vec3(0.96, 0.98, 1.03);
    vec3 tintSide = vec3(1.04, 0.98, 0.92);
    vec3 tintRim  = vec3(0.86, 0.93, 1.06);
    float mainGain = 1.0;
    float sideGain = 1.0;
    float rimGain  = 1.0;
    float backGain = 0.0;

    if (uLightMode == 1) {
        // Pure neutral grayscale studio lighting
        col = vec3(dot(col, vec3(0.299, 0.587, 0.114)));
        tintMain = vec3(1.0);
        tintSide = vec3(1.0);
        tintRim  = vec3(1.0);
    } else if (uLightMode == 2) {
        // Grazing raking strip lighting
        mainGain = 0.35;
        sideGain = 1.65;
        rimGain  = 1.35;
        tintSide = vec3(1.05, 0.96, 0.88);
    } else if (uLightMode == 3) {
        // Backlit cyclorama silhouette (controlled backdrop so rim pops)
        mainGain = 0.25;
        sideGain = 0.42;
        rimGain  = 1.25;
        backGain = 1.45;
    }

    // Spherical/planar projection coordinates for studio light banks
    float az = atan(d.z, d.x);
    float el = asin(clamp(d.y, -1.0, 1.0));

    // 1. Overhead elongated automotive softbox bank (projects cleanly on roof & hood)
    if (d.y > 0.05) {
        vec2 topUV = d.xz / max(d.y, 0.18);
        topUV = rot2(0.32) * topUV;
        float sbMain = softboxRect(topUV - vec2(0.0, 0.08), vec2(1.20, 0.30), blur * 1.6);
        // Subtle softbox diffuser vignette (brighter center, crisp border)
        float innerGrad = 0.78 + 0.22 * exp(-dot(topUV * vec2(0.6, 1.6), topUV * vec2(0.6, 1.6)));
        col += tintMain * (sbMain * innerGrad * 2.25 * mainGain) * smoothstep(0.05, 0.25, d.y);

        // Twin narrow overhead accent ribs flanking the main softbox
        float sbRib = softboxRect(vec2(topUV.x, abs(topUV.y - 0.08) - 0.68), vec2(1.08, 0.065), blur * 1.2);
        col += tintMain * (sbRib * 0.95 * mainGain) * smoothstep(0.08, 0.25, d.y);
    }

    // 2. Classic automotive horizontal side strip-light (draws razor-sharp ribbon across flank)
    float sideAz = az - 0.65;
    sideAz = atan(sin(sideAz), cos(sideAz));
    float sideEl = (uLightMode == 2) ? 0.16 : 0.30;
    float sbSide = softboxRect(vec2(sideAz, el - sideEl), vec2(0.86, 0.070), blur * 0.9);
    col += tintSide * (sbSide * 2.05 * sideGain);

    // 3. Opposite cool rim strip-light
    float rimAz = az + 2.35;
    rimAz = atan(sin(rimAz), cos(rimAz));
    float sbRim = softboxRect(vec2(rimAz, el - 0.36), vec2(0.74, 0.090), blur * 1.0);
    col += tintRim * (sbRim * 1.55 * rimGain);

    // 4. Backlit studio lightwall (active in uLightMode == 3)
    if (backGain > 0.01) {
        float backAz = az + 2.15;
        backAz = atan(sin(backAz), cos(backAz));
        float sbBack = softboxRect(vec2(backAz, el - 0.14), vec2(0.76, 0.34), blur * 1.4);
        col += vec3(0.95, 0.97, 1.02) * (sbBack * backGain);
    }

    // 5. Dark Negative-Fill Flags (gobos) right below the side strip & at mid-azimuth
    // Creates dramatic black-to-white crisp transitions on the curved clearcoat!
    float negFlag1 = softboxRect(vec2(sideAz, el - (sideEl - 0.19)), vec2(1.05, 0.085), blur * 0.7);
    float negFlag2 = softboxRect(vec2(az - 2.1, el - 0.22), vec2(0.55, 0.22), blur * 0.8);
    float negMask = clamp(negFlag1 + negFlag2 * 0.8, 0.0, 1.0);
    col *= mix(1.0, 0.14, negMask * (1.0 - rough * 0.65));

    // Keep neutral grayscale if uLightMode == 1
    if (uLightMode == 1) {
        col = vec3(dot(col, vec3(0.299, 0.587, 0.114)));
    }

    return col;
}

// -----------------------------------------------------------------------------
// PBR Microfacet Helpers (GGX)
// -----------------------------------------------------------------------------
float D_GGX(float NdotH, float alpha) {
    float a2 = alpha * alpha;
    float d = NdotH * NdotH * (a2 - 1.0) + 1.0;
    return a2 / (PI * d * d + 1e-6);
}

float G_Smith(float NdotV, float NdotL, float rough) {
    float k = (rough + 1.0);
    k = (k * k) * 0.125;
    float gv = NdotV / (NdotV * (1.0 - k) + k + 1e-5);
    float gl = NdotL / (NdotL * (1.0 - k) + k + 1e-5);
    return gv * gl;
}

vec3 fresnelSchlick(float cosTheta, vec3 F0) {
    return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

float fresnelSchlickScalar(float cosTheta, float F0) {
    return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
}

// Build orthonormal tangent basis from surface normal
void buildBasis(vec3 N, out vec3 T, out vec3 B) {
    vec3 up = abs(N.y) < 0.99 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);
    T = normalize(cross(up, N));
    B = cross(N, T);
}

// -----------------------------------------------------------------------------
// Discrete 3D Voronoi Metallic Aluminum Micro-Flakes (fwidth-antialiased)
// -----------------------------------------------------------------------------
struct FlakeSample {
    vec3 normal;
    float mask;      // 1 inside discrete metallic platelet, 0 in thin resin gap
    float reflVar;   // per-flake brightness variation
    float aaFade;    // 1 when resolved, smoothly fades when sub-pixel
};

FlakeSample sampleFlakeLayer(vec3 posObj, vec3 N, vec3 T, vec3 B, float scale, float tiltSpread) {
    vec3 q = posObj * scale;
    // Screen-space filter width for alias-free micro-sparkle
    float fw = length(fwidth(q));

    vec3 iCell = floor(q);
    vec3 fCell = fract(q);

    float d1 = 8.0;
    float d2 = 8.0;
    vec3 bestHash = vec3(0.5);

    for (int z = -1; z <= 1; z++) {
        for (int y = -1; y <= 1; y++) {
            for (int x = -1; x <= 1; x++) {
                vec3 neighbor = vec3(float(x), float(y), float(z));
                vec3 h = hash33(iCell + neighbor);
                vec3 diff = neighbor + 0.14 + 0.72 * h - fCell;
                float dist = dot(diff, diff);
                if (dist < d1) {
                    d2 = d1;
                    d1 = dist;
                    bestHash = h;
                } else if (dist < d2) {
                    d2 = dist;
                }
            }
        }
    }

    // Distance to Voronoi cell edge gives crisp polygonal aluminum platelet facets
    float edgeDist = sqrt(d2) - sqrt(d1);
    float aaWidth = max(0.06, fw * 0.35);
    float facetMask = smoothstep(0.02, 0.02 + aaWidth, edgeDist);

    // Random orientation of each aluminum platelet around the macro surface normal
    vec2 tilt = (bestHash.xy * 2.0 - 1.0) * tiltSpread;
    vec3 nFlake = normalize(N + T * tilt.x + B * tilt.y);

    // Smoothly attenuate discrete glint variance when cell footprint exceeds ~1 pixel
    float aaFade = 1.0 - smoothstep(0.28, 1.55, fw);

    FlakeSample fs;
    fs.normal = mix(N, nFlake, aaFade);
    fs.mask = mix(0.75, facetMask, aaFade);
    fs.reflVar = 0.65 + 0.70 * bestHash.z;
    fs.aaFade = aaFade;
    return fs;
}

// -----------------------------------------------------------------------------
// Two-Layer Automotive Paint Shading (Clearcoat + Metallic Flake Flop Basecoat)
// -----------------------------------------------------------------------------
vec3 shadeCarPaint(vec3 p, vec3 N, vec3 V) {
    vec3 pLocal = toHeroLocal(p);
    vec3 T, B;
    buildBasis(N, T, B);

    // Subtle real-world clearcoat micro-undulation ("optical lacquer wave")
    // Very small amplitude so studio softbox edges remain razor-sharp
    vec3 opPos = pLocal * 22.0;
    float op0 = valueNoise3D(opPos);
    float opx = valueNoise3D(opPos + vec3(0.08, 0.0, 0.0)) - op0;
    float opy = valueNoise3D(opPos + vec3(0.0, 0.08, 0.0)) - op0;
    float opz = valueNoise3D(opPos + vec3(0.0, 0.0, 0.08)) - op0;
    vec3 opGrad = vec3(opx, opy, opz);
    opGrad -= N * dot(opGrad, N);
    float opFade = 1.0 - smoothstep(0.3, 1.4, length(fwidth(opPos)));
    vec3 Ncc = normalize(N + opGrad * (0.045 * opFade));

    float NdotV = max(dot(Ncc, V), 0.001);

    // Clearcoat Fresnel (IOR = 1.5 -> F0 = 0.04)
    float Fcc = fresnelSchlickScalar(NdotV, 0.04);
    float roughCC = 0.024;

    // Refracted view vector inside the clearcoat resin (IOR 1.5)
    vec3 V_refr = normalize(refract(-V, Ncc, 1.0 / 1.5));
    float NdotV_base = max(dot(N, -V_refr), 0.001);

    // -------------------------------------------------------------------------
    // Pigment & Metallic Flop Palette (uOpen: 0 = Sapphire/Emerald, 1 = Candy Crimson)
    // -------------------------------------------------------------------------
    float u = clamp(uOpen, 0.0, 1.0);

    // Deep sapphire-blue -> emerald mid-angle -> midnight-indigo flop
    vec3 sapFace  = vec3(0.035, 0.19, 0.62);
    vec3 sapMid   = vec3(0.018, 0.36, 0.44);
    vec3 sapFlop  = vec3(0.012, 0.035, 0.14);
    vec3 sapSpec  = vec3(0.32, 0.68, 0.98);
    vec3 sapAbs   = vec3(1.15, 0.45, 0.12); // optical clear-candy depth absorption

    // Metallic candy-crimson ("Soul Red Crystal") -> fiery vermilion -> deep oxblood flop
    vec3 crmFace  = vec3(0.72, 0.035, 0.085);
    vec3 crmMid   = vec3(0.84, 0.14, 0.045);
    vec3 crmFlop  = vec3(0.16, 0.012, 0.028);
    vec3 crmSpec  = vec3(1.00, 0.42, 0.34);
    vec3 crmAbs   = vec3(0.14, 1.25, 1.15);

    vec3 baseFace = mix(sapFace, crmFace, u);
    vec3 baseMid  = mix(sapMid,  crmMid,  u);
    vec3 baseFlop = mix(sapFlop, crmFlop, u);
    vec3 flakeTint = mix(sapSpec, crmSpec, u);
    vec3 candyAbs = mix(sapAbs,  crmAbs,  u);

    // 3-stop automotive metallic flop curve based on viewing angle
    float flopT = 1.0 - NdotV_base;
    vec3 pigmentColor = mix(baseFace, baseMid, smoothstep(0.08, 0.55, flopT));
    pigmentColor = mix(pigmentColor, baseFlop, smoothstep(0.42, 0.92, flopT));

    // Optical candy-coat depth darkening at grazing path lengths
    float pathLen = (1.0 / max(NdotV_base, 0.25) - 1.0) * 0.42;
    vec3 coatTransmission = exp(-candyAbs * pathLen);

    // -------------------------------------------------------------------------
    // Dual-Scale Discrete Aluminum Micro-Flakes (fwidth-antialiased, fine automotive grain)
    // -------------------------------------------------------------------------
    FlakeSample flake1 = sampleFlakeLayer(pLocal, N, T, B, 152.0, 0.24);
    FlakeSample flake2 = sampleFlakeLayer(pLocal + vec3(3.7, 1.9, 5.3), N, T, B, 296.0, 0.32);

    // -------------------------------------------------------------------------
    // Studio Direct Lights (matched to the studio softboxes & uLightMode)
    // -------------------------------------------------------------------------
    vec3 L0_dir = normalize(vec3(0.55, 1.15, 0.72));   // Overhead key softbox
    vec3 L1_dir = normalize(vec3(1.15, 0.34, 0.85));   // Side strip light
    vec3 L2_dir = normalize(vec3(-1.10, 0.52, -0.78)); // Rim strip light

    vec3 L0_col = vec3(1.58, 1.62, 1.70);
    vec3 L1_col = vec3(1.48, 1.40, 1.32);
    vec3 L2_col = vec3(1.12, 1.22, 1.42);

    if (uLightMode == 1) {
        L0_col = vec3(1.62);
        L1_col = vec3(1.40);
        L2_col = vec3(1.22);
    } else if (uLightMode == 2) {
        L0_dir = normalize(vec3(0.25, 0.65, 0.85));
        L1_dir = normalize(vec3(1.35, 0.18, 0.55));
        L0_col = vec3(0.72, 0.75, 0.82);
        L1_col = vec3(2.25, 2.08, 1.90);
        L2_col = vec3(1.65, 1.78, 2.02);
    } else if (uLightMode == 3) {
        L0_col = vec3(0.55, 0.58, 0.64);
        L1_col = vec3(0.78, 0.74, 0.70);
        L2_dir = normalize(vec3(-0.75, 0.38, -1.25));
        L2_col = vec3(2.75, 2.85, 3.05);
    }

    float ao = calcAO(p, N);

    // Accumulate Basecoat (diffuse + broad metallic lobe + discrete flake glints) & Clearcoat
    vec3 baseLayer = vec3(0.0);
    vec3 coatLayer = vec3(0.0);

    // Basecoat metallic parameters
    float roughBase = 0.30;
    vec3 F0_metal = mix(vec3(0.18), flakeTint, 0.82);

    // Evaluate 3 studio lights
    for (int i = 0; i < 3; i++) {
        vec3 L = (i == 0) ? L0_dir : ((i == 1) ? L1_dir : L2_dir);
        vec3 Lcol = (i == 0) ? L0_col : ((i == 1) ? L1_col : L2_col);

        float NdotL = max(dot(N, L), 0.0);
        float NccDotL = max(dot(Ncc, L), 0.0);
        if (NdotL <= 0.0 && NccDotL <= 0.0) continue;

        // Rule 3: Hero-only soft shadow with bias p + N * 0.014
        float sh = (i == 0) ? softShadow(p + N * 0.014, L, 6.0, 10.0) : 1.0;

        vec3 H = normalize(V + L);

        // --- Clearcoat direct GGX specular ---
        float NccDotH = max(dot(Ncc, H), 0.0);
        float D_cc = min(D_GGX(NccDotH, roughCC * roughCC), 55.0);
        float G_cc = G_Smith(NdotV, NccDotL, roughCC);
        float F_cc_l = fresnelSchlickScalar(max(dot(H, V), 0.0), 0.04);
        vec3 specCC = vec3(D_cc * G_cc * F_cc_l / (4.0 * NdotV * NccDotL + 1e-4));
        coatLayer += specCC * Lcol * NccDotL * sh * 0.22;

        // --- Basecoat metallic diffuse + broad metallic flake lobe ---
        float NdotH = max(dot(N, H), 0.0);
        float D_m = D_GGX(NdotH, roughBase * roughBase);
        float G_m = G_Smith(NdotV_base, NdotL, roughBase);
        vec3 F_m = fresnelSchlick(max(dot(H, V), 0.0), F0_metal);
        vec3 broadMetal = (D_m * G_m * F_m) / (4.0 * NdotV_base * NdotL + 1e-4);

        // --- Discrete glittering aluminum micro-flakes ---
        float roughF1 = mix(0.09, 0.26, 1.0 - flake1.aaFade);
        float N1dotH = max(dot(flake1.normal, H), 0.0);
        float glint1 = min(D_GGX(N1dotH, roughF1 * roughF1), 16.0) * flake1.mask * flake1.reflVar;

        float roughF2 = mix(0.07, 0.24, 1.0 - flake2.aaFade);
        float N2dotH = max(dot(flake2.normal, H), 0.0);
        float glint2 = min(D_GGX(N2dotH, roughF2 * roughF2), 16.0) * flake2.mask * flake2.reflVar;

        // Aluminum sparkle tinted slightly by the candy pigment (bright metallic silver-hue glints)
        vec3 aluminumGlintColor = mix(flakeTint, vec3(0.95, 0.97, 1.0), 0.42);
        vec3 flakeSparkle = aluminumGlintColor * (glint1 * 0.068 + glint2 * 0.048) * (0.35 + 0.65 * flake1.aaFade);

        // Subtle pigmented binder diffuse + broad metallic + crisp micro-flakes
        vec3 diff = pigmentColor * INV_PI * 0.50;
        baseLayer += (diff + broadMetal * 0.56 + flakeSparkle) * Lcol * NdotL * sh;
    }

    // -------------------------------------------------------------------------
    // Image-Based Studio Reflections (IBL) for Basecoat, Micro-Flakes & Clearcoat
    // -------------------------------------------------------------------------
    // 1. Basecoat diffuse ambient & broad metallic environment reflection
    vec3 envDiff = evalStudioEnv(N, 0.92);
    vec3 R_base = reflect(-V, N);
    vec3 envMetal = evalStudioEnv(R_base, 0.34);

    // 2. Discrete micro-flake environment reflections (catches studio softboxes as twinkling platelets!)
    vec3 R_f1 = reflect(-V, flake1.normal);
    vec3 R_f2 = reflect(-V, flake2.normal);
    float envRoughF1 = mix(0.06, 0.34, 1.0 - flake1.aaFade);
    float envRoughF2 = mix(0.05, 0.34, 1.0 - flake2.aaFade);

    vec3 envFlake1 = evalStudioEnv(R_f1, envRoughF1) * flake1.mask * flake1.reflVar;
    vec3 envFlake2 = evalStudioEnv(R_f2, envRoughF2) * flake2.mask * flake2.reflVar;

    vec3 flakeEnvCol = mix(flakeTint, vec3(0.94, 0.96, 1.0), 0.35)
                     * (envFlake1 * 0.28 + envFlake2 * 0.20)
                     * (0.28 + 0.72 * flake1.aaFade);

    vec3 F_envMetal = fresnelSchlick(NdotV_base, F0_metal);
    baseLayer += pigmentColor * envDiff * 0.65 * ao;
    baseLayer += envMetal * F_envMetal * 0.58 * ao;
    baseLayer += flakeEnvCol * (0.45 + 0.55 * ao);

    // Apply candy-coat optical depth tinting
    baseLayer *= coatTransmission;

    // 3. Razor-sharp dielectric clearcoat studio reflection (IOR 1.5)
    vec3 R_cc = reflect(-V, Ncc);
    vec3 envCC = evalStudioEnv(R_cc, roughCC);
    coatLayer += envCC * Fcc * mix(0.55, 1.0, ao);

    // Physically energy-conserving two-layer composition:
    // Clearcoat reflects Fcc; remaining (1 - Fcc) transmits into metallic flake basecoat
    vec3 total = baseLayer * (1.0 - Fcc) + coatLayer;

    return total;
}

// -----------------------------------------------------------------------------
// Studio Bench Shading (Grounded Contact Shadow + Subtle Satin Reflection)
// -----------------------------------------------------------------------------
vec3 shadeBench(vec3 p, vec3 N, vec3 V) {
    // Subtle micro-textured dark anodized/slate studio bench
    float grain = valueNoise3D(vec3(p.xz * 26.0, 0.5)) * 0.5
                + valueNoise3D(vec3(p.xz * 64.0, 1.7)) * 0.5;
    float radial = exp(-dot(p.xz, p.xz) * 0.085);

    vec3 benchAlbedo = mix(vec3(0.032, 0.035, 0.042), vec3(0.068, 0.072, 0.082), radial);
    benchAlbedo *= (0.94 + 0.12 * grain);

    if (uLightMode == 1) {
        benchAlbedo = vec3(dot(benchAlbedo, vec3(0.299, 0.587, 0.114)));
    }

    // Contact AO & clean hero-only soft shadows (Rule 3)
    float ao = calcAO(p, N);
    vec3 L0 = normalize(vec3(0.55, 1.15, 0.72));
    vec3 L1 = normalize(vec3(1.15, 0.34, 0.85));
    if (uLightMode == 2) {
        L0 = normalize(vec3(0.25, 0.65, 0.85));
        L1 = normalize(vec3(1.35, 0.18, 0.55));
    }

    float sh0 = softShadow(p + N * 0.014, L0, 7.0, 7.5);
    float sh1 = softShadow(p + N * 0.014, L1, 7.0, 9.0);

    vec3 L0_col = (uLightMode == 1) ? vec3(2.4) : vec3(2.35, 2.40, 2.52);
    vec3 L1_col = (uLightMode == 1) ? vec3(1.5) : vec3(1.65, 1.56, 1.48);
    if (uLightMode == 2) {
        L0_col *= 0.45;
        L1_col *= 1.55;
    } else if (uLightMode == 3) {
        L0_col *= 0.35;
        L1_col *= 0.55;
    }

    float NdotL0 = max(dot(N, L0), 0.0);
    float NdotL1 = max(dot(N, L1), 0.0);

    vec3 diff = benchAlbedo * INV_PI * (
        L0_col * NdotL0 * sh0 +
        L1_col * NdotL1 * sh1 +
        evalStudioEnv(N, 0.88) * 1.45 * ao
    );

    // Subtle satin-matte specular reflection of the studio & speed-shape bounce
    float NdotV = max(dot(N, V), 0.001);
    float F_bench = fresnelSchlickScalar(NdotV, 0.032);
    vec3 R = reflect(-V, N);
    vec3 envRefl = evalStudioEnv(R, 0.32) * F_bench * mix(0.35, 1.0, sh0) * ao;

    // Subtle colored paint bounce-light on the bench right underneath the speed-shape
    float dHero = mapHero(p);
    float bounceMask = exp(-dHero * 3.8) * (0.35 + 0.65 * sh0);
    vec3 bounceCol = mix(vec3(0.04, 0.18, 0.48), vec3(0.55, 0.06, 0.08), clamp(uOpen, 0.0, 1.0));
    vec3 bounce = bounceCol * bounceMask * 0.14;

    return diff + envRefl * 0.72 + bounce;
}

// -----------------------------------------------------------------------------
// ACES Filmic Tone Mapping (calibrated for hero lum 12-245, 0% clip/crush)
// -----------------------------------------------------------------------------
vec3 acesFilm(vec3 x) {
    const float a = 2.51;
    const float b = 0.03;
    const float c = 2.43;
    const float d = 0.59;
    const float e = 0.14;
    return clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
}

// -----------------------------------------------------------------------------
// Main Raymarcher
// -----------------------------------------------------------------------------
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution) / uResolution.y;

    // Subtle slow studio drift when uTime > 0, perfectly framed hero shot at uTime == 0
    float drift = sin(uTime * 0.25) * 0.10;

    vec3 ro;
    vec3 ta;
    float focal;

    if (uCamMode == 1) {
        // ~2.5x Macro view focused on the sculpted front fender / hood shoulder crease
        // Showcases discrete fine aluminum micro-flakes + crisp clearcoat softbox edge
        ro = vec3(1.16, 0.68, 1.28);
        ro.xz = rot2(drift * 0.45) * ro.xz;
        ta = vec3(0.28, 0.36, 0.16);
        focal = 2.55;
    } else {
        // Classic automotive 3/4 hero studio view (pulled back with clean margins on all sides)
        ro = vec3(2.96, 1.54, 3.28);
        ro.xz = rot2(drift) * ro.xz;
        ta = vec3(0.0, 0.30, 0.0);
        focal = 2.10;
    }

    vec3 cw = normalize(ta - ro);
    vec3 cu = normalize(cross(cw, vec3(0.0, 1.0, 0.0)));
    vec3 cv = cross(cu, cw);
    vec3 rd = normalize(uv.x * cu + uv.y * cv + focal * cw);

    // Primary raymarch
    float t = 0.0;
    bool hit = false;
    for (int i = 0; i < 120; i++) {
        vec3 p = ro + rd * t;
        float d = mapScene(p);
        if (d < 0.0005) {
            hit = true;
            break;
        }
        t += d;
        if (t > MAX_DIST) break;
    }

    vec3 col;
    float bgScale = (uLightMode == 3) ? 0.46 : 0.68;
    if (hit) {
        vec3 p = ro + rd * t;
        vec3 N = calcNormal(p);
        vec3 V = -rd;

        // Rule 2: Exact bench vs hero classification
        float dHero = mapHero(p);
        bool isBench = (p.y <= dHero + 0.001);

        if (isBench) {
            col = shadeBench(p, N, V);
            // Smooth studio cyclorama distance fog into background
            float fog = 1.0 - exp(-0.0045 * t * t);
            vec3 bgCol = evalStudioEnv(rd, 0.55) * bgScale;
            col = mix(col, bgCol, clamp(fog, 0.0, 1.0));
        } else {
            col = shadeCarPaint(p, N, V);
        }
    } else {
        // Out-of-focus studio cyclorama background
        col = evalStudioEnv(rd, 0.48) * bgScale;
    }

    // Pure neutral grayscale output for uLightMode == 1
    if (uLightMode == 1) {
        col = vec3(dot(col, vec3(0.2126, 0.7152, 0.0722)));
    }

    // Exposure & ACES Filmic Tone Mapping (0% clipped, hero lum cleanly in 12..245)
    col *= 0.94;
    col = acesFilm(col) * 0.90;

    // Subtle studio vignette (gentle, preserves shadows above black floor)
    vec2 vigUV = gl_FragCoord.xy / uResolution - 0.5;
    float vig = 1.0 - 0.20 * dot(vigUV, vigUV);
    col *= vig;

    // Gentle toe lift to prevent 0% black crush in deep shadow flop
    col = max(col, vec3(0.005));

    // sRGB gamma encode + 1/255 dithering to eliminate 8-bit banding
    col = pow(col, vec3(1.0 / 2.2));
    col += (hash12(gl_FragCoord.xy) - 0.5) / 255.0;

    fragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
}

Mathematical models & shader specifications

Identifiermetallic-flake-clearcoat
CategoryMetals & Armor Shaders · Industrial Metals
Upstream studymetals/lib/03_metallic_flake_clearcoat_car_paint.glsl (commit 4778681)
Animation cycleContinuous procedural uTime
Declared uniformsuResolution, uTime, uOpen, uLightMode, uCamMode
Source size765 lines · 29.0 KB standalone GLSL ES 3.00
PNG baker outputs512px · 1024px · 2048px RGBA8 (4-tap seamless + alpha key)
Companion pixel VFXFree MIT scifi sprite sheets
LicenseMIT License + CC0 / MIT Helpers

Physical & shading models implemented

Voronoi/Worley cellular fields (Voronoi 1908; Worley 1996); GGX microfacet specular (Trowbridge–Reitz 1975; Walter et al. 2007); Schlick Fresnel reflectance (1994); Beer–Lambert volumetric absorption/attenuation

Adapted upstream mathematical helpers

David Hoskins, hash · Krzysztof Narkowicz, filmic curve · Inigo Quilez, distance formulation · Inigo Quilez, quadratic distance blend · Inigo Quilez, tetrahedral SDF normal

All metals & armor shaders
Sand-Cast Iron Stipple WebGL2 procedural shaderAnimated

Heavy foundry cast iron with mold-sand stipple micro-relief, graphite dark oxide, and parting seam.

Metals & Armor
Engine-Turned Guilloche WebGL2 procedural shaderAnimated

Overlapping circular perlage abrasive swirls catching directional metallic sheen across steel plate.

Metals & Armor