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

// ============================================================================
// VFX Realistic Study 07: Artillery Dirt Geyser Impact
// Procedural blasted soil crater + 16 ballistic fractured mud/rock clods +
// dense Beer-Lambert under-lit dirt-and-dust geyser plume + airborne dirt grit
// spray + razor-sharp tapered hot shrapnel streaks.
// ============================================================================

const float PI = 3.14159265359;

// --- Fast deterministic hashes & value noise ---
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 hash13(vec3 p3) {
    p3 = fract(p3 * 0.1031);
    p3 += dot(p3, p3.zyx + 31.32);
    return fract((p3.x + p3.y) * p3.z);
}

vec3 hash31(float p) {
    vec3 p3 = fract(vec3(p) * vec3(0.1031, 0.1030, 0.0973));
    p3 += dot(p3, p3.yzx + 33.33);
    return fract((p3.xxy + p3.yzz) * p3.zyx);
}

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

// Interleaved gradient noise for clean volumetric jitter
float ign(vec2 p) {
    return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));
}

float noise2(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 noise3(vec3 p) {
    vec3 i = floor(p);
    vec3 f = fract(p);
    vec3 u = 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));
    return mix(
        mix(mix(n000, n100, u.x), mix(n010, n110, u.x), u.y),
        mix(mix(n001, n101, u.x), mix(n011, n111, u.x), u.y),
        u.z
    );
}

const mat2 ROT2 = mat2(0.80, -0.60, 0.60, 0.80);

float fbm2(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 5; i++) {
        v += a * noise2(p);
        p = ROT2 * p * 2.04 + vec2(17.1, 31.7);
        a *= 0.5;
    }
    return v;
}

float fbm3(vec3 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * noise3(p);
        p = vec3(
            0.80 * p.x - 0.60 * p.z,
            p.y * 1.02 + 13.7,
            0.60 * p.x + 0.80 * p.z
        ) * 2.03 + vec3(7.3, 19.1, 11.4);
        a *= 0.5;
    }
    return v;
}

// Billowy cauliflower turbulence for dense explosive dust clouds
float billow3(vec3 p) {
    float v = 0.0;
    float a = 0.52;
    for (int i = 0; i < 4; i++) {
        float n = noise3(p);
        float b = 1.0 - abs(n * 2.0 - 1.0);
        v += a * b * b;
        p = vec3(
            0.80 * p.x - 0.60 * p.z,
            p.y * 1.04 + 9.2,
            0.60 * p.x + 0.80 * p.z
        ) * 2.08 + vec3(11.7, 5.3, 23.1);
        a *= 0.48;
    }
    return v;
}

// Fast 1-cell 3D cellular dirt-grit field for crisp airborne gravel/soil flecks
float gritSpeck(vec3 p) {
    vec3 cell = floor(p);
    vec3 f = fract(p);
    vec3 rnd = hash33(cell);
    // Only populate ~42% of cells so specks are sparse and crisp
    if (rnd.z < 0.58) return 0.0;
    vec3 center = 0.22 + 0.56 * rnd;
    float d = length(f - center);
    float r = mix(0.06, 0.145, hash13(cell + 19.3));
    return 1.0 - smoothstep(r * 0.55, r, d);
}

// Rotation matrix around arbitrary unit axis
mat3 rotAxis(vec3 ax, float a) {
    float s = sin(a);
    float c = cos(a);
    float oc = 1.0 - c;
    return mat3(
        oc * ax.x * ax.x + c,        oc * ax.x * ax.y - ax.z * s, oc * ax.z * ax.x + ax.y * s,
        oc * ax.x * ax.y + ax.z * s, oc * ax.y * ax.y + c,        oc * ax.y * ax.z - ax.x * s,
        oc * ax.z * ax.x - ax.y * s, oc * ax.y * ax.z + ax.x * s, oc * ax.z * ax.z + c
    );
}

// ============================================================================
// 1. Procedural Blasted Cratered Earth Terrain
// ============================================================================
float craterRadiusAt(vec2 xz) {
    float ang = atan(xz.y, xz.x);
    float jag = 0.11 * sin(ang * 3.0 + 0.7)
              + 0.075 * cos(ang * 5.0 - 1.3)
              + 0.05 * sin(ang * 9.0 + 2.1)
              + 0.035 * cos(ang * 15.0 - 0.4);
    return 1.48 + jag;
}

float groundHeight(vec2 xz) {
    float r = length(xz);
    float rC = craterRadiusAt(xz);
    float rNorm = r / rC;

    // Deep blasted crater pit with steep jagged inner walls
    float pitMask = 1.0 - smoothstep(0.60, 1.02, rNorm);
    float wallSteep = smoothstep(0.55, 0.98, rNorm) * (1.0 - smoothstep(0.98, 1.14, rNorm));
    float pit = -0.98 * pitMask;

    // Sharp vertical blast gouges on inner crater wall
    float ang = atan(xz.y, xz.x);
    float wallGouge = (abs(noise2(vec2(ang * 11.0, r * 5.0)) * 2.0 - 1.0) - 0.45) * 0.24 * wallSteep;

    // Raised jagged ejecta rim around the crater lip
    float rim = 0.26 * exp(-pow((rNorm - 1.12) / 0.34, 2.0));
    float radialStrata = (noise2(vec2(ang * 8.0, r * 2.5)) - 0.45) * 0.15
                       * exp(-pow((rNorm - 1.18) / 0.55, 2.0));

    // Crumbly, cloddy blasted dry earth across foreground and rim
    float macroRoll = (fbm2(xz * 0.45 + vec2(3.1, -1.7)) - 0.5) * 0.22 * smoothstep(0.8, 2.4, rNorm);
    float clodsMed = pow(1.0 - abs(noise2(xz * 2.6) * 2.0 - 1.0), 1.6) * 0.13;
    float clodsFine = pow(1.0 - abs(noise2(xz * 7.5 + 4.3) * 2.0 - 1.0), 1.5) * 0.055;
    float grit = (noise2(xz * 21.0) - 0.5) * 0.026;

    float soilRough = (clodsMed + clodsFine + grit) * (0.45 + 0.80 * smoothstep(0.55, 1.05, rNorm));

    return pit + wallGouge + rim + radialStrata + macroRoll + soilRough - 0.05;
}

