#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;

// ============================================================================
// Constants & Slab Geometry
// ============================================================================
const vec3 SLAB_HALF = vec3(1.08, 0.19, 0.82); // 2.16 x 0.38 x 1.64 core-cut slab
const float SLAB_TOP = SLAB_HALF.y * 2.0;      // Grounded on y = 0.0 -> top at y = 0.38
const float PI = 3.14159265359;

// ============================================================================
// Hash & Procedural Noise
// ============================================================================
float hash11(float p) {
    p = fract(p * 0.1031);
    p *= p + 33.33;
    p *= p + p;
    return fract(p);
}

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);
}

vec2 hash22(vec2 p) {
    vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.xx + p3.yz) * p3.zy);
}

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 vnoise2(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    vec2 u = f * f * (3.0 - 2.0 * f);
    float a = hash12(i);
    float b = hash12(i + vec2(1.0, 0.0));
    float c = hash12(i + vec2(0.0, 1.0));
    float d = hash12(i + vec2(1.0, 1.0));
    return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

float fbm2(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    mat2 rot = mat2(0.80, 0.60, -0.60, 0.80);
    for (int i = 0; i < 4; i++) {
        v += a * vnoise2(p);
        p = rot * p * 2.03 + vec2(13.7, 7.3);
        a *= 0.5;
    }
    return v;
}

// ============================================================================
// Voronoi Crushed-Stone Aggregate (2D Top Surface + 3D Saw-Cut Cross Section)
// ============================================================================
// Returns vec4(edgeDist = F2 - F1, F1, cellId, facetTilt)
vec4 voronoiStone2D(vec2 x) {
    vec2 n = floor(x);
    vec2 f = fract(x);

    vec2 mg, mr;
    float md = 8.0;
    float id = 0.0;

    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 g = vec2(float(i), float(j));
            vec2 o = hash22(n + g);
            // Slightly tighter packing jitter for angular crushed gravel
            o = 0.14 + 0.72 * o;
            vec2 r = g + o - f;
            float d = dot(r, r);
            if (d < md) {
                md = d;
                mr = r;
                mg = g;
                id = hash12(n + g + vec2(17.1, 31.7));
            }
        }
    }

    // Distance to Voronoi cell border (true metric)
    float edgeD = 8.0;
    for (int j = -1; j <= 1; j++) {
        for (int i = -1; i <= 1; i++) {
            vec2 g = mg + vec2(float(i), float(j));
            vec2 o = hash22(n + g);
            o = 0.14 + 0.72 * o;
            vec2 r = g + o - f;
            if (dot(mr - r, mr - r) > 0.00001) {
                edgeD = min(edgeD, dot(0.5 * (mr + r), normalize(r - mr)));
            }
        }
    }

    // Subtle random facet tilt per stone
    vec2 tiltDir = normalize(hash22(n + mg + vec2(5.2, 9.8)) - 0.5 + 0.001);
    float tilt = dot(mr, tiltDir);

    return vec4(edgeD, sqrt(md), id, tilt);
}

// 3D Voronoi for saw-cut vertical faces showing sliced aggregate cross-sections
vec3 voronoiStone3D(vec3 x) {
    vec3 n = floor(x);
    vec3 f = fract(x);

    float md1 = 8.0;
    float md2 = 8.0;
    float id = 0.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 = 0.15 + 0.70 * hash33(n + g);
                vec3 r = g + o - f;
                float d = dot(r, r);
                if (d < md1) {
                    md2 = md1;
                    md1 = d;
                    id = hash12(n.xy + g.xy + (n.z + g.z) * 19.37);
                } else if (d < md2) {
                    md2 = d;
                }
            }
        }
    }
    return vec3(sqrt(md2) - sqrt(md1), sqrt(md1), id);
}

// ============================================================================
// Diagonal Jagged Stress Crack & Poured-Tar Ribbon Field
// ============================================================================
// Returns:
//   x = unsigned perpendicular distance to jagged diagonal crack centerline
//   y = along-crack coordinate s
//   z = signed offset from centerline
//   w = secondary hairline spur distance
vec4 crackField(vec2 xz) {
    // Diagonal basis from back-left (-1.08, -0.78) to front-right (+1.08, +0.78)
    vec2 dir = normalize(vec2(1.05, 0.72));
    vec2 nrm = vec2(-dir.y, dir.x);

    float s = dot(xz, dir);
    float u = dot(xz, nrm);

    // Multi-frequency jagged stress-fracture centerline
    float jag = 0.0;
    jag += 0.115 * sin(s * 2.15 + 0.45);
    jag += 0.052 * (vnoise2(vec2(s * 3.8, 4.1)) - 0.5) * 2.0;
    jag += 0.024 * (vnoise2(vec2(s * 11.5, 19.3)) - 0.5) * 2.0;
    jag += 0.009 * (vnoise2(vec2(s * 29.0, 53.7)) - 0.5) * 2.0;

    float signedU = u - jag;
    float dMain = abs(signedU);

    // Subtle short hairline stress spur branching off near s = -0.18
    vec2 spurOrigin = dir * (-0.18) + nrm * (0.115 * sin(-0.18 * 2.15 + 0.45));
    vec2 spurDir = normalize(vec2(0.28, -0.96));
    vec2 spurNrm = vec2(-spurDir.y, spurDir.x);
    vec2 rel = xz - spurOrigin;
    float spS = dot(rel, spurDir);
    float spJag = 0.018 * (vnoise2(vec2(spS * 9.0, 81.2)) - 0.5) * 2.0;
    float spU = abs(dot(rel, spurNrm) - spJag);
    float spSeg = max(max(-spS, spS - 0.42), 0.0);
    float dSpur = length(vec2(spU, spSeg));

    return vec4(dMain, s, signedU, dSpur);
}

