#version 300 es
precision highp float;
precision highp int;

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

out vec4 fragColor;

// -----------------------------------------------------------------------------
// Math & Procedural Noise Utilities
// -----------------------------------------------------------------------------

const float PI = 3.14159265359;

float saturate(float x) {
    return clamp(x, 0.0, 1.0);
}

vec3 saturate3(vec3 x) {
    return clamp(x, 0.0, 1.0);
}

float hash13(vec3 p3) {
    p3 = fract(p3 * 0.1031);
    p3 += dot(p3, p3.zyx + 31.32);
    return fract((p3.x + p3.y) * p3.z);
}

vec3 hash33(vec3 p3) {
    p3 = fract(p3 * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yxz + 33.33);
    return fract((p3.xxy + p3.yxx) * p3.zyx);
}

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

    float n000 = hash13(i + vec3(0.0, 0.0, 0.0));
    float n100 = hash13(i + vec3(1.0, 0.0, 0.0));
    float n010 = hash13(i + vec3(0.0, 1.0, 0.0));
    float n110 = hash13(i + vec3(1.0, 1.0, 0.0));
    float n001 = hash13(i + vec3(0.0, 0.0, 1.0));
    float n101 = hash13(i + vec3(1.0, 0.0, 1.0));
    float n011 = hash13(i + vec3(0.0, 1.0, 1.0));
    float n111 = hash13(i + vec3(1.0, 1.0, 1.0));

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

    float nxy0 = mix(nx00, nx10, f.y);
    float nxy1 = mix(nx01, nx11, f.y);

    return mix(nxy0, nxy1, f.z);
}

float fbm3(vec3 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * vnoise3(p);
        p = p * 2.03 + vec3(17.1, 31.7, 11.3);
        a *= 0.5;
    }
    return v;
}

// Fast 3D cellular pebble/pit distance for green-sand stipple
vec2 sandVoronoi3(vec3 p) {
    vec3 n = floor(p);
    vec3 f = fract(p);
    float md1 = 8.0;
    float md2 = 8.0;
    for (int k = -1; k <= 1; k++) {
        for (int j = -1; j <= 1; j++) {
            for (int i = -1; i <= 1; i++) {
                vec3 g = vec3(float(i), float(j), float(k));
                vec3 o = hash33(n + g);
                vec3 r = g + o - f;
                float d = dot(r, r);
                if (d < md1) {
                    md2 = md1;
                    md1 = d;
                } else if (d < md2) {
                    md2 = d;
                }
            }
        }
    }
    return vec2(sqrt(md1), sqrt(md2));
}

// -----------------------------------------------------------------------------
// SDF Primitives & Smooth Blending
// -----------------------------------------------------------------------------

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 sdCylinderY(vec3 p, float r, float h) {
    vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h);
    return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));
}

float sdCappedCylinderChamfer(vec3 p, float r, float h, float c) {
    float dr = length(p.xz) - r;
    float dy = abs(p.y) - h;
    float dBox = min(max(dr, dy), 0.0) + length(max(vec2(dr, dy), 0.0));
    float dCham = (dr + dy + c) * 0.70710678;
    return max(dBox, dCham);
}

float sdRoundBox(vec3 p, vec3 b, float r) {
    vec3 q = abs(p) - b;
    return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;
}

// Stadium / oval mounting flange prism along X
float sdStadiumY(vec3 p, float halfLen, float radius, float halfH, float bevel) {
    vec2 q = p.xz;
    q.x -= clamp(q.x, -halfLen, halfLen);
    float d2 = length(q) - radius;
    vec2 w = vec2(d2, abs(p.y) - halfH);
    return min(max(w.x, w.y), 0.0) + length(max(w, 0.0)) - bevel;
}

// -----------------------------------------------------------------------------
// Shared Parting-Line & Grinding Mask Helpers
// -----------------------------------------------------------------------------

// Parting plane wraps around the midsection of the cast body
float partingPlaneY(vec3 p) {
    float ang = atan(p.z, p.x);
    float wave = 0.008 * sin(ang * 2.0 + 0.4) + 0.005 * sin(ang * 5.0 - 1.1);
    return 0.44 + wave;
}

// Grinding progress mask driven by uOpen (0..1): sweeps from front-center around both sides
float getGrindMask(vec3 p) {
    float openVal = saturate(uOpen);
    if (openVal <= 0.001) return 0.0;

    float yPart = partingPlaneY(p);
    float dy = abs(p.y - yPart);

    // Angle measured from front-center (+Z)
    float angFromFront = abs(atan(p.x, p.z)) / PI; // 0 at +Z, 1 at -Z
    float sweepEdge = openVal * 1.18;
    float alongSweep = smoothstep(sweepEdge + 0.05, sweepEdge - 0.08, angFromFront);

    // Subtle hand-grinder wobble along the ground band width
    float wobble = (vnoise3(p * 18.0 + vec3(2.3, 0.0, 5.1)) - 0.5) * 0.012;
    float bandHalfW = mix(0.018, 0.042, openVal) + wobble;
    float acrossBand = smoothstep(bandHalfW + 0.010, bandHalfW - 0.008, dy);

    // Keep grinding strictly on the cast body exterior around the midsection
    float rXZ = length(p.xz);
    float onBody = smoothstep(0.24, 0.34, rXZ) * smoothstep(0.86, 0.65, p.y);

    return saturate(alongSweep * acrossBand * onBody * smoothstep(0.0, 0.08, openVal));
}