float sdGround(vec3 p) {
    float h = groundHeight(p.xz);
    return (p.y - h) * 0.54;
}

// ============================================================================
// 2. Ballistic Fractured Jagged Dirt & Rock Clods (16 Clods)
// ============================================================================
struct ClodKin {
    vec3 pos;
    float rad;
    vec3 axis;
    float angle;
    float seed;
};

ClodKin getClod(int id) {
    float fid = float(id);
    vec3 h = hash31(fid * 13.71 + 4.19);
    vec3 h2 = hash31(fid * 29.37 + 11.83);

    float blastOpen = 1.0 + 0.08 * uOpen;
    float grav = 2.15;
    float period = 3.0;

    vec3 p0 = vec3(0.0);
    vec3 vel = vec3(0.0);
    float rad = 0.15;
    float phase = 0.0;

    if (id == 0) {
        // Large hero craggy clod center-right of plume (iconic ref chunk)
        phase = 0.05;
        p0 = vec3(0.04, -0.32, 0.18);
        vel = vec3(0.24, 3.02, 0.68) * blastOpen;
        rad = 0.33;
    } else if (id == 1) {
        // Chunky hero clod lower-right of plume
        phase = 0.25;
        p0 = vec3(0.18, -0.30, 0.22);
        vel = vec3(0.58, 2.58, 0.56) * blastOpen;
        rad = 0.26;
    } else if (id == 2) {
        // Dark dramatic silhouette clod upper-left
        phase = 0.38;
        p0 = vec3(-0.18, -0.28, 0.10);
        vel = vec3(-0.92, 3.92, 0.36) * blastOpen;
        rad = 0.24;
    } else if (id == 3) {
        // Mid-left flying mud chunk
        phase = 0.12;
        p0 = vec3(-0.22, -0.30, 0.25);
        vel = vec3(-1.32, 2.38, 0.42) * blastOpen;
        rad = 0.19;
    } else if (id == 4) {
        // Lower-left foreground clod above crater rim
        phase = 0.52;
        p0 = vec3(-0.28, -0.25, 0.30);
        vel = vec3(-0.98, 2.26, 0.62) * blastOpen;
        rad = 0.17;
    } else if (id == 5) {
        // Mid-center chunk just below hero #0
        phase = 0.18;
        p0 = vec3(-0.08, -0.35, 0.20);
        vel = vec3(-0.16, 2.52, 0.65) * blastOpen;
        rad = 0.18;
    } else {
        // 10 secondary jagged mud/rock clods spraying outward along V-cone
        float side = (mod(fid, 2.0) < 0.5) ? 1.0 : -1.0;
        float az = (h.x * 0.85 + 0.15) * PI * side + (h2.x - 0.5) * 0.5;
        float spread = mix(0.55, 1.75, h.y);
        phase = fract(fid * 0.231 + 0.17) * period;
        p0 = vec3(cos(az) * 0.32, -0.34, sin(az) * 0.28);
        vel = vec3(
            cos(az) * spread,
            mix(2.35, 3.95, h.z),
            sin(az) * spread * 0.62 + 0.22
        ) * blastOpen;
        rad = mix(0.08, 0.165, h2.y * h2.y);
    }

    float tau = mod(uTime + phase, period);
    float env = smoothstep(0.0, 0.16, tau) * (1.0 - smoothstep(2.45, 2.92, tau));

    vec3 pos = p0 + vel * tau + vec3(0.0, -0.5 * grav * tau * tau, 0.0);
    vec3 axis = normalize(h2 * 2.0 - 1.0 + vec3(0.01, 0.02, -0.01));
    float spinRate = mix(1.8, 4.6, h.x) * ((h.z > 0.5) ? 1.0 : -1.0);
    float angle = uTime * spinRate + fid * 2.17;

    ClodKin k;
    k.pos = pos;
    k.rad = rad * env;
    k.axis = axis;
    k.angle = angle;
    k.seed = fid * 7.31 + 1.13;
    return k;
}