// Evaluates aggregate height & stone metadata at top-surface xz
// Returns vec4(height, stoneMask, wearPolish, stoneId)
vec4 evalAggregate(vec2 xz) {
    // Coarse crushed stone (~9-13mm crushed asphalt aggregate, not cobblestones)
    vec4 vCoarse = voronoiStone2D(xz * 11.4 + vec2(3.1, 1.7));
    float cPresent = step(0.20, vCoarse.z); // ~80% occupancy so dark bitumen binder shows cleanly
    float cShape = smoothstep(0.055, 0.25, vCoarse.x);
    // Tire-worn flattened angular top with subtle facet tilt
    float cFlat = min(cShape * 1.15, 0.76 + 0.14 * hash11(vCoarse.z * 73.1));
    float cHeight = cPresent * max(0.0, cFlat + vCoarse.w * 0.14) * 0.019;

    // Medium crushed stone (~4-7mm) filling interstitial gaps
    vec4 vMed = voronoiStone2D(xz * 24.5 + vec2(14.3, 9.2));
    float mPresent = step(0.18, vMed.z);
    float mShape = smoothstep(0.055, 0.24, vMed.x);
    float mFlat = min(mShape * 1.12, 0.78);
    float mHeight = mPresent * max(0.0, mFlat + vMed.w * 0.10) * 0.012;

    // Fine mineral grit in bitumen
    float grit = (fbm2(xz * 64.0) - 0.45) * 0.005;

    // Combine coarse and medium stones cleanly
    float useCoarse = smoothstep(0.0035, 0.0085, cHeight - mHeight * 0.82);
    float stoneH = max(cHeight, mHeight * (1.0 - 0.55 * smoothstep(0.005, 0.014, cHeight)));
    float stoneMask = smoothstep(0.0045, 0.0105, stoneH);
    float stoneId = mix(vMed.z, vCoarse.z, useCoarse);

    // Tire-polished wear occurs on the highest flattened stone crests
    float wearPolish = smoothstep(0.0125, 0.0185, stoneH) * stoneMask;

    float totalH = stoneH + grit * (1.0 - 0.5 * stoneMask);
    return vec4(totalH, stoneMask, wearPolish, stoneId);
}

// Evaluates poured-tar ribbon height and mask
// Returns vec4(tarHeightDelta, tarMask, crackTrenchDepth, wetHalo)
vec4 evalTarAndCrack(vec2 xz, float openAmt, float aggHeight) {
    vec4 cf = crackField(xz);
    float dMain = cf.x;
    float s = cf.y;
    float dSpur = cf.w;

    // Organic wobble along the poured-tar edges (hot liquid tar pooling unevenly)
    float flowNoise = fbm2(vec2(s * 5.2, cf.z * 7.5 + 2.3));
    float edgeLobe = (flowNoise - 0.5) * 0.032 * (0.65 + 0.7 * openAmt);
    float fineRipple = (vnoise2(vec2(s * 24.0, cf.z * 18.0)) - 0.5) * 0.004;

    // uOpen widens the underlying stress crack AND thickens/widens the poured-tar ribbon
    float crackHalfW = mix(0.018, 0.088, openAmt);
    float tarHalfW = mix(0.052, 0.162, openAmt) + edgeLobe;
    float tarPeakH = mix(0.018, 0.044, openAmt);

    // Underlying jagged stress fissure
    float crackTrench = (1.0 - smoothstep(crackHalfW * 0.35, crackHalfW * 1.15, dMain))
                      * mix(0.026, 0.068, openAmt);
    // Hairline secondary spur fissure (not fully tar-covered unless uOpen is high)
    float spurTrench = (1.0 - smoothstep(0.005, 0.017, dSpur)) * 0.018;

    // Raised glossy poured-tar snake meniscus
    float rNorm = clamp(dMain / max(tarHalfW, 0.02), 0.0, 1.0);
    // Steep viscous bead profile at edges, smoothly domed crown
    float meniscus = pow(max(0.0, 1.0 - rNorm * rNorm), 0.58);
    // Subtle settled center trough when crack is wide open (tar sank slightly into fissure)
    float centerSettle = openAmt * 0.24 * exp(-pow(rNorm / 0.34, 2.0));
    float tarDome = tarPeakH * max(0.0, meniscus - centerSettle) + fineRipple * meniscus;

    // Slight flow-bead extension into the start of the spur when uOpen > 0.2
    float spurTar = (1.0 - smoothstep(0.008, mix(0.020, 0.042, openAmt), dSpur))
                  * mix(0.008, 0.020, openAmt) * smoothstep(0.35, 0.02, dSpur);

    float tarH = max(tarDome, spurTar);

    // Tar coats and rises above the local aggregate
    float tarMask = smoothstep(0.0025, 0.0095, tarH - aggHeight * 0.25);
    float wetHalo = smoothstep(tarHalfW * 1.18, tarHalfW * 0.85, dMain);

    return vec4(tarH, tarMask, crackTrench + spurTrench, wetHalo);
}

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