// -----------------------------------------------------------------------------
// Sand-Cast Iron Macro & Micro Geometry (Hero SDF)
// -----------------------------------------------------------------------------

// Base smooth cast + machined shape (no micro-stipple, used for masks & fast far-field)
float mapHeroBase(vec3 p) {
    // 1. Heavy sand-cast stadium base flange resting cleanly on y = 0.0
    // Subtle cast draft angle (slightly wider at bottom, narrower at top of flange)
    float draftBase = (p.y - 0.12) * 0.06;
    vec3 pBase = p - vec3(0.0, 0.125, 0.0);
    float dBase = sdStadiumY(pBase, 0.66, 0.44 - draftBase, 0.095, 0.030);

    // Subtle ear thickening bosses at x = +-0.76
    vec3 pEar = vec3(abs(p.x) - 0.76, p.y - 0.135, p.z);
    float dEar = sdCylinderY(pEar, 0.28 - (p.y - 0.13) * 0.05, 0.105) - 0.025;
    dBase = smin(dBase, dEar, 0.06);

    // 2. Central sand-cast cylindrical housing / neck with draft taper and tiny mold shift
    float yPart = partingPlaneY(p);
    float copeShift = smoothstep(yPart - 0.015, yPart + 0.015, p.y);
    vec3 pBody = p - vec3(0.007 * (copeShift - 0.5), 0.46, -0.005 * (copeShift - 0.5));
    // Draft narrows away from parting line (classic two-part sand mold draft)
    float draftBody = abs(p.y - yPart) * 0.075;
    float bodyRad = 0.515 - draftBody;
    float dBody = sdCylinderY(pBody, bodyRad, 0.38) - 0.032;

    // 3. Structural tapered gusset ribs along +-X connecting base flange to upper boss
    vec3 pRib = vec3(abs(p.x) - 0.48, p.y - 0.36, p.z);
    // Taper rib height down toward outer ear
    float ribSlope = (abs(p.x) - 0.35) * 0.58;
    vec3 pRibShaped = vec3(pRib.x, pRib.y + max(ribSlope, 0.0), pRib.z);
    float ribThick = 0.068 - (p.y - 0.30) * 0.025;
    float dRib = sdRoundBox(pRibShaped, vec3(0.24, 0.25, ribThick), 0.028);

    // Secondary front/back small stiffening buttresses along +-Z
    vec3 pButt = vec3(p.x, p.y - 0.27, abs(p.z) - 0.42);
    float buttSlope = (abs(p.z) - 0.36) * 0.65;
    float dButt = sdRoundBox(vec3(pButt.x, pButt.y + max(buttSlope, 0.0), pButt.z), vec3(0.085, 0.19, 0.12), 0.026);

    // Blend cast features with generous foundry fillets
    float dCast = smin(dBase, dBody, 0.11);
    dCast = smin(dCast, dRib, 0.075);
    dCast = smin(dCast, dButt, 0.065);

    // 4. Raised freshly face-milled machined top bolt boss (crisp, sharp chamfer)
    // Sits cleanly atop the cast housing at y = 0.88
    vec3 pTopBoss = p - vec3(0.0, 0.77, 0.0);
    float dTopBoss = sdCappedCylinderChamfer(pTopBoss, 0.465, 0.11, 0.022);
    // Crisp transition from cast neck to machined boss collar
    float dHero = smin(dCast, dTopBoss, 0.025);

    // Flat face-milled top cut at y = 0.880 (razor-flat machined plane)
    float dTopCut = p.y - 0.880;
    float rTop = length(p.xz);
    float topChamfer = (rTop - 0.465 + (p.y - 0.880) + 0.018) * 0.70710678;
    dHero = max(dHero, max(dTopCut, topChamfer));

    // Flat machined bottom seating plane at y = 0.000 (grounds hero squarely on bench)
    dHero = max(dHero, -p.y);

    // 5. Machined spot-faced bolt seats on left & right base ears (flat at y = 0.245)
    vec2 earPos = vec2(abs(p.x) - 0.76, p.z);
    float rEar = length(earPos);
    float dEarSeatCut = max(p.y - 0.245, rEar - 0.215);
    // Carve flat spot-face downward into the cast ear
    float dSpotFace = max(-(p.y - 0.245), rEar - 0.215);
    // Only cut above y = 0.245 within rEar < 0.215
    float dEarCarve = max(0.245 - p.y, rEar - 0.215);
    dHero = max(dHero, -dEarCarve);
    // Suppress unused warning
    dHero += 0.0 * (dEarSeatCut + dSpotFace);

    // 6. Central precision-bored through-hole with top chamfer
    float dCenterBore = -(length(p.xz) - 0.175);
    float dCenterChamfer = -((length(p.xz) - 0.175) - (p.y - 0.880) - 0.020) * 0.70710678;
    dHero = max(dHero, max(dCenterBore, dCenterChamfer));

    // 7. Two machined ear mounting bolt holes with slight top chamfer
    float dEarHole = -(rEar - 0.105);
    float dEarHoleChamfer = -((rEar - 0.105) - (p.y - 0.245) - 0.012) * 0.70710678;
    dHero = max(dHero, max(dEarHole, dEarHoleChamfer));

    return dHero;
}