float sdJaggedClod(vec3 p, ClodKin k) {
    if (k.rad < 0.01) return 1e5;
    vec3 q = p - k.pos;
    float bound = length(q) - k.rad * 1.45;
    if (bound > 0.20) return bound;

    q = rotAxis(k.axis, k.angle) * q;
    vec3 s = q / k.rad;

    // Sharp fractured polyhedral earth clod (6 cleavage planes)
    vec3 h = hash31(k.seed);
    vec3 dims = vec3(
        mix(0.70, 1.15, h.x),
        mix(0.55, 0.96, h.y),
        mix(0.68, 1.10, h.z)
    );
    vec3 bq = abs(s) - dims;
    float d = length(max(bq, 0.0)) + min(max(bq.x, max(bq.y, bq.z)), 0.0);

    // Hard angular rock/soil fracture planes
    float c1 = dot(s, normalize(vec3(0.66, 0.54, -0.52))) - 0.66;
    float c2 = dot(s, normalize(vec3(-0.74, 0.40, 0.54))) - 0.62;
    float c3 = dot(s, normalize(vec3(0.18, -0.82, 0.54))) - 0.60;
    float c4 = dot(s, normalize(vec3(-0.42, -0.60, -0.68))) - 0.64;
    float c5 = dot(s, normalize(vec3(0.78, -0.25, 0.57))) - 0.68;
    d = max(d, max(max(c1, c2), max(c3, max(c4, c5))));

    // Craggy, dry crumbly stratified earth displacement
    float n1 = noise3(s * 3.4 + vec3(k.seed)) - 0.5;
    float n2 = abs(noise3(s * 7.8 + vec3(k.seed * 1.7)) * 2.0 - 1.0) - 0.5;
    float n3 = noise3(s * 15.5 + vec3(k.seed * 2.9)) - 0.5;
    float strata = sin(s.y * 13.0 + n1 * 5.0) * 0.045;
    d += n1 * 0.26 + n2 * 0.14 + n3 * 0.055 + strata;

    return d * k.rad * 0.58;
}

// Returns vec2(distance, materialID): 0 = ground, 1 = clod
vec2 mapScene(vec3 p) {
    float dG = sdGround(p);
    vec2 res = vec2(dG, 0.0);

    if (p.y > -0.6 && p.y < 5.6 && dot(p.xz, p.xz) < 28.0) {
        for (int i = 0; i < 16; i++) {
            ClodKin ck = getClod(i);
            if (ck.rad < 0.01) continue;
            float dC = sdJaggedClod(p, ck);
            if (dC < res.x) {
                res = vec2(dC, 1.0);
            }
        }
    }
    return res;
}

// Unit-sign tetrahedral normals
vec3 calcNormal(vec3 p) {
    const float eps = 0.0024;
    const vec2 k = vec2(1.0, -1.0);
    return normalize(
        k.xyy * mapScene(p + k.xyy * eps).x +
        k.yyx * mapScene(p + k.yyx * eps).x +
        k.yxy * mapScene(p + k.yxy * eps).x +
        k.xxx * mapScene(p + k.xxx * eps).x
    );
}

// Dual-octave micro-crumb normal perturbation for dry crumbly matte soil
vec3 bumpNormal(vec3 p, vec3 n, float scale, float strength) {
    float e = 0.006;
    float c1 = noise3(p * scale);
    vec3 g1 = vec3(
        noise3((p + vec3(e, 0.0, 0.0)) * scale) - c1,
        noise3((p + vec3(0.0, e, 0.0)) * scale) - c1,
        noise3((p + vec3(0.0, 0.0, e)) * scale) - c1
    ) / e;

    float s2 = scale * 2.4;
    float c2 = noise3(p * s2);
    vec3 g2 = vec3(
        noise3((p + vec3(e, 0.0, 0.0)) * s2) - c2,
        noise3((p + vec3(0.0, e, 0.0)) * s2) - c2,
        noise3((p + vec3(0.0, 0.0, e)) * s2) - c2
    ) / e;

    vec3 grad = g1 * 0.65 + g2 * 0.35;
    grad -= n * dot(grad, n);
    return normalize(n - grad * strength);
}

// ============================================================================
// 3. Volumetric Dirt & Dust Geyser Plume Field + Airborne Grit Spray
// ============================================================================
const vec3 VOL_CENTER = vec3(0.15, 2.05, 0.0);
const float VOL_RADIUS = 4.95;