float mapHero(vec3 p) {
    // Center of slab sits at y = SLAB_HALF.y so bottom rests cleanly at y = 0.0
    vec3 q = p - vec3(0.0, SLAB_HALF.y, 0.0);

    // Fast bounding-box early-out
    float dBound = sdRoundBox(q, SLAB_HALF + vec3(0.03, 0.08, 0.03), 0.02);
    if (dBound > 0.14) {
        return dBound;
    }

    float openAmt = clamp(uOpen, 0.0, 1.0);

    // Subtle macro road-surface crown & tire-track wear undulation
    float macroWear = 0.006 * sin(q.x * 1.9 + 0.5) * cos(q.z * 2.1)
                    - 0.005 * exp(-pow((q.z - 0.15) * 2.6, 2.0));

    // Slight edge chipping along the diamond-saw top perimeter
    float edgeDist = max(abs(q.x) - SLAB_HALF.x, abs(q.z) - SLAB_HALF.z);
    float topMask = smoothstep(0.04, 0.16, q.y) * smoothstep(0.02, -0.04, edgeDist);
    float edgeChip = smoothstep(-0.08, 0.01, edgeDist) * smoothstep(0.08, 0.18, q.y)
                   * (fbm2(q.xz * 18.0 + vec2(4.2, 8.7)) - 0.55) * 0.014;

    // Evaluate 3D protruding aggregate & poured-tar ribbon on top surface
    vec4 agg = evalAggregate(q.xz);
    vec4 tar = evalTarAndCrack(q.xz, openAmt, agg.x);

    // Net surface height offset on top face
    // Outside tar: aggregate protrudes cleanly; inside crack: fissured down, then filled/raised by poured tar
    float aggContrib = agg.x * (1.0 - 0.72 * tar.y);
    float topDisp = (macroWear + aggContrib - tar.z * (1.0 - tar.y * 0.85) + tar.x - edgeChip) * topMask;

    // Subtle porous pitted relief on saw-cut vertical sides (mostly flat, tiny binder voids)
    float sideMask = (1.0 - topMask) * smoothstep(-SLAB_HALF.y + 0.01, -SLAB_HALF.y + 0.04, q.y);
    float sideVoid = sideMask * (fbm2(vec2(q.x + q.z, q.y) * 26.0) - 0.65) * 0.0045;
    // Where diagonal crack meets the vertical saw-cut edge, slight notch at upper edge
    vec4 cf = crackField(q.xz);
    float sideCrackNotch = sideMask * smoothstep(0.0, SLAB_HALF.y, q.y)
                         * (1.0 - smoothstep(0.008, mix(0.024, 0.065, openAmt), cf.x))
                         * mix(0.010, 0.028, openAmt);

    // Base saw-cut slab with crisp 0.014 bevel
    float dSlab = sdRoundBox(q, SLAB_HALF, 0.014);

    // Apply displacements with conservative scaling for clean SDF gradients
    float d = dSlab - topDisp - sideVoid + sideCrackNotch;
    return d;
}

float map(vec3 p) {
    return min(mapHero(p), p.y);
}

// ============================================================================
// Normals, Soft Shadows, and Ambient Occlusion (Zero-Bug Contract)
// ============================================================================
vec3 calcNormal(vec3 p) {
    const float e = 0.0012;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * map(p + k.xyy * e) +
        k.yyx * map(p + k.yyx * e) +
        k.yxy * map(p + k.yxy * e) +
        k.xxx * map(p + k.xxx * e)
    );
}

// Clean hero-only soft shadow (no ph, bias p + N * 0.014, tMin = 0.025, step max(h, 0.015))
float calcSoftShadow(vec3 p, vec3 N, vec3 rd, float kSoft) {
    vec3 ro = p + N * 0.014;
    float res = 1.0;
    float t = 0.025;
    for (int i = 0; i < 48; i++) {
        float h = mapHero(ro + rd * t);
        if (h < 0.001) return 0.0;
        res = min(res, kSoft * h / t);
        t += max(h, 0.015);
        if (t > 4.5) 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 = 1; i <= 5; i++) {
        float h = 0.012 + 0.036 * float(i) * float(i) / 5.0;
        float d = map(p + N * h);
        occ += (h - d) * sca;
        sca *= 0.72;
    }
    return clamp(1.0 - 2.3 * occ, 0.14, 1.0);
}