// Compute mask: 1.0 on machined faces (top face-milled boss, bore, ear spot-faces), 0.0 on sand-cast skin
float getMachinedMask(vec3 p) {
    float rXZ = length(p.xz);
    vec2 earPos = vec2(abs(p.x) - 0.76, p.z);
    float rEar = length(earPos);

    // Top face-milled boss + its outer & inner machined chamfers
    float topFace = smoothstep(0.848, 0.864, p.y) * smoothstep(0.495, 0.455, rXZ);

    // Central bored cylinder wall
    float centerBore = smoothstep(0.195, 0.178, rXZ);

    // Ear spot-faced seats & bolt holes
    float earSeat = smoothstep(0.228, 0.205, rEar) * smoothstep(0.215, 0.238, p.y) * smoothstep(0.28, 0.25, p.y);
    float earBore = smoothstep(0.118, 0.106, rEar);

    return saturate(max(max(topFace, centerBore), max(earSeat, earBore)));
}

// Full Hero SDF including 3D coarse green-sand stipple pits & raised ragged parting-line flash
float mapHero(vec3 p) {
    float d = mapHeroBase(p);

    // Far-field fast path: skip displacement when far from surface
    if (d > 0.085) return d;

    float machMask = getMachinedMask(p);
    float castMask = 1.0 - machMask;

    // Protect bottom contact plane at y = 0 from bulging below bench
    float bottomProtect = smoothstep(0.008, 0.035, p.y);
    castMask *= bottomProtect;

    if (castMask > 0.001) {
        // 1. Fine-to-medium green-sand mold waviness + 3D pebbled stipple pits
        float macroWave = (vnoise3(p * 8.5 + vec3(1.2, 4.7, 2.9)) - 0.5) * 0.0045;
        vec2 vor = sandVoronoi3(p * 68.0);
        // Granular green-sand quartz pit impressions (shallower & finer, non-bubbly)
        float pit = smoothstep(0.14, 0.56, vor.x);
        float fineGrain = vnoise3(p * 145.0) - 0.5;
        float stippleDisp = macroWave + (pit - 0.52) * 0.0048 + fineGrain * 0.0014;

        // 2. Raised ragged mold parting-line seam flash running around the midsection
        float yPart = partingPlaneY(p);
        float dy = p.y - yPart;
        float ang = atan(p.z, p.x);

        // Ragged organic modulation along the seam perimeter
        float nRagged1 = vnoise3(vec3(cos(ang) * 6.5, p.y * 12.0, sin(ang) * 6.5) + p * 8.0);
        float nRagged2 = vnoise3(p * 42.0 + vec3(9.1, 3.4, 7.2));
        float finWidth = mix(0.011, 0.023, nRagged1);
        float finProfile = exp(- (dy * dy) / (finWidth * finWidth));

        // Broken/chipped flash height along the seam
        float chipMask = smoothstep(0.12, 0.38, nRagged1 * 0.72 + nRagged2 * 0.28);
        float finHeight = (0.016 + 0.022 * nRagged1 + 0.008 * nRagged2) * chipMask;

        // Keep flash on the outer cast body & ribs, fade near machined top or very low base
        float flashRegion = smoothstep(0.28, 0.38, length(p.xz)) * smoothstep(0.74, 0.60, p.y);
        float grindMask = getGrindMask(p);

        // When uOpen grinds the parting flash, knock down the ragged peak into a flat-ish ground chamfer
        float groundFin = finHeight * mix(1.0, 0.28, grindMask);
        float flashDisp = -finProfile * groundFin * flashRegion;

        // Slight inward grinding bevel when uOpen > 0
        float grindCut = 0.0055 * grindMask * flashRegion;

        d += castMask * (stippleDisp + flashDisp + grindCut);
    }

    // Keep bottom strictly >= 0.0 so hero never clips through bench
    d = max(d, -p.y);
    return d;
}

// -----------------------------------------------------------------------------
// Unit-Weight Tetrahedral Normals (Zero-Bug Rule #1)
// -----------------------------------------------------------------------------

vec3 calcNormalHero(vec3 p) {
    const float e = 0.0012;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapHero(p + k.xyy * e) +
        k.yyx * mapHero(p + k.yyx * e) +
        k.yxy * mapHero(p + k.yxy * e) +
        k.xxx * mapHero(p + k.xxx * e)
    );
}

// -----------------------------------------------------------------------------
// Hero-Only Soft Shadow (Zero-Bug Rule #3: clean min(res, k*h/t), no ph!)
// -----------------------------------------------------------------------------

float calcSoftShadow(vec3 p, vec3 N, vec3 L, float maxDist, float k) {
    vec3 ro = p + N * 0.014;
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 64; i++) {
        float h = mapHero(ro + L * t);
        if (h < 0.0006) return 0.0;
        res = min(res, k * h / t);
        t += max(h, 0.015);
        if (t > maxDist) break;
    }
    return saturate(res);
}

// -----------------------------------------------------------------------------
// Ambient Occlusion (Hero + Bench)
// -----------------------------------------------------------------------------