// Returns vec3(dustDensity, fireEmission, gritMask)
vec3 evalPlume(vec3 p) {
    // Smooth bounding-sphere fade well inside VOL_RADIUS so zero clipping edges ever appear
    float distCenter = length(p - VOL_CENTER);
    if (distCenter >= VOL_RADIUS) return vec3(0.0);
    float boundFade = 1.0 - smoothstep(VOL_RADIUS * 0.66, VOL_RADIUS * 0.94, distCenter);
    if (boundFade < 0.001) return vec3(0.0);

    float t = uTime;
    float h = max(p.y + 0.35, 0.0);
    float blastScale = 1.0 + 0.06 * uOpen;

    // Asymmetric violent V-shaped geyser envelope matching reference
    float vRad = (0.94 + 0.42 * pow(h, 1.04)) * blastScale;

    // 1. Core central erupting column
    float rCore = length(p.xz - vec2(0.05 * h, -0.05 * h));
    float envCore = 1.0 - smoothstep(0.24 * vRad, 0.90 * vRad, rCore);
    envCore *= smoothstep(-0.48, 0.22, p.y) * (1.0 - smoothstep(2.45, 4.15, p.y));

    // 2. Massive billowing upper-right dust lobe reaching top-right (well inside VOL_RADIUS)
    vec2 dR = p.xz - vec2(0.22 + 0.22 * h, -0.10 - 0.04 * h);
    float rRight = length(dR);
    float envRight = 1.0 - smoothstep(0.30, 1.18 + 0.16 * h, rRight);
    envRight *= smoothstep(0.45, 1.45, p.y) * (1.0 - smoothstep(3.45, 4.75, p.y));

    // 3. Dense mid-left billowing lobe
    vec3 cLeft = vec3(-0.96, 1.98, 0.14);
    float rLeft = length((p - cLeft) * vec3(0.86, 0.72, 0.92));
    float envLeft = 1.0 - smoothstep(0.28, 1.20, rLeft);

    // 4. Lower crater-rim swirling dust collar
    float rCollar = length(p.xz);
    float envCollar = (1.0 - smoothstep(0.62, 1.78, rCollar))
                    * smoothstep(-0.35, 0.12, p.y)
                    * (1.0 - smoothstep(0.32, 1.08, p.y));

    float env = max(max(envCore, envRight * 0.96), max(envLeft * 0.94, envCollar * 0.76));

    // Upward & radially outward turbulent advection
    vec3 radDir = vec3(p.x, 0.0, p.z) / (length(p.xz) + 0.35);
    vec3 advP = p - vec3(0.0, t * 1.10, 0.0) - radDir * (t * 0.20 * clamp(h * 0.4, 0.0, 1.0));

    float dust = 0.0;
    float grit = 0.0;

    if (env > 0.005) {
        // Domain warp for swirling blast eddies
        vec3 warp = vec3(
            noise3(advP * 0.88 + vec3(1.2, 0.0, 3.4)) - 0.5,
            noise3(advP * 0.88 + vec3(5.7, 2.1, 0.8)) - 0.5,
            noise3(advP * 0.88 + vec3(2.9, 6.4, 4.1)) - 0.5
        );
        vec3 q = advP + warp * (0.48 + 0.11 * h);

        // Dense cauliflower billowing clouds with crisp sculptural edges
        float b = billow3(q * 0.98);
        float detail = fbm3(q * 2.35 + vec3(0.0, -t * 0.55, 0.0));

        float shape = env * (0.62 + 0.82 * b) - (0.36 - 0.18 * detail);
        dust = smoothstep(0.04, 0.42, shape) * (1.85 + 1.55 * b);

        // Keep white-hot crater core visible through lower dust
        vec3 cp = p - vec3(-0.10, -0.04, 0.06);
        float coreClear = 1.0 - 0.62 * exp(-dot(cp, cp) * 2.4);
        dust *= coreClear;
    }

    // Crisp airborne dirt/gravel grit spray erupting around the clods and V-cone
    float gritEnv = (1.0 - smoothstep(0.65 * vRad, 1.48 * vRad, length(p.xz)))
                  * smoothstep(-0.10, 0.45, p.y)
                  * (1.0 - smoothstep(3.2, 4.6, p.y));
    if (gritEnv > 0.01) {
        vec3 gritP = p - vec3(0.0, t * 1.65, 0.0) - radDir * (t * 0.55);
        float g1 = gritSpeck(gritP * 5.2);
        float g2 = gritSpeck(gritP * 9.4 + vec3(7.1, 3.3, 11.7));
        grit = (g1 * 1.0 + g2 * 0.7) * gritEnv;
    }

    // --- Fiery White-Hot / Orange Crater Core Emission ---
    float pulse = 0.90 + 0.14 * sin(t * 7.5) + 0.08 * sin(t * 17.3);
    vec3 fp = p - vec3(-0.12, -0.20, 0.06);
    float fDist = length(fp * vec3(1.12, 0.86, 1.12));
    float fireTurb = fbm3(p * 2.7 - vec3(0.0, t * 2.8, 0.0));
    float fireCore = smoothstep(1.12, 0.06, fDist + (fireTurb - 0.48) * 0.50);
    float innerCrater = (1.0 - smoothstep(0.60, 1.46, length(p.xz)))
                      * smoothstep(-0.72, -0.25, p.y)
                      * (1.0 - smoothstep(-0.04, 0.72, p.y));
    float fireTongues = innerCrater * smoothstep(0.34, 0.76, fireTurb) * 0.72;
    float fire = (fireCore * 2.15 + fireTongues) * pulse;

    return vec3(max(dust, 0.0) * boundFade, max(fire, 0.0) * boundFade, grit * boundFade);
}

// Henyey-Greenstein phase function
float hgPhase(float cosTheta, float g) {
    float g2 = g * g;
    return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * cosTheta, 0.001), 1.5));
}

// ============================================================================
// 4. Razor-Sharp Tapered Glowing Hot Shrapnel Streaks (3D Analytic Segments)
// ============================================================================
// Returns vec3(dist, rayT, segFrac) where segFrac in [0, 1] (0 = tail, 1 = head)
vec3 raySegDist(vec3 ro, vec3 rd, vec3 a, vec3 b) {
    vec3 u = rd;
    vec3 v = b - a;
    vec3 w = ro - a;
    float aDot = dot(u, u);
    float bDot = dot(u, v);
    float cDot = dot(v, v);
    float dDot = dot(u, w);
    float eDot = dot(v, w);
    float denom = aDot * cDot - bDot * bDot;

    float sc, tc;
    if (denom < 1e-6) {
        sc = 0.0;
        tc = (bDot > cDot ? dDot / bDot : eDot / cDot);
    } else {
        sc = (bDot * eDot - cDot * dDot) / denom;
        tc = (aDot * eDot - bDot * dDot) / denom;
    }
    tc = clamp(tc, 0.0, 1.0);
    sc = max((bDot * tc - dDot) / aDot, 0.0);

    vec3 dp = (ro + rd * sc) - (a + v * tc);
    return vec3(length(dp), sc, tc);
}