// ============================================================================
// Studio Sky / Environment with Softboxes & Negative-Fill Flags
// ============================================================================
vec3 studioEnv(vec3 rd, int lightMode) {
    // Dark-studio cyclorama dome so glossy black tar reflects deep darks between crisp softbox streaks
    float up = clamp(rd.y, 0.0, 1.0);
    vec3 baseSky = mix(vec3(0.11, 0.115, 0.125), vec3(0.16, 0.17, 0.185), pow(up, 0.65));
    // Subtle bench bounce below horizon
    if (rd.y < 0.0) {
        baseSky = mix(vec3(0.10, 0.105, 0.11), vec3(0.06, 0.062, 0.068), clamp(-rd.y * 2.5, 0.0, 1.0));
    }

    vec3 col = baseSky;

    if (lightMode == 0) {
        // HERO STUDIO: tight overhead strip softbox (crisp glossy tar specular streak),
        // warm-neutral key softbox, cool fill softbox, and dark negative-fill flags
        // 1. Tight overhead strip softbox positioned to glint along the curved tar meniscus
        float stripDot = dot(rd, normalize(vec3(-0.22, 0.90, -0.38)));
        float stripBox = smoothstep(0.90, 0.975, stripDot);
        col += vec3(2.20, 2.16, 2.10) * stripBox;

        // 2. Key softbox (front-left elevated)
        float keyDot = dot(rd, normalize(vec3(-0.62, 0.60, 0.50)));
        float keyBox = smoothstep(0.86, 0.955, keyDot);
        col += vec3(1.65, 1.58, 1.48) * keyBox;

        // 3. Cool fill softbox (right side)
        float fillDot = dot(rd, normalize(vec3(0.80, 0.38, 0.46)));
        float fillBox = smoothstep(0.84, 0.95, fillDot);
        col += vec3(0.58, 0.66, 0.78) * fillBox;

        // 4. Subtle rear rim strip
        float rimDot = dot(rd, normalize(vec3(0.20, 0.44, -0.87)));
        float rimBox = smoothstep(0.88, 0.965, rimDot);
        col += vec3(1.15, 1.18, 1.24) * rimBox;

        // 5. Negative-fill flags (dark matte studio gobos for deep pitch-black tar reflection contrast)
        float negFlagL = smoothstep(0.62, 0.84, dot(rd, normalize(vec3(-0.85, 0.28, -0.45))));
        float negFlagR = smoothstep(0.64, 0.85, dot(rd, normalize(vec3(0.82, 0.30, -0.49))));
        float negOver  = smoothstep(0.74, 0.92, dot(rd, normalize(vec3(0.28, 0.92, 0.27))));
        col *= 1.0 - 0.78 * max(max(negFlagL, negFlagR), negOver * 0.85);
    } else if (lightMode == 1) {
        // PURE NEUTRAL GRAYSCALE STUDIO
        col = vec3(mix(0.14, 0.22, pow(up, 0.7)));
        float keyBox = smoothstep(0.84, 0.95, dot(rd, normalize(vec3(-0.55, 0.68, 0.48))));
        float fillBox = smoothstep(0.80, 0.94, dot(rd, normalize(vec3(0.72, 0.48, 0.50))));
        float topBox = smoothstep(0.88, 0.965, dot(rd, normalize(vec3(0.0, 0.96, -0.25))));
        col += vec3(1.30) * keyBox + vec3(0.52) * fillBox + vec3(0.90) * topBox;
        float negFlag = smoothstep(0.68, 0.86, dot(rd, normalize(vec3(-0.88, 0.20, -0.45))));
        col *= 1.0 - 0.65 * negFlag;
    } else if (lightMode == 2) {
        // GRAZING RAKING LIGHT: low side softbox + strong negative fill overhead
        col *= 0.62;
        float rakingBox = smoothstep(0.86, 0.96, dot(rd, normalize(vec3(-0.92, 0.25, 0.30))));
        col += vec3(2.35, 2.24, 2.08) * rakingBox;
        float fillBounce = smoothstep(0.76, 0.94, dot(rd, normalize(vec3(0.80, 0.38, 0.46))));
        col += vec3(0.38, 0.43, 0.50) * fillBounce;
        float negTop = smoothstep(0.65, 0.88, dot(rd, normalize(vec3(0.0, 0.98, 0.15))));
        col *= 1.0 - 0.60 * negTop;
    } else {
        // BACKLIT: strong rear rim softbox + soft front bounce + dark side flags
        col *= 0.65;
        float backBox = smoothstep(0.80, 0.94, dot(rd, normalize(vec3(0.12, 0.44, -0.89))));
        col += vec3(2.45, 2.40, 2.32) * backBox;
        float frontBounce = smoothstep(0.72, 0.92, dot(rd, normalize(vec3(-0.20, 0.55, 0.81))));
        col += vec3(0.45, 0.48, 0.54) * frontBounce;
        float negSide = smoothstep(0.70, 0.88, abs(rd.x)) * (1.0 - smoothstep(0.35, 0.70, up));
        col *= 1.0 - 0.68 * negSide;
    }

    return col;
}