float calcAO(vec3 p, vec3 N) {
    float occ = 0.0;
    float sca = 1.0;
    for (int i = 1; i <= 5; i++) {
        float h = 0.018 + 0.042 * float(i);
        vec3 q = p + N * h;
        float d = min(mapHero(q), q.y);
        occ += (h - d) * sca;
        sca *= 0.72;
    }
    return saturate(1.0 - 2.35 * occ);
}

// -----------------------------------------------------------------------------
// High-Contrast Studio Environment (Softboxes + Dark Negative-Fill Flags)
// -----------------------------------------------------------------------------

vec3 evalStudioEnv(vec3 R, int lightMode) {
    vec3 d = normalize(R);
    float y = d.y;

    // Base dark architectural studio shell
    vec3 baseSky = mix(vec3(0.032, 0.034, 0.038), vec3(0.075, 0.080, 0.088), smoothstep(-0.25, 0.85, y));

    vec3 keyTint = vec3(1.04, 0.99, 0.94);
    vec3 rimTint = vec3(0.88, 0.95, 1.06);
    vec3 fillTint = vec3(0.95, 0.97, 1.01);

    if (lightMode == 1) {
        // Pure neutral grayscale studio
        baseSky = vec3(dot(baseSky, vec3(0.2126, 0.7152, 0.0722)));
        keyTint = vec3(1.0);
        rimTint = vec3(1.0);
        fillTint = vec3(1.0);
    }

    vec3 env = baseSky;

    if (lightMode == 0 || lightMode == 1) {
        // Overhead-left large studio softbox (creates crisp specular sweep on face-milled boss)
        vec3 sb1Dir = normalize(vec3(-0.48, 0.78, 0.40));
        float sb1 = smoothstep(0.76, 0.95, dot(d, sb1Dir));
        // Rectangular softbox frame falloff
        vec3 sb1U = normalize(cross(vec3(0.0, 1.0, 0.0), sb1Dir));
        vec3 sb1V = cross(sb1Dir, sb1U);
        float u1 = abs(dot(d, sb1U));
        float v1 = abs(dot(d, sb1V));
        float rect1 = (1.0 - smoothstep(0.28, 0.42, u1)) * (1.0 - smoothstep(0.18, 0.30, v1)) * step(0.0, dot(d, sb1Dir));
        env += keyTint * (2.65 * rect1 + 0.55 * sb1);

        // Right-side vertical strip softbox (catches the parting line & cylindrical flank)
        vec3 sb2Dir = normalize(vec3(0.84, 0.34, 0.42));
        vec3 sb2U = normalize(cross(vec3(0.0, 1.0, 0.0), sb2Dir));
        vec3 sb2V = cross(sb2Dir, sb2U);
        float rect2 = (1.0 - smoothstep(0.11, 0.19, abs(dot(d, sb2U)))) *
                      (1.0 - smoothstep(0.32, 0.48, abs(dot(d, sb2V)))) *
                      step(0.0, dot(d, sb2Dir));
        env += rimTint * (2.10 * rect2);

        // Rear-top rim strip for silhouette separation
        vec3 sb3Dir = normalize(vec3(0.15, 0.62, -0.77));
        float sb3 = smoothstep(0.82, 0.96, dot(d, sb3Dir));
        env += fillTint * (1.75 * sb3);

        // Dark negative-fill flags (crucial for metallic contrast on bright machined iron!)
        vec3 neg1 = normalize(vec3(0.28, 0.44, 0.85));
        float flag1 = smoothstep(0.72, 0.90, dot(d, neg1));
        vec3 neg2 = normalize(vec3(-0.88, 0.20, -0.42));
        float flag2 = smoothstep(0.74, 0.92, dot(d, neg2));
        env *= (1.0 - 0.78 * flag1) * (1.0 - 0.72 * flag2);
    } else if (lightMode == 2) {
        // Grazing raking studio: low-angle right-front strip light + dark overhead flag
        vec3 grazeDir = normalize(vec3(0.92, 0.24, 0.31));
        float grazeBox = smoothstep(0.82, 0.96, dot(d, grazeDir));
        env += vec3(1.06, 0.98, 0.90) * (3.40 * grazeBox);

        // Subtle cool opposite kick
        vec3 kickDir = normalize(vec3(-0.82, 0.36, -0.44));
        env += vec3(0.82, 0.90, 1.04) * (1.10 * smoothstep(0.80, 0.95, dot(d, kickDir)));

        // Overhead negative fill to accentuate raking relief
        float topNeg = smoothstep(0.65, 0.92, y);
        env *= (1.0 - 0.62 * topNeg);
    } else {
        // Mode 3: Backlit rim studio — strong rear softbox + dark front negative fill + soft floor bounce
        vec3 backDir = normalize(vec3(-0.12, 0.46, -0.88));
        vec3 backU = normalize(cross(vec3(0.0, 1.0, 0.0), backDir));
        vec3 backV = cross(backDir, backU);
        float backRect = (1.0 - smoothstep(0.30, 0.48, abs(dot(d, backU)))) *
                         (1.0 - smoothstep(0.22, 0.36, abs(dot(d, backV)))) *
                         step(0.0, dot(d, backDir));
        env += vec3(0.96, 0.98, 1.04) * (3.60 * backRect);

        // Subtle front bounce card so dark sand-cast iron retains readable mid-shadow detail
        vec3 frontCard = normalize(vec3(0.18, 0.22, 0.96));
        env += vec3(0.94, 0.95, 0.98) * (0.48 * smoothstep(0.55, 0.90, dot(d, frontCard)));

        // Side negative-fill flags
        float sideNeg = smoothstep(0.70, 0.92, abs(d.x));
        env *= (1.0 - 0.65 * sideNeg);
    }

    // Subtle bench bounce from below horizon
    float floorBounce = smoothstep(0.05, -0.55, y);
    vec3 bounceCol = (lightMode == 1) ? vec3(0.052) : vec3(0.050, 0.052, 0.056);
    env = mix(env, bounceCol, floorBounce * 0.72);

    return env;
}