vec3 evalShrapnel(vec3 ro, vec3 rd, float maxT, float flashMult) {
    if (flashMult < 0.05) return vec3(0.0);
    vec3 glow = vec3(0.0);

    for (int i = 0; i < 26; i++) {
        float fi = float(i);
        vec3 h = hash31(fi * 19.31 + 7.13);
        vec3 h2 = hash31(fi * 41.17 + 2.71);

        float az = (h.x * 2.0 - 1.0) * PI;
        float elev = mix(0.28, 1.38, h.y);
        if (i < 8) {
            // Iconic razor-thin bright streaks shooting up-left and sideways into dark sky
            az = mix(-0.32, 0.32, h.x) + ((mod(fi, 2.0) < 0.5) ? 0.0 : PI);
            elev = mix(0.30, 1.24, h.y);
        } else if (i < 15) {
            // Short hot sparks right inside the crater mouth and lower geyser
            elev = mix(0.95, 1.50, h.y);
        }

        vec3 dir = normalize(vec3(
            cos(elev) * cos(az),
            sin(elev),
            cos(elev) * sin(az) * 0.55
        ));

        float speed = (i < 15 && i >= 8) ? mix(2.2, 4.4, h2.x) : mix(5.2, 9.6, h2.x);
        float cycle = (i < 15 && i >= 8) ? 0.72 : 1.30;
        float tau = mod(uTime * 1.05 + h2.y * cycle, cycle);

        vec3 origin = vec3((h2.z - 0.5) * 0.60, -0.25, (h.z - 0.5) * 0.42);
        vec3 head = origin + dir * (speed * tau) + vec3(0.0, -0.75 * tau * tau, 0.0);
        float streakLen = mix(0.24, 0.68, h.z) * (speed * 0.10);
        vec3 velNow = normalize(dir * speed + vec3(0.0, -1.5 * tau, 0.0));
        vec3 tail = head - velNow * streakLen;

        vec3 ds = raySegDist(ro, rd, tail, head);
        if (ds.y > 0.1 && ds.y < maxT) {
            float lifeFade = smoothstep(0.0, 0.08, tau) * (1.0 - smoothstep(cycle * 0.65, cycle, tau));
            // Taper width & brightness from tail (0) to hot leading tip (1)
            float taper = smoothstep(0.0, 0.85, ds.z);
            float tipFade = 1.0 - smoothstep(0.92, 1.0, ds.z) * 0.25;
            float w = mix(0.0011, 0.0028, h2.z) * (0.45 + 0.55 * taper) * (0.65 + 0.10 * ds.y);

            float core = exp(-pow(ds.x / w, 2.0));
            float halo = exp(-ds.x / (w * 3.2)) * 0.09;

            vec3 sCol = mix(vec3(1.0, 0.40, 0.06), vec3(1.0, 0.94, 0.78), core * taper);
            glow += sCol * (core * 2.6 + halo) * (0.20 + 0.80 * taper) * tipFade * lifeFade * flashMult;
        }
    }
    return glow;
}

// ============================================================================
// 5. Battlefield Night-Slate Backdrop & Lighting Setup
// ============================================================================
struct LightRig {
    vec3 keyDir;
    vec3 keyCol;
    vec3 fillCol;
    vec3 rimDir;
    vec3 rimCol;
    vec3 craterPos;
    vec3 craterCol;
    float flashMult;
};

LightRig getLightRig() {
    LightRig r;
    r.craterPos = vec3(-0.08, -0.14, 0.06);
    float pulse = 0.92 + 0.10 * sin(uTime * 7.5) + 0.06 * sin(uTime * 17.3);

    if (uLightMode == 1) {
        // Mode 1: Pure neutral grayscale study with crisp sculptural light/shadow range
        r.keyDir = normalize(vec3(-0.58, 0.72, 0.38));
        r.keyCol = vec3(1.18);
        r.fillCol = vec3(0.038);
        r.rimDir = normalize(vec3(0.45, 0.55, -0.70));
        r.rimCol = vec3(0.58);
        r.craterCol = vec3(0.10);
        r.flashMult = 0.02;
    } else if (uLightMode == 2) {
        // Mode 2: Grazing raking key light
        r.keyDir = normalize(vec3(0.92, 0.18, 0.34));
        r.keyCol = vec3(1.65, 1.38, 1.05);
        r.fillCol = vec3(0.015, 0.019, 0.026);
        r.rimDir = normalize(vec3(-0.82, 0.28, -0.48));
        r.rimCol = vec3(0.28, 0.38, 0.54);
        r.craterCol = vec3(1.8, 0.80, 0.22) * pulse;
        r.flashMult = 0.38;
    } else if (uLightMode == 3) {
        // Mode 3: Backlit rim light
        r.keyDir = normalize(vec3(-0.35, 0.65, 0.65));
        r.keyCol = vec3(0.14, 0.17, 0.22);
        r.fillCol = vec3(0.012, 0.016, 0.024);
        r.rimDir = normalize(vec3(-0.22, 0.42, -0.88));
        r.rimCol = vec3(1.85, 1.48, 1.05);
        r.craterCol = vec3(3.2, 1.25, 0.28) * pulse;
        r.flashMult = 0.68;
    } else {
        // Mode 0: Dramatic dark battlefield night-slate sky + blazing crater under-lighting
        r.keyDir = normalize(vec3(-0.62, 0.70, 0.35));
        r.keyCol = vec3(0.22, 0.27, 0.35);
        r.fillCol = vec3(0.014, 0.018, 0.025);
        r.rimDir = normalize(vec3(-0.48, 0.55, -0.68));
        r.rimCol = vec3(0.18, 0.23, 0.32);
        r.craterCol = vec3(7.2, 2.85, 0.62) * pulse;
        r.flashMult = 1.0;
    }
    return r;
}