// ============================================================================
// GGX PBR BRDF + Clearcoat for Glossy Poured-Tar Ribbon
// ============================================================================
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 V_SmithGGX(float NoV, float NoL, float a) {
    float a2 = a * a;
    float ggxV = NoL * sqrt(NoV * NoV * (1.0 - a2) + a2);
    float ggxL = NoV * sqrt(NoL * NoL * (1.0 - a2) + a2);
    return 0.5 / (ggxV + ggxL + 1e-5);
}

vec3 F_Schlick(float u, vec3 f0) {
    return f0 + (1.0 - f0) * pow(clamp(1.0 - u, 0.0, 1.0), 5.0);
}

vec3 evalDirectPBR(vec3 N, vec3 V, vec3 L, vec3 lightCol, vec3 albedo, float rough, vec3 f0, float coatWeight, float coatRough) {
    float NoL = max(dot(N, L), 0.0);
    if (NoL <= 0.0) return vec3(0.0);

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

    float a = max(rough * rough, 0.003);
    float D = D_GGX(NoH, a);
    float Vis = V_SmithGGX(NoV, NoL, a);
    vec3 F = F_Schlick(VoH, f0);

    vec3 spec = D * Vis * F;
    vec3 diff = (1.0 - F) * albedo / PI;

    vec3 outCol = (diff + spec) * lightCol * NoL;

    // Optional clearcoat layer for the poured-tar ribbon
    if (coatWeight > 0.001) {
        float ca = max(coatRough * coatRough, 0.002);
        float cD = D_GGX(NoH, ca);
        float cVis = V_SmithGGX(NoV, NoL, ca);
        float cF = 0.048 + (1.0 - 0.048) * pow(clamp(1.0 - VoH, 0.0, 1.0), 5.0);
        outCol = outCol * (1.0 - coatWeight * cF) + vec3(cD * cVis * cF * coatWeight) * lightCol * NoL;
    }

    return outCol;
}

// ============================================================================
// Material Evaluation (Aggregate Lithologies, Bitumen Binder, Glossy Tar)
// ============================================================================
struct Mat {
    vec3 albedo;
    float roughness;
    vec3 f0;
    float coatWeight;
    float coatRough;
    vec3 bumpN;
};

vec3 stoneLithologyAlbedo(float id, vec2 uv) {
    float speckle = fbm2(uv * 115.0 + id * 37.0);
    float micro = vnoise2(uv * 240.0 + id * 19.0);

    if (id < 0.48) {
        // Dark basalt / gabbro (dominant asphalt aggregate)
        vec3 base = mix(vec3(0.055, 0.058, 0.064), vec3(0.095, 0.100, 0.108), speckle);
        return base * (0.90 + 0.20 * micro);
    } else if (id < 0.78) {
        // Dark speckled gray granite
        vec3 base = mix(vec3(0.105, 0.108, 0.114), vec3(0.168, 0.172, 0.178), speckle);
        float mica = smoothstep(0.78, 0.94, micro);
        return mix(base, vec3(0.24, 0.24, 0.25), mica * 0.40);
    } else if (id < 0.90) {
        // Muted weathered quartzite / warm gray limestone
        vec3 base = mix(vec3(0.135, 0.122, 0.108), vec3(0.195, 0.178, 0.156), speckle);
        return base * (0.92 + 0.16 * micro);
    } else {
        // Sparse pale quartz / feldspar chips (~10%, catching tire-polished glints)
        vec3 base = mix(vec3(0.23, 0.228, 0.222), vec3(0.31, 0.305, 0.296), speckle);
        return base * (0.93 + 0.14 * micro);
    }
}