// -----------------------------------------------------------------------------
// GGX PBR Direct & IBL Helpers
// -----------------------------------------------------------------------------

float D_GGX(float NoH, float a) {
    float a2 = a * a;
    float d = (NoH * a2 - NoH) * NoH + 1.0;
    return a2 / (PI * d * d + 1e-6);
}

float G_SchlickGGX(float NoV, float k) {
    return NoV / (NoV * (1.0 - k) + k + 1e-6);
}

float G_Smith(float NoV, float NoL, float rough) {
    float r = rough + 1.0;
    float k = (r * r) * 0.125;
    return G_SchlickGGX(NoV, k) * G_SchlickGGX(NoL, k);
}

vec3 F_Schlick(float cosTheta, vec3 F0) {
    return F0 + (1.0 - F0) * pow(saturate(1.0 - cosTheta), 5.0);
}

vec3 evalDirectLight(vec3 N, vec3 V, vec3 L, vec3 lightCol, vec3 baseColor, float metallic, float rough, float shadow) {
    float NoL = saturate(dot(N, L));
    if (NoL <= 0.0 || shadow <= 0.0) return vec3(0.0);

    float NoV = max(dot(N, V), 0.001);
    vec3 H = normalize(V + L);
    float NoH = saturate(dot(N, H));
    float VoH = saturate(dot(V, H));

    vec3 F0 = mix(vec3(0.04), baseColor, metallic);
    float a = max(rough * rough, 0.006);

    float D = D_GGX(NoH, a);
    float G = G_Smith(NoV, NoL, rough);
    vec3 F = F_Schlick(VoH, F0);

    vec3 spec = (D * G * F) / (4.0 * NoV * NoL + 0.001);
    vec3 kD = (vec3(1.0) - F) * (1.0 - metallic);
    vec3 diff = kD * baseColor / PI;

    return (diff + spec) * lightCol * NoL * shadow;
}

// -----------------------------------------------------------------------------
// Surface Micro-Detail Perturbation & Material Evaluation
// -----------------------------------------------------------------------------

struct Material {
    vec3 baseColor;
    float metallic;
    float roughness;
    vec3 N;
};