vec3 evalBackdrop(vec3 rd, LightRig rig) {
    if (uLightMode == 1) {
        // Clean dark charcoal studio gradient for high-contrast grayscale study
        float g = mix(0.012, 0.036, smoothstep(-0.15, 0.65, rd.y));
        float cloud = fbm2(rd.xy * 3.0 + vec2(uTime * 0.03, 0.0));
        return vec3(g + (cloud - 0.5) * 0.008);
    }

    // Dramatic dark night-slate battlefield sky (subtle misty upper-left glow like ref)
    float h = clamp(rd.y * 0.5 + 0.5, 0.0, 1.0);
    vec3 skyDark = vec3(0.0028, 0.0036, 0.0052);
    vec3 skyMid  = vec3(0.0065, 0.0088, 0.0125);
    vec3 skyMist = vec3(0.026, 0.033, 0.044);

    vec3 col = mix(skyDark, skyMid, smoothstep(0.35, 0.85, h));

    // Cool moonlit battlefield smoke mist in upper-left corner
    float leftMist = smoothstep(0.35, -0.60, rd.x) * smoothstep(0.02, 0.62, rd.y);
    float smokeTex = fbm2(rd.xy * 3.2 + vec2(-0.4, uTime * 0.02));
    col = mix(col, skyMist, leftMist * (0.40 + 0.50 * smokeTex));

    // Subtle warm horizon smoke bounce from impact
    float horizGlow = exp(-abs(rd.y + 0.09) * 8.5) * exp(-rd.x * rd.x * 2.6);
    col += vec3(0.045, 0.018, 0.006) * horizGlow * rig.flashMult;

    if (uLightMode == 3) {
        float backSun = pow(max(dot(rd, rig.rimDir), 0.0), 6.0);
        col += rig.rimCol * backSun * 0.35;
    }

    return col;
}

// Soft shadow march for solid surfaces
float calcSoftShadow(vec3 ro, vec3 rd, float tMin, float tMax) {
    float res = 1.0;
    float t = tMin;
    for (int i = 0; i < 20; i++) {
        float h = mapScene(ro + rd * t).x;
        res = min(res, 6.0 * h / t);
        t += clamp(h, 0.04, 0.32);
        if (res < 0.02 || t > tMax) break;
    }
    return clamp(res, 0.0, 1.0);
}

// Oren-Nayar matte rough diffuse approximation (roughness ~ 0.94, zero plastic sheen)
float orenNayar(vec3 n, vec3 l, vec3 v, float rough) {
    float ndl = max(dot(n, l), 0.0);
    if (ndl <= 0.0) return 0.0;
    float ndv = max(dot(n, v), 0.0);
    float r2 = rough * rough;
    float A = 1.0 - 0.5 * (r2 / (r2 + 0.33));
    float B = 0.45 * (r2 / (r2 + 0.09));
    vec3 lProj = l - n * ndl;
    vec3 vProj = v - n * ndv;
    float cosPhi = max(dot(normalize(lProj + 1e-4), normalize(vProj + 1e-4)), 0.0);
    float sinAlpha = sqrt(max(1.0 - min(ndl, ndv) * min(ndl, ndv), 0.0));
    float tanBeta = sqrt(max(1.0 - max(ndl, ndv) * max(ndl, ndv), 0.0)) / max(max(ndl, ndv), 0.05);
    return ndl * (A + B * cosPhi * sinAlpha * tanBeta);
}

// Shade matte dry blasted soil ground and fractured dark mud/rock clods
vec3 shadeSolid(vec3 p, vec3 n, vec3 v, float matID, LightRig rig) {
    // Strong dual-octave crumbly soil micro-bump
    vec3 nb = bumpNormal(p, n, (matID > 0.5) ? 13.5 : 9.0, (matID > 0.5) ? 0.38 : 0.28);

    // Dry matte dark-brown dirt & rock albedo
    float nMacro = fbm3(p * 1.5);
    float nFine = noise3(p * 12.5);
    float nCrumb = noise3(p * 30.0);

    vec3 soilDark = vec3(0.028, 0.022, 0.017);
    vec3 soilMid  = vec3(0.072, 0.056, 0.042);
    vec3 soilDust = vec3(0.135, 0.106, 0.078);

    vec3 albedo = mix(soilDark, soilMid, nMacro);
    albedo = mix(albedo, soilDust, smoothstep(0.54, 0.88, nFine) * 0.42);
    albedo *= (0.72 + 0.52 * nCrumb);

    if (matID > 0.5) {
        // Airborne mud/rock clods: dense dark dry earth with dusty edges
        albedo *= 0.85;
    } else {
        // Scorched inner crater walls
        float rC = length(p.xz) / craterRadiusAt(p.xz);
        float scorch = 1.0 - smoothstep(0.58, 1.15, rC);
        albedo = mix(albedo, vec3(0.14, 0.09, 0.05), scorch * 0.50);
    }

    if (uLightMode == 1) {
        float g = dot(albedo, vec3(0.299, 0.587, 0.114));
        albedo = vec3(mix(0.10, 0.36, g * 4.5));
    }

    // Crevice AO for deep fractured dirt clod shadows
    float ao = clamp(0.38 + 0.62 * mapScene(p + nb * 0.16).x / 0.16, 0.14, 1.0);
    ao *= clamp(0.45 + 0.55 * nb.y, 0.22, 1.0);
    float rough = 0.94;

    // 1. Directional sky/key light (matte Oren-Nayar, no plastic spec)
    float diffKey = orenNayar(nb, rig.keyDir, v, rough);
    float shKey = calcSoftShadow(p + nb * 0.03, rig.keyDir, 0.05, 5.5);
    vec3 col = albedo * rig.keyCol * diffKey * (0.20 + 0.80 * shKey);

    // 2. Subtle matte rim light (no chrome/plastic Fresnel)
    float diffRim = orenNayar(nb, rig.rimDir, v, rough);
    float dustRim = pow(1.0 - max(dot(nb, v), 0.0), 3.0) * 0.06 * diffRim;
    col += albedo * rig.rimCol * (diffRim * 0.72 + dustRim * 2.0);

    // 3. Intense warm orange-gold crater under-lighting
    vec3 toCrater = rig.craterPos - p;
    float dCrater = length(toCrater);
    vec3 lCrater = toCrater / max(dCrater, 0.001);
    float atten = 1.0 / (0.26 + 0.55 * dCrater * dCrater);
    float diffCrater = orenNayar(nb, lCrater, v, rough);
    float wrapCrater = clamp((dot(nb, lCrater) + 0.22) / 1.22, 0.0, 1.0);

    float innerBoost = 1.0;
    if (matID < 0.5) {
        float rC = length(p.xz) / craterRadiusAt(p.xz);
        float inWall = 1.0 - smoothstep(0.84, 1.06, rC);
        innerBoost = 1.0 + 2.35 * inWall;
        // Raised rim casts shadow across outer foreground dirt
        float rimShadow = mix(1.0, 0.16, smoothstep(1.04, 1.50, rC) * smoothstep(0.26, -0.05, p.y));
        atten *= rimShadow;
    }

    vec3 craterLight = rig.craterCol * atten * innerBoost;
    col += albedo * (diffCrater * 0.92 + wrapCrater * 0.25) * craterLight;

    // 4. Subtle dark ambient fill (keeps shadowed upper faces dark & readable)
    col += albedo * rig.fillCol * (0.40 + 0.60 * ao);

    // Distance atmospheric night-smoke falloff on far terrain
    if (matID < 0.5) {
        float dist = length(p.xz);
        float fog = 1.0 - exp(-max(dist - 2.6, 0.0) * 0.16);
        vec3 fogCol = evalBackdrop(normalize(vec3(p.x, 0.04, p.z)), rig);
        col = mix(col, fogCol, clamp(fog, 0.0, 0.95));
    }

    return col;
}