Mat evalHeroMaterial(vec3 p, vec3 N) {
    Mat m;
    m.f0 = vec3(0.04);
    m.coatWeight = 0.0;
    m.coatRough = 0.08;
    m.bumpN = N;

    vec3 q = p - vec3(0.0, SLAB_HALF.y, 0.0);
    float openAmt = clamp(uOpen, 0.0, 1.0);
    float topFace = smoothstep(0.45, 0.82, N.y);

    // ------------------------------------------------------------------------
    // 1. Top Surface: Dark Charcoal Bitumen + Crushed-Stone Aggregate + Poured-Tar
    // ------------------------------------------------------------------------
    vec4 agg = evalAggregate(q.xz);
    vec4 tar = evalTarAndCrack(q.xz, openAmt, agg.x);

    float stoneMask = agg.y;
    float wearPolish = agg.z;
    float stoneId = agg.w;

    // Dark matte charcoal bitumen binder (~0.02-0.04) with subtle dusty crevices
    float dust = fbm2(q.xz * 14.0 + vec2(9.4, 2.1));
    float grit = fbm2(q.xz * 78.0);
    vec3 bitumenCol = mix(vec3(0.020, 0.021, 0.024), vec3(0.040, 0.041, 0.044), dust * 0.55 + grit * 0.25);
    float bitumenRough = mix(0.86, 0.96, grit);

    // Aggregate stone albedo & tire-polished top roughness
    vec3 stoneCol = stoneLithologyAlbedo(stoneId, q.xz);
    // Bitumen staining around lower stone skirts
    float skirt = smoothstep(0.005, 0.014, agg.x);
    stoneCol = mix(bitumenCol * 1.15, stoneCol, skirt);
    float stoneRough = mix(0.78, 0.26, wearPolish);
    // Pale quartz chips polish smoother under tire traffic
    if (stoneId >= 0.90) {
        stoneRough = mix(stoneRough, 0.18, wearPolish);
    }

    vec3 topAlbedo = mix(bitumenCol, stoneCol, stoneMask);
    float topRough = mix(bitumenRough, stoneRough, stoneMask);
    vec3 topF0 = mix(vec3(0.028), vec3(0.042), stoneMask * (0.5 + 0.5 * wearPolish));

    // Poured-tar ribbon (deep pitch-black glossy liquid-cooled sealant)
    float tarMask = tar.y;
    float wetHalo = tar.w * (1.0 - tarMask);
    // Wet halo darkens and slightly glosses adjacent stones where hot tar bled
    topAlbedo *= (1.0 - 0.55 * wetHalo);
    topRough = mix(topRough, 0.30, wetHalo * 0.65);

    // Tar ribbon itself: deep pitch-black (~0.015) with crisp glossy clearcoat
    vec4 cf = crackField(q.xz);
    float tarFlow = fbm2(vec2(cf.y * 16.0, cf.z * 48.0));
    vec3 tarAlbedo = mix(vec3(0.011, 0.012, 0.014), vec3(0.017, 0.018, 0.020), tarFlow);
    float tarEdgeDust = smoothstep(0.95, 0.25, tarMask) * 0.10;
    float tarRough = mix(0.055, 0.115, tarFlow) + tarEdgeDust;

    topAlbedo = mix(topAlbedo, tarAlbedo, tarMask);
    topRough = mix(topRough, tarRough, tarMask);
    topF0 = mix(topF0, vec3(0.046), tarMask);
    float topCoatW = tarMask * 0.95;
    float topCoatR = mix(0.035, 0.075, tarFlow);

    // ------------------------------------------------------------------------
    // 2. Saw-Cut Vertical Sides: Sliced 3D Aggregate Cross-Section
    // ------------------------------------------------------------------------
    vec3 v3 = voronoiStone3D(q * 11.2 + vec3(2.7, 1.3, 5.1));
    float sideStoneMask = smoothstep(0.04, 0.11, v3.x) * step(0.18, v3.z);
    // Sub-base binder slightly coarser and lighter near bottom 25% of core
    float subBase = smoothstep(-0.04, -SLAB_HALF.y + 0.02, q.y);
    vec2 sideUV = vec2(q.x + q.z, q.y);
    vec3 sideStoneCol = stoneLithologyAlbedo(v3.z, sideUV * 1.15);
    vec3 sideBinderCol = mix(vec3(0.028, 0.030, 0.033), vec3(0.058, 0.056, 0.054), subBase * 0.65 + fbm2(sideUV * 28.0) * 0.35);
    // Diamond-saw kerf dust gives sliced sides a subtle matte read
    vec3 sideAlbedo = mix(sideBinderCol, sideStoneCol * 0.90, sideStoneMask);
    float sawMarks = sin(q.y * 190.0 + (q.x + q.z) * 14.0) * 0.5 + 0.5;
    sideAlbedo *= (0.94 + 0.08 * sawMarks);
    float sideRough = mix(0.88, 0.54, sideStoneMask);

    // Tar drip/fill visible where the crack intersects the top of the saw-cut side
    float sideTar = (1.0 - topFace) * smoothstep(-0.02, SLAB_HALF.y, q.y)
                  * (1.0 - smoothstep(0.015, mix(0.042, 0.115, openAmt), cf.x));
    sideAlbedo = mix(sideAlbedo, tarAlbedo, sideTar);
    sideRough = mix(sideRough, 0.10, sideTar);

    // Blend top and side materials
    m.albedo = mix(sideAlbedo, topAlbedo, topFace);
    m.roughness = mix(sideRough, topRough, topFace);
    m.f0 = mix(vec3(0.032), topF0, topFace);
    m.coatWeight = mix(sideTar * 0.75, topCoatW, topFace);
    m.coatRough = mix(0.07, topCoatR, topFace);

    // ------------------------------------------------------------------------
    // 3. Micro-Bump Normal Perturbation (Fine Grit vs Smooth Tar Flow)
    // ------------------------------------------------------------------------
    vec3 bOff = vec3(0.0);
    if (topFace > 0.1) {
        float eps = 0.0025;
        float n0 = fbm2(q.xz * 72.0);
        float nx = fbm2((q.xz + vec2(eps, 0.0)) * 72.0);
        float nz = fbm2((q.xz + vec2(0.0, eps)) * 72.0);
        // Stronger micro-grit on matte bitumen/stone, very smooth liquid flow on tar
        float gritAmp = mix(0.16, 0.07, stoneMask) * (1.0 - 0.88 * tarMask);
        bOff += vec3(n0 - nx, 0.0, n0 - nz) * (gritAmp / eps) * 0.018 * topFace;

        // Subtle longitudinal viscous cooling ripples along the poured-tar ribbon
        if (tarMask > 0.05) {
            float t0 = vnoise2(vec2(cf.y * 22.0, cf.z * 62.0));
            float tx = vnoise2(vec2((cf.y + 0.004) * 22.0, cf.z * 62.0));
            float tz = vnoise2(vec2(cf.y * 22.0, (cf.z + 0.004) * 62.0));
            vec2 dir = normalize(vec2(1.05, 0.72));
            vec2 nrm = vec2(-dir.y, dir.x);
            vec2 flowGrad = dir * (t0 - tx) * 0.35 + nrm * (t0 - tz) * 0.85;
            bOff += vec3(flowGrad.x, 0.0, flowGrad.y) * 0.055 * tarMask * topFace;
        }
    } else {
        // Subtle saw-kerf micro-grooves on vertical faces
        bOff += vec3(0.0, (sawMarks - 0.5) * 0.04, 0.0) * (1.0 - topFace);
    }

    m.bumpN = normalize(N + bOff);

    // Pure neutral albedo override for uLightMode == 1
    if (uLightMode == 1) {
        m.albedo = vec3(0.28);
        m.f0 = vec3(0.04);
    }

    return m;
}