Material evalHeroMaterial(vec3 p, vec3 Ngeom) {
    Material m;
    m.N = Ngeom;

    float machMask = getMachinedMask(p);
    float grindMask = getGrindMask(p);
    float yPart = partingPlaneY(p);
    float distPart = abs(p.y - yPart);
    float flashRidge = exp(-(distPart * distPart) / 0.00045) * (1.0 - machMask);

    // ---- A. Green-Sand Cast Gray Iron (matte-charcoal finely pebbled sand-mold skin) ----
    vec2 vorCoarse = sandVoronoi3(p * 68.0);
    vec2 vorFine = sandVoronoi3(p * 155.0);
    float sandPit = smoothstep(0.14, 0.58, vorCoarse.x);
    float finePebble = smoothstep(0.16, 0.64, vorFine.x);
    float microN = fbm3(p * 82.0);

    // Subtle granular micro-normal perturbation (fine matte quartz-sand grains, non-bubbly)
    float eps = 0.0014;
    float h0 = sandVoronoi3(p * 145.0).x * 0.45 + vnoise3(p * 235.0) * 0.55;
    float hx = sandVoronoi3((p + vec3(eps, 0.0, 0.0)) * 145.0).x * 0.45 + vnoise3((p + vec3(eps, 0.0, 0.0)) * 235.0) * 0.55;
    float hy = sandVoronoi3((p + vec3(0.0, eps, 0.0)) * 145.0).x * 0.45 + vnoise3((p + vec3(0.0, eps, 0.0)) * 235.0) * 0.55;
    float hz = sandVoronoi3((p + vec3(0.0, 0.0, eps)) * 145.0).x * 0.45 + vnoise3((p + vec3(0.0, 0.0, eps)) * 235.0) * 0.55;
    vec3 sandGrad = vec3(hx - h0, hy - h0, hz - h0) / eps;
    // Project gradient onto tangent plane with restrained amplitude
    sandGrad -= Ngeom * dot(sandGrad, Ngeom);
    vec3 Ncast = normalize(Ngeom - sandGrad * 0.00135);

    // Matte-charcoal foundry gray iron: dark silica-dusted pits, softly rubbed graphite grain crests
    vec3 pitColor = vec3(0.048, 0.051, 0.055);
    vec3 crestColor = vec3(0.128, 0.133, 0.140);
    vec3 oxideTint = vec3(0.095, 0.082, 0.072);
    vec3 castColor = mix(pitColor, crestColor, saturate(sandPit * 0.60 + finePebble * 0.40));
    // Subtle foundry oxide warmth in crevices/fillets
    float creviceWarmth = smoothstep(0.35, 0.12, p.y) * 0.25 + (1.0 - sandPit) * 0.15;
    castColor = mix(castColor, oxideTint, creviceWarmth * 0.20);

    // Raw parting-line flash tip has slight rubbed graphite sheen
    castColor = mix(castColor, vec3(0.155, 0.160, 0.168), flashRidge * 0.32);

    // Matte foundry scale: moderate metallic, high roughness (0.68..0.84) for sharp contrast vs bright milled boss
    float castMetal = mix(0.38, 0.58, sandPit * 0.60 + microN * 0.40);
    float castRough = mix(0.84, 0.68, sandPit * 0.55 + finePebble * 0.45);
    castRough = mix(castRough, 0.60, flashRidge * 0.40);

    // ---- B. Freshly Face-Milled Machined Bolt Boss (subtle fly-cutter arc marks) ----
    // Offset fly-cutter spindle centers create sweeping circular arc marks across the flat face
    vec2 c1 = vec2(0.54, 0.36);
    vec2 c2 = vec2(-0.58, 0.28);
    vec2 d1 = p.xz - c1;
    vec2 d2 = p.xz - c2;
    float r1 = length(d1);
    float r2 = length(d2);

    // Primary and secondary fly-cutter sweep grooves
    float arc1 = sin(r1 * 215.0) * 0.65 + sin(r1 * 430.0 + 1.1) * 0.25;
    float arc2 = sin(r2 * 215.0 + 0.7) * 0.38;
    float arcPattern = arc1 + arc2;

    // Fine lathe turning rings inside the central bored hole
    float boreRing = sin(p.y * 320.0) * 0.6 + sin(p.y * 640.0) * 0.25;
    float isTopFlat = smoothstep(0.85, 0.98, Ngeom.y);

    // Radial tangent direction of fly-cutter grooves for subtle normal perturbation
    vec3 arcGrad = vec3(d1.x / (r1 + 1e-4), 0.0, d1.y / (r1 + 1e-4)) * cos(r1 * 215.0) * 0.040
                 + vec3(d2.x / (r2 + 1e-4), 0.0, d2.y / (r2 + 1e-4)) * cos(r2 * 215.0 + 0.7) * 0.022;
    vec3 boreGrad = vec3(0.0, cos(p.y * 320.0) * 0.032, 0.0);

    vec3 Nmach = normalize(Ngeom + mix(boreGrad, arcGrad, isTopFlat));

    // Bright freshly milled gray iron: cool silvery-pewter with delicate arc brightness modulation
    float arcShade = 0.5 + 0.5 * clamp(arcPattern, -1.0, 1.0);
    vec3 machColor = mix(vec3(0.56, 0.58, 0.61), vec3(0.71, 0.73, 0.76), arcShade * isTopFlat + (0.5 + 0.5 * boreRing) * (1.0 - isTopFlat));
    float machMetal = 0.97;
    float machRough = mix(0.17, 0.25, 1.0 - arcShade);

    // ---- C. Freshly Ground Bright Metal Along Parting Flash (uOpen 0..1) ----
    // Angle-grinder directional scratches running tangentially along the seam
    float ang = atan(p.z, p.x);
    float scratch1 = vnoise3(vec3(ang * 14.0, p.y * 280.0, length(p.xz) * 45.0));
    float scratch2 = sin(p.y * 420.0 + vnoise3(p * 32.0) * 4.5);
    float grindStreak = saturate(scratch1 * 0.65 + (0.5 + 0.5 * scratch2) * 0.35);

    vec3 Ngrind = normalize(Ngeom + vec3(0.0, (scratch2 * 0.055), 0.0));
    vec3 grindColor = mix(vec3(0.58, 0.60, 0.63), vec3(0.76, 0.78, 0.81), grindStreak);
    // Subtle heat-affected / burred edge right at the transition from raw cast to ground metal
    float grindEdge = grindMask * (1.0 - grindMask) * 4.0;
    grindColor = mix(grindColor, vec3(0.42, 0.36, 0.31), grindEdge * 0.28);

    float grindMetal = 0.96;
    float grindRough = mix(0.19, 0.31, 1.0 - grindStreak);

    // ---- D. Composite Materials ----
    // First blend raw cast iron with uOpen freshly ground parting-line metal
    float gBlend = grindMask * (1.0 - machMask);
    vec3 col = mix(castColor, grindColor, gBlend);
    float met = mix(castMetal, grindMetal, gBlend);
    float rgh = mix(castRough, grindRough, gBlend);
    vec3 Nout = normalize(mix(Ncast, Ngrind, gBlend));

    // Then blend in the crisp freshly face-milled machined bolt boss & spot-faces
    col = mix(col, machColor, machMask);
    met = mix(met, machMetal, machMask);
    rgh = mix(rgh, machRough, machMask);
    Nout = normalize(mix(Nout, Nmach, machMask));

    // Mode 1: pure neutral grayscale
    if (uLightMode == 1) {
        float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(lum);
    }

    m.baseColor = col;
    m.metallic = met;
    m.roughness = rgh;
    m.N = Nout;
    return m;
}