// ============================================================================
// 6. Volumetric Beer-Lambert Integration (60 Jittered Steps)
// ============================================================================
void marchPlume(
    vec3 ro, vec3 rd, float tMaxSolid, float jitter, LightRig rig,
    inout vec3 accumLight, inout float transmittance
) {
    vec3 oc = ro - VOL_CENTER;
    float b = dot(oc, rd);
    float c = dot(oc, oc) - VOL_RADIUS * VOL_RADIUS;
    float disc = b * b - c;
    if (disc < 0.0) return;

    float sq = sqrt(disc);
    float t0 = max(-b - sq, 0.05);
    float t1 = min(-b + sq, tMaxSolid);
    if (t1 <= t0) return;

    const int STEPS = 60;
    float dt = (t1 - t0) / float(STEPS);
    float t = t0 + dt * jitter;

    float sigmaT = 3.15;
    vec3 dustUpper = (uLightMode == 1)
        ? vec3(0.46)
        : vec3(0.38, 0.285, 0.205);
    vec3 dustDark = (uLightMode == 1)
        ? vec3(0.14)
        : vec3(0.055, 0.038, 0.026);
    vec3 gritCol = (uLightMode == 1)
        ? vec3(0.08)
        : vec3(0.024, 0.018, 0.013);

    float cosKey = dot(rd, rig.keyDir);
    float phaseKey = mix(hgPhase(cosKey, 0.35), hgPhase(cosKey, -0.15), 0.35);
    float cosRim = dot(rd, rig.rimDir);
    float phaseRim = hgPhase(cosRim, (uLightMode == 3) ? 0.68 : 0.45);

    for (int i = 0; i < STEPS; i++) {
        vec3 p = ro + rd * t;
        vec3 dfg = evalPlume(p);
        float dens = dfg.x;
        float fire = dfg.y;
        float grit = dfg.z;

        float totalDens = dens + grit * 4.8;
        if (totalDens > 0.002 || fire > 0.002) {
            if (totalDens > 0.002) {
                float stepExt = totalDens * sigmaT * dt;
                float stepT = exp(-stepExt);

                // 2-tap Beer-Lambert self-shadowing toward blazing crater core
                vec3 toCrater = rig.craterPos - p;
                float dCrater = length(toCrater);
                vec3 lCrater = toCrater / max(dCrater, 0.001);
                float odCrater = evalPlume(p + lCrater * 0.30).x * 0.58
                               + evalPlume(p + lCrater * 0.82).x * 0.92;
                float trCrater = exp(-odCrater * 2.35);
                // Warm multi-scatter glow deep inside thick billows
                float msCrater = exp(-odCrater * 0.55) * 0.26;
                float cosCrater = dot(rd, lCrater);
                float phaseCrater = 0.40 + 0.60 * hgPhase(cosCrater, 0.42) * 3.2;
                float craterAtten = 1.0 / (0.30 + 0.46 * dCrater * dCrater);
                vec3 litCrater = rig.craterCol * craterAtten * (trCrater + msCrater) * phaseCrater;

                // 1-tap self-shadowing toward key/skylight
                float odKey = evalPlume(p + rig.keyDir * 0.50).x * 1.15;
                float trKey = exp(-odKey * 1.85);
                float powder = 1.0 - 0.70 * exp(-dens * 2.6);
                vec3 litKey = rig.keyCol * (trKey * 0.88 + 0.12) * (0.40 + 1.8 * phaseKey) * powder;

                // Backlit rim contribution
                float odRim = evalPlume(p + rig.rimDir * 0.46).x * 1.05;
                float trRim = exp(-odRim * 1.55);
                vec3 litRim = rig.rimCol * trRim * (0.32 + 2.5 * phaseRim);

                // Dense dark charcoal-umber lower clouds -> warm tan-brown upper billows
                float hNorm = clamp((p.y + 0.15) / 4.0, 0.0, 1.0);
                vec3 dustAlbedo = mix(dustDark, dustUpper, 0.22 + 0.78 * hNorm);

                // Blend dark opaque dirt-grit specks with dust albedo
                float gritWeight = (grit * 4.8) / max(totalDens, 1e-4);
                vec3 localAlbedo = mix(dustAlbedo, gritCol, gritWeight);

                vec3 scatter = localAlbedo * (litCrater + litKey + litRim + rig.fillCol * 0.75);

                accumLight += transmittance * scatter * (1.0 - stepT);
                transmittance *= stepT;
            }

            // --- Incandescent white-hot / fiery-orange crater fireball emission ---
            if (fire > 0.002 && rig.flashMult > 0.01) {
                float fTemp = clamp(fire, 0.0, 2.0);
                vec3 fireCol = mix(
                    vec3(1.0, 0.28, 0.03),
                    mix(vec3(1.0, 0.70, 0.18), vec3(1.0, 0.97, 0.88), smoothstep(0.60, 1.35, fTemp)),
                    smoothstep(0.10, 0.70, fTemp)
                );
                accumLight += transmittance * fireCol * fire * 2.85 * rig.flashMult * dt;
            }

            if (transmittance < 0.012) {
                transmittance = 0.0;
                break;
            }
        }
        t += dt;
    }
}