// ============================================================================
// Lighting Rig (Key, Fill, Rim + IBL Environment)
// ============================================================================
vec3 shadeSurface(vec3 p, vec3 N, vec3 V, Mat m, bool isBench) {
    float ao = calcAO(p, N);

    // Configure directional lights matching the studio softbox environment
    vec3 keyDir, keyCol;
    vec3 fillDir, fillCol;
    vec3 rimDir, rimCol;
    float shadowK = 14.0;

    if (uLightMode == 0) {
        // HERO STUDIO
        keyDir = normalize(vec3(-0.60, 0.65, 0.47));
        keyCol = vec3(2.15, 2.09, 2.00);
        fillDir = normalize(vec3(0.76, 0.45, 0.47));
        fillCol = vec3(0.62, 0.68, 0.78);
        rimDir = normalize(vec3(0.18, 0.48, -0.86));
        rimCol = vec3(1.15, 1.18, 1.24);
        shadowK = 13.0;
    } else if (uLightMode == 1) {
        // PURE NEUTRAL GRAYSCALE
        keyDir = normalize(vec3(-0.55, 0.68, 0.48));
        keyCol = vec3(1.85);
        fillDir = normalize(vec3(0.72, 0.48, 0.50));
        fillCol = vec3(0.60);
        rimDir = normalize(vec3(0.15, 0.52, -0.84));
        rimCol = vec3(0.85);
        shadowK = 13.0;
    } else if (uLightMode == 2) {
        // GRAZING RAKING
        keyDir = normalize(vec3(-0.92, 0.25, 0.30));
        keyCol = vec3(3.15, 3.00, 2.82);
        fillDir = normalize(vec3(0.80, 0.40, 0.44));
        fillCol = vec3(0.45, 0.50, 0.58);
        rimDir = normalize(vec3(0.25, 0.42, -0.87));
        rimCol = vec3(0.68, 0.72, 0.78);
        shadowK = 18.0;
    } else {
        // BACKLIT
        keyDir = normalize(vec3(0.12, 0.44, -0.89));
        keyCol = vec3(3.05, 2.98, 2.88);
        fillDir = normalize(vec3(-0.35, 0.58, 0.74));
        fillCol = vec3(0.62, 0.66, 0.74);
        rimDir = normalize(vec3(0.75, 0.36, -0.55));
        rimCol = vec3(0.95, 0.98, 1.04);
        shadowK = 15.0;
    }

    vec3 Ns = m.bumpN;

    // Soft shadows from hero onto hero & bench
    float shKey = calcSoftShadow(p, N, keyDir, shadowK);
    float shRim = calcSoftShadow(p, N, rimDir, shadowK * 0.85);

    vec3 col = vec3(0.0);
    col += evalDirectPBR(Ns, V, keyDir, keyCol, m.albedo, m.roughness, m.f0, m.coatWeight, m.coatRough) * shKey;
    col += evalDirectPBR(Ns, V, fillDir, fillCol, m.albedo, m.roughness, m.f0, m.coatWeight, m.coatRough) * (0.65 + 0.35 * ao);
    col += evalDirectPBR(Ns, V, rimDir, rimCol, m.albedo, m.roughness, m.f0, m.coatWeight, m.coatRough) * shRim;

    // Image-Based Studio Reflection & Diffuse Ambient
    vec3 R = reflect(-V, Ns);
    float NoV = max(dot(Ns, V), 0.001);

    // Diffuse irradiance approximation from studio sky (kept low so charcoal asphalt stays rich & dark)
    vec3 diffEnv = mix(studioEnv(normalize(vec3(Ns.x, 0.15, Ns.z)), uLightMode),
                       studioEnv(normalize(vec3(0.0, 1.0, 0.0)), uLightMode),
                       clamp(Ns.y * 0.5 + 0.5, 0.0, 1.0));
    vec3 Fenv = F_Schlick(NoV, m.f0);
    col += m.albedo * diffEnv * (1.0 - Fenv) * 0.36 * ao;

    // Specular environment reflection (falls off strongly with roughness so matte bitumen stays dark)
    vec3 specDir = normalize(mix(R, Ns, m.roughness * m.roughness * 0.55));
    vec3 specEnv = studioEnv(specDir, uLightMode);
    float envAtten = pow(clamp(1.0 - m.roughness, 0.0, 1.0), 2.1) * 0.82;
    col += specEnv * Fenv * envAtten * (0.45 + 0.55 * ao);

    // Clearcoat IBL reflection for the poured-tar ribbon (sharp studio softbox + negative-fill contrast)
    if (m.coatWeight > 0.001) {
        vec3 coatEnv = studioEnv(R, uLightMode);
        float cF = 0.046 + (1.0 - 0.046) * pow(clamp(1.0 - NoV, 0.0, 1.0), 5.0);
        col += coatEnv * cF * m.coatWeight * (0.58 + 0.42 * ao);
    }

    // Contact shadow darkening right where the slab meets the studio bench
    if (isBench) {
        vec2 dBox = abs(p.xz) - SLAB_HALF.xz;
        float distEdge = length(max(dBox, 0.0)) + min(max(dBox.x, dBox.y), 0.0);
        float contactAO = smoothstep(-0.02, 0.22, distEdge);
        col *= mix(0.42, 1.0, contactAO);
    }

    return col;
}