// -----------------------------------------------------------------------------
// ACES Filmic Tone Mapping
// -----------------------------------------------------------------------------

vec3 acesToneMap(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 saturate3((x * (a * x + b)) / (x * (c * x + d) + e));
}

// -----------------------------------------------------------------------------
// Studio Lighting Setup by uLightMode
// -----------------------------------------------------------------------------

void getLights(int mode, out vec3 L1, out vec3 C1, out vec3 L2, out vec3 C2, out vec3 L3, out vec3 C3) {
    if (mode == 0) {
        // Hero studio: crisp overhead-left key, cool right rim, gentle rear accent
        L1 = normalize(vec3(-0.52, 0.76, 0.39));
        C1 = vec3(2.35, 2.24, 2.12);
        L2 = normalize(vec3(0.82, 0.36, 0.44));
        C2 = vec3(0.95, 1.04, 1.18);
        L3 = normalize(vec3(0.12, 0.58, -0.80));
        C3 = vec3(0.82, 0.85, 0.90);
    } else if (mode == 1) {
        // Pure neutral grayscale studio
        L1 = normalize(vec3(-0.52, 0.76, 0.39));
        C1 = vec3(2.26);
        L2 = normalize(vec3(0.82, 0.36, 0.44));
        C2 = vec3(1.04);
        L3 = normalize(vec3(0.12, 0.58, -0.80));
        C3 = vec3(0.84);
    } else if (mode == 2) {
        // Grazing raking light to pop coarse green-sand stipple & parting-line ridge
        L1 = normalize(vec3(0.92, 0.23, 0.31));
        C1 = vec3(2.85, 2.66, 2.45);
        L2 = normalize(vec3(-0.80, 0.35, -0.48));
        C2 = vec3(0.68, 0.76, 0.88);
        L3 = normalize(vec3(-0.15, 0.85, 0.50));
        C3 = vec3(0.42, 0.44, 0.48);
    } else {
        // Mode 3: Backlit rim studio
        L1 = normalize(vec3(-0.14, 0.48, -0.86));
        C1 = vec3(2.95, 3.00, 3.12);
        L2 = normalize(vec3(0.76, 0.42, -0.49));
        C2 = vec3(1.15, 1.18, 1.24);
        L3 = normalize(vec3(0.22, 0.34, 0.91));
        C3 = vec3(0.54, 0.55, 0.58);
    }
}