// ============================================================================
// 7. ACES Filmic Tone Mapping (Soft Shoulder, %clip < 1%)
// ============================================================================
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;
    vec3 mapped = clamp((x * (a * x + b)) / (x * (c * x + d) + e), 0.0, 1.0);
    return mapped / (1.0 + 0.035 * mapped);
}

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

    // Camera setup
    vec3 ro, ta;
    float fl;
    if (uCamMode == 1) {
        // ~2.5x macro close-up of glowing crater rim, hero mud clods, and under-lit dust eddies
        ro = vec3(-0.32, 0.88, 2.88);
        ta = vec3(0.08, 0.56, 0.02);
        fl = 1.52;
    } else {
        // Hero framing matching photoreal reference
        ro = vec3(0.0, 1.22, 5.25);
        ta = vec3(0.0, 1.86, 0.0);
        fl = 1.02;
    }

    // Subtle handheld camera shock tremor
    float shakeAmp = (uCamMode == 1) ? 0.008 : 0.012;
    ro.x += sin(uTime * 23.0) * shakeAmp * 0.5;
    ro.y += cos(uTime * 29.0) * shakeAmp * 0.5;

    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 + fl * cw);

    LightRig rig = getLightRig();

    // 1. Raymarch matte blasted terrain & 16 ballistic fractured mud/rock clods
    float t = 0.05;
    float tMax = 24.0;
    float hitMat = -1.0;
    for (int i = 0; i < 96; i++) {
        vec3 p = ro + rd * t;
        vec2 h = mapScene(p);
        if (h.x < 0.0020 * (1.0 + 0.15 * t)) {
            hitMat = h.y;
            break;
        }
        t += h.x;
        if (t > tMax) break;
    }

    vec3 bgCol = evalBackdrop(rd, rig);
    vec3 solidCol = bgCol;
    float tSolid = tMax;

    if (hitMat >= 0.0) {
        tSolid = t;
        vec3 p = ro + rd * t;
        vec3 n = calcNormal(p);
        solidCol = shadeSolid(p, n, -rd, hitMat, rig);
    }

    // 2. Volumetric Beer-Lambert dirt-and-dust geyser plume + airborne grit spray
    vec3 volLight = vec3(0.0);
    float volTrans = 1.0;
    float jitter = ign(gl_FragCoord.xy + fract(uTime * 13.7) * 64.0);
    marchPlume(ro, rd, tSolid, jitter, rig, volLight, volTrans);

    vec3 col = solidCol * volTrans + volLight;

    // 3. Razor-sharp tapered glowing hot shrapnel streaks
    vec3 streaks = evalShrapnel(ro, rd, tSolid, rig.flashMult);
    col += streaks * mix(0.28, 1.0, volTrans);

    // 4. Tight atmospheric bloom halo around white-hot crater core
    if (rig.flashMult > 0.05) {
        vec3 toCore = normalize(rig.craterPos - ro);
        float coreAlign = max(dot(rd, toCore), 0.0);
        float halo = pow(coreAlign, 12.0) * 0.22 * rig.flashMult;
        col += vec3(1.0, 0.48, 0.12) * halo;
    }

    // 5. ACES filmic tone mapping & sRGB gamma
    col = acesToneMap(col * 1.12);
    col = pow(max(col, vec3(0.0)), vec3(1.0 / 2.2));

    // Subtle vignette
    vec2 qv = gl_FragCoord.xy / uResolution;
    float vig = 0.84 + 0.16 * pow(16.0 * qv.x * qv.y * (1.0 - qv.x) * (1.0 - qv.y), 0.18);
    col *= vig;

    // Gentle floor lift so night-slate shadows never crush to pure black (lumMin ~6-10)
    col = max(col, vec3(0.025));

    if (uLightMode == 1) {
        // Strict pure neutral grayscale study (R == G == B)
        float lum = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = vec3(lum);
    }

    fragColor = vec4(col, 1.0);
}