// ============================================================================
// ACES Filmic Tone Mapping
// ============================================================================
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 Raymarching & Camera Setup
// ============================================================================
void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * uResolution.xy) / uResolution.y;

    // Camera modes: 0 = hero 3/4 studio view (full slab + bench shadow), 1 = ~2.5x macro close-up
    vec3 ro, ta;
    float focal;
    if (uCamMode == 1) {
        ro = vec3(0.18, 0.72, 0.86);
        ta = vec3(0.02, 0.34, 0.00);
        focal = 2.35;
    } else {
        ro = vec3(0.46, 1.86, 2.88);
        ta = vec3(0.00, 0.16, 0.02);
        focal = 2.05;
    }

    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);

    // Raymarch scene (hero slab + studio bench at y = 0.0)
    float t = 0.0;
    float tMax = 18.0;
    bool hit = false;
    for (int i = 0; i < 140; i++) {
        vec3 p = ro + rd * t;
        float d = map(p);
        if (d < 0.00055 * (1.0 + t * 0.35)) {
            hit = true;
            break;
        }
        // Conservative step near the detailed aggregate/tar surface
        float stepScale = (d < 0.12) ? 0.62 : 0.90;
        t += max(d * stepScale, 0.0005);
        if (t > tMax) break;
    }

    vec3 col;
    if (!hit) {
        // Clean studio cyclorama backdrop
        col = studioEnv(rd, uLightMode) * 0.72;
    } else {
        vec3 p = ro + rd * t;
        float dHero = mapHero(p);
        bool isBench = (p.y <= dHero + 0.001);

        vec3 N = isBench ? vec3(0.0, 1.0, 0.0) : calcNormal(p);
        vec3 V = -rd;

        Mat m;
        if (isBench) {
            // Subtle matte studio bench surface
            float benchGrain = fbm2(p.xz * 10.0) * 0.03;
            m.albedo = (uLightMode == 1)
                ? vec3(0.38)
                : vec3(0.24, 0.245, 0.255) + vec3(benchGrain);
            m.roughness = 0.80;
            m.f0 = vec3(0.03);
            m.coatWeight = 0.0;
            m.coatRough = 0.1;
            m.bumpN = N;
        } else {
            m = evalHeroMaterial(p, N);
        }

        col = shadeSurface(p, N, V, m, isBench);

        // Smooth studio bench horizon fade into cyclorama
        if (isBench) {
            float fade = smoothstep(3.6, 13.0, length(p.xz));
            vec3 bg = studioEnv(rd, uLightMode) * 0.72;
            col = mix(col, bg, fade);
        }
    }

    // Exposure calibration + ACES filmic tone mapping
    float exposure = (uLightMode == 1) ? 0.64 : 0.84;
    col *= exposure;
    col = acesFilm(col);

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

    // Gentle studio vignette (non-crushing)
    vec2 qv = gl_FragCoord.xy / uResolution.xy;
    float vig = 0.90 + 0.10 * pow(16.0 * qv.x * qv.y * (1.0 - qv.x) * (1.0 - qv.y), 0.18);
    col *= vig;

    // Gamma encode (sRGB)
    col = pow(max(col, 0.0), vec3(1.0 / 2.2));

    // Clean sRGB safety bounds (lum 12-245, 0% black/clipped, no midtone washout)
    col = clamp(col, vec3(0.048), vec3(0.960));

    fragColor = vec4(col, 1.0);
}