// -----------------------------------------------------------------------------
// Main Raymarch & Shading
// -----------------------------------------------------------------------------

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

    // Subtle time hook (keeps framing rock-steady for inspection)
    float tIdle = sin(uTime * 0.25) * 0.0;

    // Camera setup: 0 = Hero 3/4 view (full flange + both ears + contact shadow with margin),
    // 1 = ~2.5x macro close-up on milled boss + sand stipple + parting flash
    vec3 ro;
    vec3 ta;
    float lens;
    if (uCamMode == 1) {
        ro = vec3(0.72 + tIdle, 0.94, 0.98);
        ta = vec3(0.05, 0.60, 0.22);
        lens = 2.55;
    } else {
        ro = vec3(2.15 + tIdle, 1.78, 2.95);
        ta = vec3(0.0, 0.36, 0.0);
        lens = 2.20;
    }

    vec3 ww = normalize(ta - ro);
    vec3 uu = normalize(cross(ww, vec3(0.0, 1.0, 0.0)));
    vec3 vv = cross(uu, ww);
    vec3 rd = normalize(uu * uv.x + vv * uv.y + ww * lens);

    // Raymarch hero + studio bench (y = 0)
    float t = 0.0;
    const float tMax = 14.0;
    bool hit = false;

    for (int i = 0; i < 128; i++) {
        vec3 p = ro + rd * t;
        float dHero = mapHero(p);
        float dBench = p.y;
        float d = min(dHero * 0.72, dBench);
        if (d < 0.00075) {
            hit = true;
            break;
        }
        t += d;
        if (t > tMax) break;
    }

    // Studio cyclorama background
    vec3 bgCol = evalStudioEnv(rd, uLightMode) * 0.58;
    // Soft radial studio vignette on backdrop
    float bgVig = saturate(1.0 - 0.28 * dot(uv, uv));
    vec3 col = bgCol * bgVig;

    if (hit) {
        vec3 p = ro + rd * t;
        float dHero = mapHero(p);
        // Zero-Bug Rule #2: exact bench classification
        bool isBench = (p.y <= dHero + 0.001);

        vec3 V = -rd;
        vec3 L1, C1, L2, C2, L3, C3;
        getLights(uLightMode, L1, C1, L2, C2, L3, C3);

        if (isBench) {
            // Studio bench: dark architectural honed slate / steel-bench surface
            float benchGrain = fbm3(vec3(p.xz * 4.5, 1.7));
            float benchFine = vnoise3(vec3(p.xz * 38.0, 3.1));
            vec3 N = normalize(vec3(
                (vnoise3(vec3((p.x + 0.01) * 28.0, 0.0, p.z * 28.0)) - vnoise3(vec3((p.x - 0.01) * 28.0, 0.0, p.z * 28.0))) * 0.018,
                1.0,
                (vnoise3(vec3(p.x * 28.0, 0.0, (p.z + 0.01) * 28.0)) - vnoise3(vec3(p.x * 28.0, 0.0, (p.z - 0.01) * 28.0))) * 0.018
            ));

            vec3 benchCol = mix(vec3(0.052, 0.054, 0.058), vec3(0.078, 0.080, 0.085), benchGrain * 0.75 + benchFine * 0.25);
            if (uLightMode == 1) {
                benchCol = vec3(dot(benchCol, vec3(0.2126, 0.7152, 0.0722)));
            }
            float benchRough = mix(0.64, 0.80, benchGrain);
            float benchMetal = 0.04;

            float sh1 = calcSoftShadow(p, N, L1, 5.5, 10.0);
            float sh2 = calcSoftShadow(p, N, L2, 5.5, 8.0);
            float sh3 = calcSoftShadow(p, N, L3, 5.5, 8.0);
            float ao = calcAO(p, N);

            vec3 direct = evalDirectLight(N, V, L1, C1, benchCol, benchMetal, benchRough, sh1)
                        + evalDirectLight(N, V, L2, C2, benchCol, benchMetal, benchRough, sh2)
                        + evalDirectLight(N, V, L3, C3, benchCol, benchMetal, benchRough, sh3);

            vec3 R = reflect(-V, N);
            vec3 envSpec = evalStudioEnv(mix(R, N, benchRough * benchRough), uLightMode);
            vec3 envDiff = evalStudioEnv(N, uLightMode);
            vec3 F = F_Schlick(max(dot(N, V), 0.0), vec3(0.04));

            vec3 ibl = (envDiff * benchCol * (1.0 - F) * 0.58 + envSpec * F * (1.0 - benchRough * 0.65) * 0.55) * ao;
            vec3 benchFloor = benchCol * 0.08 + vec3(0.0045);
            col = direct + ibl + benchFloor;

            // Smooth studio cyclorama horizon fade on bench
            float distFade = smoothstep(2.8, 9.0, length(p.xz));
            col = mix(col, bgCol * bgVig, distFade);
        } else {
            // Hero sand-cast gray-iron mounting flange
            vec3 Ngeom = calcNormalHero(p);
            Material mat = evalHeroMaterial(p, Ngeom);
            vec3 N = mat.N;

            // Hero-only soft shadows (bias uses geometric normal for clean self-shadowing)
            float sh1 = calcSoftShadow(p, Ngeom, L1, 4.5, 14.0);
            float sh2 = calcSoftShadow(p, Ngeom, L2, 4.5, 10.0);
            float sh3 = calcSoftShadow(p, Ngeom, L3, 4.5, 10.0);
            float ao = calcAO(p, Ngeom);

            vec3 direct = evalDirectLight(N, V, L1, C1, mat.baseColor, mat.metallic, mat.roughness, sh1)
                        + evalDirectLight(N, V, L2, C2, mat.baseColor, mat.metallic, mat.roughness, sh2)
                        + evalDirectLight(N, V, L3, C3, mat.baseColor, mat.metallic, mat.roughness, sh3);

            // Multi-tap studio IBL (crisp reflections on machined & ground iron, soft wrap on cast skin)
            vec3 R = reflect(-V, N);
            float r2 = mat.roughness * mat.roughness;
            vec3 envRefl = evalStudioEnv(normalize(mix(R, N, r2 * 0.65)), uLightMode);
            vec3 envBroad = evalStudioEnv(normalize(mix(R, N, 0.55)), uLightMode);
            vec3 envSpec = mix(envRefl, envBroad, smoothstep(0.18, 0.72, mat.roughness));
            vec3 envDiff = evalStudioEnv(N, uLightMode);

            vec3 F0 = mix(vec3(0.04), mat.baseColor, mat.metallic);
            float NoV = max(dot(N, V), 0.001);
            // Roughness-attenuated Fresnel for IBL
            vec3 F = F0 + (max(vec3(1.0 - mat.roughness), F0) - F0) * pow(saturate(1.0 - NoV), 5.0);

            // Specular AO (keeps deep cast pits grounded without crushing to zero)
            float specAO = saturate(pow(NoV + ao, exp2(-16.0 * mat.roughness - 1.0)) - 1.0 + ao);
            vec3 iblDiff = (1.0 - F) * (1.0 - mat.metallic) * mat.baseColor * envDiff * (0.62 * ao);
            vec3 iblSpec = F * envSpec * mix(0.92, 0.45, mat.roughness) * specAO;

            // Gentle studio ambient floor so deepest bore/crevice stays >= lum 14 (0% crushed black)
            vec3 minFill = mat.baseColor * (0.11 * ao + 0.045) + vec3(0.0055);

            col = direct + iblDiff + iblSpec + minFill;
        }
    }

    // Calibrated studio exposure + ACES filmic tone mapping (capped <= lum 243, 0% clipped) + sRGB gamma
    col *= 0.86;
    col = acesToneMap(col) * 0.90;
    col = pow(max(col, vec3(0.0)), vec3(1.0 / 2.2));
    if (uLightMode == 1) {
        col = vec3(dot(col, vec3(0.2126, 0.7152, 0.0722)));
    }

    fragColor = vec4(col, 1.0);
}
