{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "edm-crater-field",
  "title": "EDM Crater Field",
  "description": "A full-bleed metal plate eroded by electrical discharge machining: sparks continuously pit the surface with small raised-rim craters that fade back to base as later discharges erode the recast layer, holding the plate at a steady simmer of pockmarks rather than ever saturating.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/loud/edm-crater-field/component.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useId, useRef } from \"react\";\n\n// ---------------------------------------------------------------------------\n// EdmCraterField — a full-bleed metal-surface hero eroded by electrical\n// discharge machining: repeated sparks between an electrode and the\n// workpiece vaporize material, each discharge leaving a small crater with a\n// raised recast rim. Under continuous machining later discharges erode and\n// flush away older recast material, so a real EDM surface reaches a\n// statistical steady state — birth rate balanced by removal — rather than\n// filling in solid. That steady state is the whole point of the component:\n// it is never allowed to accumulate toward a saturated frame the way a\n// literal \"craters pile up\" reading would.\n//\n// IMPLEMENTATION: unlike weld-pool's per-pixel analytic height field, a\n// crater field is stamped discretely — a spark either happened somewhere or\n// it didn't — so the height field lives in a small CPU-side buffer (a\n// LUMINANCE texture, one erosion \"cell\" of resolution derived from the\n// container's SMALLER dimension) rather than being evaluated in the\n// fragment shader. Each discharge additively stamps a crater shape (a\n// recessed bowl plus a raised outer rim) into that buffer; every real frame\n// the whole buffer is multiplied toward zero by an exponential decay factor\n// (birth rate is constant, decay is constant, so the resident population is\n// a steady simmer, never a monotonic fill). The fragment shader only has to\n// sample that texture, central-difference it for a surface normal, and light\n// it — the same normal-from-heightfield + achromatic multi-band studio\n// approach as weld-pool, simplified to fewer light sources since a pocked\n// surface needs less environment structure to read as metal than a mirror\n// pool does.\n//\n// Colours: five stops derived from --background, --foreground, --ns-muted\n// and --border (getComputedStyle at mount, re-read on a MutationObserver\n// watching documentElement's class) — no literals anywhere, including this\n// comment's numbers are unitless ramp positions, not colours. --ns-accent is\n// never touched: there is no interactive climactic moment here (a pointer\n// only shifts *where* sparks land, never their colour), and that is a\n// deliberate reading of the showpiece recipe's standing defect — the exact\n// bug edge-yield/granule-churn/shear-billow shipped.\n// ---------------------------------------------------------------------------\n\nexport interface EdmCraterFieldProps {\n  /** Freezes the surface on a composed steady-state frame without unmounting. */\n  paused?: boolean;\n  /** Rendered in the DOM over the field — eyebrow, headline, CTA. */\n  children?: React.ReactNode;\n  className?: string;\n  style?: React.CSSProperties;\n}\n\nconst VERT_SRC = `\nattribute vec2 a_pos;\nvoid main() { gl_Position = vec4(a_pos, 0.0, 1.0); }\n`;\n\nconst FRAG_SRC = `\nprecision highp float;\n\nuniform vec2 u_size;      // css px\nuniform float u_dpr;\nuniform sampler2D u_height;\nuniform vec2 u_texRes;    // erosion buffer size in texels\nuniform float u_relief;\nuniform float u_time;\nuniform vec3 u_c0;\nuniform vec3 u_c1;\nuniform vec3 u_c2;\nuniform vec3 u_c3;\nuniform vec3 u_c4;\nuniform float u_bias;\nuniform float u_contrast;\n\n// texture stores signed height packed 0..1 -> -1..1\nfloat sampleH(vec2 uv) {\n  return texture2D(u_height, uv).r * 2.0 - 1.0;\n}\n\nfloat strip(float el, float at, float width) {\n  float d = (el - at) / width;\n  return exp(-d * d);\n}\n\n// A three-source achromatic studio. Fewer bands than a mirror pool needs —\n// a pocked, mostly-flat plate only has to cross one or two reflection bands\n// per crater rim to read as machined metal rather than paper.\nfloat env(vec3 r) {\n  float el = r.y;\n  float az = atan(r.x, r.z);\n  float L = 0.40;\n  L += 0.22 * smoothstep(0.05, 0.62, el);\n  L -= 0.20 * smoothstep(0.0, -0.55, el);\n  L += 0.30 * strip(el, 0.12, 0.05);\n  L += 0.16 * strip(el, 0.44, 0.08);\n  L += 0.10 * exp(-pow(sin(az * 1.0 + u_time * 0.045) / 0.42, 2.0));\n  return L;\n}\n\nvec3 ramp(float x) {\n  vec3 c = mix(u_c0, u_c1, smoothstep(0.0, 0.30, x));\n  c = mix(c, u_c2, smoothstep(0.28, 0.58, x));\n  c = mix(c, u_c3, smoothstep(0.55, 0.85, x));\n  c = mix(c, u_c4, smoothstep(0.82, 1.0, x));\n  return c;\n}\n\nvoid main() {\n  vec2 p = vec2(gl_FragCoord.x, u_size.y * u_dpr - gl_FragCoord.y) / u_dpr;\n  vec2 uv = p / u_size;\n\n  vec2 texel = 1.0 / u_texRes;\n  float h0 = sampleH(uv);\n  float hx = sampleH(uv + vec2(texel.x, 0.0));\n  float hy = sampleH(uv + vec2(0.0, texel.y));\n\n  vec3 n = normalize(vec3(-(hx - h0) * u_relief, (hy - h0) * u_relief, 1.0));\n  vec2 vp = (p - u_size * 0.5) / min(u_size.x, u_size.y);\n  vec3 v = normalize(vec3(vp.x * 0.5, -vp.y * 0.5, 1.0));\n  vec3 r = reflect(-v, n);\n\n  float L = env(r);\n\n  vec3 l1 = normalize(vec3(-0.30, 0.72, 0.58));\n  float s1 = pow(max(dot(r, l1), 0.0), 130.0);\n  L += s1 * 0.85;\n\n  float fres = pow(1.0 - max(dot(n, v), 0.0), 5.0);\n  L += fres * 0.12;\n\n  float Lc = clamp((L - 0.5) * u_contrast + 0.5 + u_bias, 0.0, 1.0);\n  vec3 col = ramp(Lc);\n  gl_FragColor = vec4(col, 1.0);\n}\n`;\n\ntype RGB = [number, number, number];\n\nfunction parseHex(raw: string): RGB | null {\n  const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(raw.trim());\n  if (!m) return null;\n  let h = m[1];\n  if (h.length === 3) h = h.split(\"\").map((c) => c + c).join(\"\");\n  const n = parseInt(h, 16);\n  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];\n}\n\nfunction mixRGB(a: RGB, b: RGB, t: number): RGB {\n  return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];\n}\n\nfunction luminance([r, g, b]: RGB): number {\n  return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\nfunction compile(gl: WebGLRenderingContext, type: number, src: string): WebGLShader {\n  const s = gl.createShader(type)!;\n  gl.shaderSource(s, src);\n  gl.compileShader(s);\n  if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {\n    const info = gl.getShaderInfoLog(s);\n    gl.deleteShader(s);\n    throw new Error(`edm-crater-field: shader compile failed: ${info ?? \"\"}`);\n  }\n  return s;\n}\n\n// Minimal full-bleed fragment-shader host, mirroring weld-pool's GLSurface:\n// one program, one fullscreen triangle pair, lazily-resolved uniform\n// locations.\nclass GLSurface {\n  gl: WebGLRenderingContext | null = null;\n  private program: WebGLProgram | null = null;\n  private vs: WebGLShader | null = null;\n  private fs: WebGLShader | null = null;\n  private buffer: WebGLBuffer | null = null;\n  private locs = new Map<string, WebGLUniformLocation | null>();\n\n  constructor(private canvas: HTMLCanvasElement, private frag: string) {}\n\n  init(isRestore = false): boolean {\n    const gl = this.canvas.getContext(\"webgl\", {\n      alpha: false,\n      antialias: false,\n      premultipliedAlpha: false,\n      powerPreference: \"high-performance\",\n    }) as WebGLRenderingContext | null;\n    if (!gl) return false;\n    this.gl = gl;\n    try {\n      this.vs = compile(gl, gl.VERTEX_SHADER, VERT_SRC);\n      this.fs = compile(gl, gl.FRAGMENT_SHADER, this.frag);\n      const program = gl.createProgram();\n      if (!program) {\n        this.abandon(isRestore);\n        return false;\n      }\n      this.program = program;\n      gl.attachShader(program, this.vs);\n      gl.attachShader(program, this.fs);\n      gl.linkProgram(program);\n      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n        this.abandon(isRestore);\n        return false;\n      }\n    } catch {\n      this.abandon(isRestore);\n      return false;\n    }\n    gl.useProgram(this.program);\n    this.buffer = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);\n    gl.bufferData(\n      gl.ARRAY_BUFFER,\n      new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),\n      gl.STATIC_DRAW\n    );\n    const loc = gl.getAttribLocation(this.program!, \"a_pos\");\n    gl.enableVertexAttribArray(loc);\n    gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);\n    this.locs.clear();\n    return true;\n  }\n\n  // A compile/link failure above happens on a context getContext() already\n  // handed over, and the caller's `if (!surface.init()) return` never\n  // registers the effect cleanup that hands a context back — so the release\n  // belongs here, while this.gl still reaches it. The condition is the\n  // inverse of that cleanup's `!canvas.isConnected`: the canvas is still\n  // mounted on this path, and the context that must NOT be released is one\n  // the browser has just restored, since onRestored re-enters init() and a\n  // release there would feed its own loss/restore/fail cycle.\n  private abandon(isRestore: boolean) {\n    const lose = isRestore ? null : this.gl?.getExtension(\"WEBGL_lose_context\");\n    this.destroy();\n    lose?.loseContext();\n  }\n\n  private loc(name: string): WebGLUniformLocation | null {\n    if (!this.locs.has(name)) {\n      this.locs.set(name, this.gl!.getUniformLocation(this.program!, name));\n    }\n    return this.locs.get(name) ?? null;\n  }\n\n  f(name: string, x: number) {\n    this.gl?.uniform1f(this.loc(name), x);\n  }\n  i(name: string, x: number) {\n    this.gl?.uniform1i(this.loc(name), x);\n  }\n  v2(name: string, x: number, y: number) {\n    this.gl?.uniform2f(this.loc(name), x, y);\n  }\n  v3(name: string, c: RGB) {\n    this.gl?.uniform3f(this.loc(name), c[0], c[1], c[2]);\n  }\n\n  draw(pixelW: number, pixelH: number) {\n    const gl = this.gl;\n    if (!gl || !this.program) return;\n    gl.viewport(0, 0, pixelW, pixelH);\n    gl.drawArrays(gl.TRIANGLES, 0, 6);\n  }\n\n  destroy() {\n    const gl = this.gl;\n    if (!gl) return;\n    if (this.buffer) gl.deleteBuffer(this.buffer);\n    if (this.program) gl.deleteProgram(this.program);\n    if (this.vs) gl.deleteShader(this.vs);\n    if (this.fs) gl.deleteShader(this.fs);\n    this.buffer = null;\n    this.program = null;\n    this.vs = null;\n    this.fs = null;\n    this.locs.clear();\n    this.gl = null;\n  }\n}\n\n// Deterministic small PRNG so the reduced-motion freeze frame (and the warm\n// seed every mount starts from) is reproducible rather than one-shot noise.\nfunction mulberry32(seed: number) {\n  let a = seed >>> 0;\n  return () => {\n    a |= 0;\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Real numbers (from docs/specs/r9/edm-crater-field.md):\n//  - discharge (birth) rate: 14/s, uniform-random position\n//  - crater radius: 0.9%-2.2% of the smaller container dimension\n//  - crater lifetime: 5.5s birth-to-fully-faded — modeled as exponential\n//    decay with a time constant of lifetime/3 (~95% faded by three time\n//    constants, which is the \"fully faded\" read)\n//  - steady-state resident population target: 14/s * 5.5s ~= 77 craters\n//  - rim: raised band at 1.15x the crater's own depth across the outer 15%\n//    of its radius\n// ---------------------------------------------------------------------------\nconst BIRTH_RATE = 14; // craters/s, baseline uniform-random\nconst LOCAL_BOOST_RATE = 28; // additional craters/s inside the pointer radius (3x local)\nconst CRATER_LIFETIME = 5.5;\nconst DECAY_TAU = CRATER_LIFETIME / 3;\nconst RADIUS_MIN_PCT = 0.009;\nconst RADIUS_MAX_PCT = 0.022;\nconst RIM_FRACTION = 0.15;\nconst RIM_HEIGHT_MULT = 1.15;\nconst DEPTH = 0.34; // normalized bowl depth, buffer is clamped to [-1, 1]\nconst TEX_TEXELS_PER_MIN_DIM = 220; // erosion buffer resolution across the smaller dimension\nconst POINTER_RADIUS_CSS = 150;\nconst POINTER_BOOST_DECAY_MS = 600;\nconst WARMUP_SECONDS = 10; // ~5.5x the decay time constant — reaches steady state before first paint\nconst WARMUP_STEP = 0.2;\n// A fixed seed so the reduced-motion / paused frame is the same composed\n// steady-state field every time, not whatever the live RNG happened to draw.\nconst STATIC_SEED = 20260827;\n\nexport function EdmCraterField({\n  paused = false,\n  children,\n  className = \"\",\n  style,\n}: EdmCraterFieldProps) {\n  const wrapRef = useRef<HTMLDivElement | null>(null);\n  const canvasRef = useRef<HTMLCanvasElement | null>(null);\n  const uid = useId();\n  const pausedRef = useRef(paused);\n  pausedRef.current = paused;\n\n  useEffect(() => {\n    const wrap = wrapRef.current;\n    const canvas = canvasRef.current;\n    if (!wrap || !canvas) return;\n\n    const surface = new GLSurface(canvas, FRAG_SRC);\n    let raf = 0;\n    let running = false;\n    let staticMode = false;\n    let cssW = 0;\n    let cssH = 0;\n    let dpr = 1;\n    let disposed = false;\n    let lastMs = performance.now();\n\n    // erosion buffer: JS-side signed-height field, decayed and stamped on\n    // the CPU, uploaded as a LUMINANCE texture every real frame.\n    let texW = 0;\n    let texH = 0;\n    let heightBuf: Float32Array = new Float32Array(0);\n    let uploadBuf: Uint8Array = new Uint8Array(0);\n    let heightTex: WebGLTexture | null = null;\n\n    let rng = mulberry32(Date.now() & 0xffffffff);\n    let spawnAcc = 0;\n    let localSpawnAcc = 0;\n\n    let hoverX = 0;\n    let hoverY = 0;\n    let boostAmt = 0; // eased 0..1\n    let boostTarget = 0;\n\n    // Simple two-tier adaptive DPR scale: the fragment cost here is a single\n    // texture sample plus a handful of exp()/pow() calls per pixel, far\n    // cheaper than weld-pool's warped fbm, so one step down is plenty of\n    // insurance rather than a full ladder.\n    const SCALES = [1, 0.7];\n    const BUDGET_OVER = 24;\n    let scaleIdx = 0;\n    let frameEma = 16.7;\n    let overMs = 0;\n    let underMs = 0;\n    let upWindow = 8000;\n\n    let simTime = 0;\n\n    let c0: RGB = [0.03, 0.03, 0.03];\n    let c1: RGB = [0.18, 0.18, 0.18];\n    let c2: RGB = [0.56, 0.56, 0.56];\n    let c3: RGB = [0.93, 0.93, 0.93];\n    let c4: RGB = [1, 1, 1];\n    let bias = 0;\n    let contrast = 1.15;\n\n    const readColors = () => {\n      const cs = getComputedStyle(document.documentElement);\n      const bg = parseHex(cs.getPropertyValue(\"--background\")) ?? [1, 1, 1];\n      const fg = parseHex(cs.getPropertyValue(\"--foreground\")) ?? [0.09, 0.09, 0.09];\n      const muted = parseHex(cs.getPropertyValue(\"--ns-muted\")) ?? [0.55, 0.55, 0.55];\n      const border = parseHex(cs.getPropertyValue(\"--border\")) ?? [0.18, 0.18, 0.18];\n      const black: RGB = [0, 0, 0];\n      const white: RGB = [1, 1, 1];\n      if (luminance(bg) < 0.5) {\n        c0 = mixRGB(bg, black, 0.5);\n        c1 = mixRGB(border, bg, 0.15);\n        c2 = muted;\n        c3 = fg;\n        c4 = mixRGB(fg, white, 0.82);\n        bias = -0.08;\n        contrast = 1.18;\n      } else {\n        c0 = mixRGB(fg, black, 0.32);\n        c1 = mixRGB(fg, muted, 0.55);\n        c2 = mixRGB(muted, bg, 0.6);\n        c3 = mixRGB(bg, muted, 0.16);\n        c4 = bg;\n        bias = 0.02;\n        contrast = 1.22;\n      }\n    };\n    readColors();\n\n    // ---- erosion buffer -------------------------------------------------\n    const allocBuffer = () => {\n      const minDim = Math.max(1, Math.min(cssW, cssH));\n      const pxPerTexel = minDim / TEX_TEXELS_PER_MIN_DIM;\n      texW = Math.max(24, Math.round(cssW / pxPerTexel));\n      texH = Math.max(24, Math.round(cssH / pxPerTexel));\n      // a resize allocates a fresh buffer rather than resampling the old one:\n      // a real resize is rare relative to the 5.5s crater lifetime, and the\n      // caller always re-seeds to steady state right after allocating (see\n      // `resize`), so there is never a visible empty-surface frame.\n      heightBuf = new Float32Array(texW * texH);\n      uploadBuf = new Uint8Array(texW * texH);\n    };\n\n    const stampCrater = (cx: number, cy: number, radiusCss: number, pxPerTexel: number) => {\n      const rTex = radiusCss / pxPerTexel;\n      const cxTex = cx / pxPerTexel;\n      const cyTex = cy / pxPerTexel;\n      const rOuter = Math.ceil(rTex) + 1;\n      const x0 = Math.max(0, Math.floor(cxTex - rOuter));\n      const x1 = Math.min(texW - 1, Math.ceil(cxTex + rOuter));\n      const y0 = Math.max(0, Math.floor(cyTex - rOuter));\n      const y1 = Math.min(texH - 1, Math.ceil(cyTex + rOuter));\n      for (let y = y0; y <= y1; y++) {\n        const row = y * texW;\n        for (let x = x0; x <= x1; x++) {\n          const dx = x - cxTex;\n          const dy = y - cyTex;\n          const d = Math.sqrt(dx * dx + dy * dy) / rTex;\n          if (d > 1.0) continue;\n          let h: number;\n          if (d < 1.0 - RIM_FRACTION) {\n            // recessed bowl, smooth toward the floor at the centre\n            const t = d / (1.0 - RIM_FRACTION);\n            h = -DEPTH * (1.0 - t * t);\n          } else {\n            // raised recast rim, peaking mid-band then falling to 0 at d=1\n            const t = (d - (1.0 - RIM_FRACTION)) / RIM_FRACTION; // 0..1\n            h = DEPTH * RIM_HEIGHT_MULT * Math.sin(Math.min(1, t) * Math.PI);\n          }\n          heightBuf[row + x] += h;\n        }\n      }\n    };\n\n    // Advance the erosion buffer by dt: decay everything toward zero, then\n    // stamp however many new discharges dt's worth of the birth rate (plus\n    // any local pointer boost) earns. Called both by the live per-frame loop\n    // (small dt) and by the mount/reduced-motion warm-up (larger dt chunks)\n    // so a component never opens on an empty, freshly-machined-looking\n    // surface.\n    const simulate = (dt: number, r: () => number) => {\n      if (dt <= 0 || texW === 0) return;\n      const decay = Math.exp(-dt / DECAY_TAU);\n      for (let i = 0; i < heightBuf.length; i++) heightBuf[i] *= decay;\n\n      const minDim = Math.max(1, Math.min(cssW, cssH));\n      const pxPerTexel = minDim / TEX_TEXELS_PER_MIN_DIM;\n\n      spawnAcc += BIRTH_RATE * dt;\n      let n = Math.floor(spawnAcc);\n      spawnAcc -= n;\n      while (n-- > 0) {\n        const cx = r() * cssW;\n        const cy = r() * cssH;\n        const radius = (RADIUS_MIN_PCT + r() * (RADIUS_MAX_PCT - RADIUS_MIN_PCT)) * minDim;\n        stampCrater(cx, cy, radius, pxPerTexel);\n      }\n\n      if (boostAmt > 0.01) {\n        localSpawnAcc += LOCAL_BOOST_RATE * boostAmt * dt;\n        let ln = Math.floor(localSpawnAcc);\n        localSpawnAcc -= ln;\n        while (ln-- > 0) {\n          const ang = r() * Math.PI * 2;\n          const rad = Math.sqrt(r()) * POINTER_RADIUS_CSS;\n          const cx = hoverX + Math.cos(ang) * rad;\n          const cy = hoverY + Math.sin(ang) * rad;\n          const radius = (RADIUS_MIN_PCT + r() * (RADIUS_MAX_PCT - RADIUS_MIN_PCT)) * minDim;\n          stampCrater(cx, cy, radius, pxPerTexel);\n        }\n      }\n    };\n\n    const uploadTexture = () => {\n      const gl = surface.gl;\n      if (!gl || texW === 0) return;\n      for (let i = 0; i < heightBuf.length; i++) {\n        const v = Math.max(-1, Math.min(1, heightBuf[i]));\n        uploadBuf[i] = Math.round((v * 0.5 + 0.5) * 255);\n      }\n      if (!heightTex) {\n        heightTex = gl.createTexture();\n        gl.bindTexture(gl.TEXTURE_2D, heightTex);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n      } else {\n        gl.bindTexture(gl.TEXTURE_2D, heightTex);\n      }\n      gl.texImage2D(\n        gl.TEXTURE_2D,\n        0,\n        gl.LUMINANCE,\n        texW,\n        texH,\n        0,\n        gl.LUMINANCE,\n        gl.UNSIGNED_BYTE,\n        uploadBuf\n      );\n      gl.activeTexture(gl.TEXTURE0);\n      gl.bindTexture(gl.TEXTURE_2D, heightTex);\n    };\n\n    const draw = () => {\n      if (!surface.gl || cssW <= 0 || cssH <= 0) return;\n      uploadTexture();\n      surface.v2(\"u_size\", cssW, cssH);\n      surface.f(\"u_dpr\", dpr);\n      surface.v2(\"u_texRes\", texW, texH);\n      surface.f(\"u_relief\", 6.5);\n      surface.f(\"u_time\", simTime);\n      surface.i(\"u_height\", 0);\n      surface.v3(\"u_c0\", c0);\n      surface.v3(\"u_c1\", c1);\n      surface.v3(\"u_c2\", c2);\n      surface.v3(\"u_c3\", c3);\n      surface.v3(\"u_c4\", c4);\n      surface.f(\"u_bias\", bias);\n      surface.f(\"u_contrast\", contrast);\n      surface.draw(canvas.width, canvas.height);\n    };\n\n    const loop = (nowMs: number) => {\n      const rawMs = nowMs - lastMs;\n      const dt = Math.min(0.05, Math.max(0, rawMs / 1000));\n      lastMs = nowMs;\n      simTime += dt;\n\n      // per-frame exponential ease toward the target — driven by dt, not by\n      // elapsed-since-last-pointer-event, so continuous movement (which\n      // fires pointermove far more often than once per frame) still ramps\n      // boostAmt up instead of re-arming a \"just changed\" timer every event.\n      boostAmt += (boostTarget - boostAmt) * (1 - Math.exp(-dt / (POINTER_BOOST_DECAY_MS / 1000)));\n\n      simulate(dt, rng);\n      draw();\n\n      const clamped = Math.min(50, rawMs);\n      frameEma += (clamped - frameEma) * (1 - Math.exp(-clamped / 120));\n      if (frameEma > BUDGET_OVER) {\n        overMs += clamped;\n        underMs = 0;\n      } else {\n        underMs += clamped;\n        overMs = 0;\n      }\n      const down = overMs > 900 && scaleIdx < SCALES.length - 1;\n      const up = underMs > upWindow && scaleIdx > 0;\n      if (down || up) {\n        scaleIdx += down ? 1 : -1;\n        if (down) upWindow = Math.min(64000, upWindow * 2);\n        overMs = 0;\n        underMs = 0;\n        frameEma = 16.7;\n        applyBacking();\n      }\n      raf = requestAnimationFrame(loop);\n    };\n    const wake = () => {\n      if (running || disposed) return;\n      running = true;\n      lastMs = performance.now();\n      raf = requestAnimationFrame(loop);\n    };\n    const sleep = () => {\n      cancelAnimationFrame(raf);\n      running = false;\n    };\n\n    // DPR capped at 1.5, matching weld-pool's full-bleed-area-dominates\n    // rationale, applied here even though the per-pixel cost is lighter.\n    const applyBacking = () => {\n      if (cssW < 2 || cssH < 2) return;\n      dpr = Math.min(window.devicePixelRatio || 1, 1.5) * SCALES[scaleIdx];\n      const pw = Math.round(cssW * dpr);\n      const ph = Math.round(cssH * dpr);\n      if (canvas.width !== pw || canvas.height !== ph) {\n        canvas.width = pw;\n        canvas.height = ph;\n      }\n      canvas.style.width = `${cssW}px`;\n      canvas.style.height = `${cssH}px`;\n      draw();\n    };\n\n    const warmup = (seed: number, seconds: number) => {\n      const r = mulberry32(seed);\n      spawnAcc = 0;\n      localSpawnAcc = 0;\n      heightBuf.fill(0);\n      let remaining = seconds;\n      while (remaining > 0) {\n        const step = Math.min(WARMUP_STEP, remaining);\n        simulate(step, r);\n        remaining -= step;\n      }\n    };\n\n    const resize = () => {\n      const rect = wrap.getBoundingClientRect();\n      if (rect.width < 2 || rect.height < 2) return;\n      cssW = rect.width;\n      cssH = rect.height;\n      scaleIdx = 0;\n      overMs = 0;\n      underMs = 0;\n      upWindow = 8000;\n      frameEma = 16.7;\n      allocBuffer();\n      // a resize is a new grid, so re-seed to steady state on it too rather\n      // than momentarily showing an empty freshly-resized surface\n      if (staticMode) warmup(STATIC_SEED, WARMUP_SECONDS);\n      else warmup(Date.now() & 0xffffffff, WARMUP_SECONDS);\n      applyBacking();\n      draw();\n    };\n\n    let rectLeft = 0;\n    let rectTop = 0;\n    let rectDirty = true;\n    const syncRect = () => {\n      if (!rectDirty) return;\n      const rect = wrap.getBoundingClientRect();\n      rectLeft = rect.left;\n      rectTop = rect.top;\n      rectDirty = false;\n    };\n    const markRectDirty = () => {\n      rectDirty = true;\n    };\n\n    const onPointerMove = (e: PointerEvent) => {\n      syncRect();\n      hoverX = e.clientX - rectLeft;\n      hoverY = e.clientY - rectTop;\n      boostTarget = 1;\n      if (staticMode) draw();\n    };\n    const onPointerLeave = () => {\n      boostTarget = 0;\n    };\n\n    if (!surface.init()) return; // no WebGL: children still render over the page bg\n    const ro = new ResizeObserver(resize);\n    ro.observe(wrap);\n    resize();\n\n    wrap.addEventListener(\"pointermove\", onPointerMove);\n    wrap.addEventListener(\"pointerleave\", onPointerLeave);\n    window.addEventListener(\"scroll\", markRectDirty, { passive: true, capture: true });\n    window.addEventListener(\"resize\", markRectDirty, { passive: true });\n\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    let reduced = mq.matches;\n    const applyMode = () => {\n      if (reduced || pausedRef.current) {\n        staticMode = true;\n        sleep();\n        simTime = 0;\n        warmup(STATIC_SEED, WARMUP_SECONDS);\n        draw();\n      } else {\n        staticMode = false;\n        warmup(Date.now() & 0xffffffff, WARMUP_SECONDS);\n        wake();\n      }\n    };\n    const onMq = () => {\n      reduced = mq.matches;\n      applyMode();\n    };\n    mq.addEventListener(\"change\", onMq);\n\n    let onScreen = true;\n    const io = new IntersectionObserver(\n      (entries) => {\n        onScreen = entries.some((en) => en.isIntersecting);\n        if (!onScreen) sleep();\n        else if (!staticMode && !document.hidden) wake();\n      },\n      { threshold: 0 }\n    );\n    io.observe(wrap);\n\n    const onVis = () => {\n      if (document.hidden) sleep();\n      else if (!staticMode && onScreen) wake();\n    };\n    document.addEventListener(\"visibilitychange\", onVis);\n    applyMode();\n\n    let lastPolledPaused = pausedRef.current;\n    let poll = 0;\n    const tick = () => {\n      if (pausedRef.current !== lastPolledPaused) {\n        lastPolledPaused = pausedRef.current;\n        applyMode();\n      }\n      poll = window.setTimeout(tick, 140);\n    };\n    tick();\n\n    const themeObserver = new MutationObserver(() => {\n      readColors();\n      if (staticMode) draw();\n    });\n    themeObserver.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"class\"],\n    });\n\n    const onLost = (e: Event) => {\n      e.preventDefault();\n      sleep();\n    };\n    const onRestored = () => {\n      heightTex = null;\n      if (surface.init(true)) {\n        resize();\n        applyMode();\n      }\n    };\n    canvas.addEventListener(\"webglcontextlost\", onLost);\n    canvas.addEventListener(\"webglcontextrestored\", onRestored);\n\n    return () => {\n      disposed = true;\n      ro.disconnect();\n      io.disconnect();\n      mq.removeEventListener(\"change\", onMq);\n      document.removeEventListener(\"visibilitychange\", onVis);\n      themeObserver.disconnect();\n      canvas.removeEventListener(\"webglcontextlost\", onLost);\n      canvas.removeEventListener(\"webglcontextrestored\", onRestored);\n      wrap.removeEventListener(\"pointermove\", onPointerMove);\n      wrap.removeEventListener(\"pointerleave\", onPointerLeave);\n      window.removeEventListener(\"scroll\", markRectDirty, { capture: true } as EventListenerOptions);\n      window.removeEventListener(\"resize\", markRectDirty);\n      window.clearTimeout(poll);\n      sleep();\n      if (heightTex && surface.gl) surface.gl.deleteTexture(heightTex);\n      heightTex = null;\n      // destroy() frees the GL objects but not the context holding them, and a\n      // detached canvas keeps its context until GC gets round to it —\n      // browsers cap live contexts per renderer process and evict the oldest\n      // first, which kills fields still on screen. Hand it back explicitly,\n      // but only on a real unmount: this cleanup also runs when a dep changes,\n      // and a canvas returns its one lost context to every later getContext(),\n      // so releasing too eagerly would blank the rebuilt field.\n      const lose = surface.gl?.getExtension(\"WEBGL_lose_context\");\n      surface.destroy();\n      if (!canvas.isConnected) lose?.loseContext();\n    };\n  }, []);\n\n  return (\n    <div\n      ref={wrapRef}\n      data-edm-crater-field={uid}\n      className={`relative isolate h-full w-full touch-none overflow-hidden bg-background ${className}`}\n      style={style}\n    >\n      <canvas ref={canvasRef} aria-hidden=\"true\" className=\"absolute inset-0 block h-full w-full\" />\n      {children ? <div className=\"relative z-[1] h-full w-full\">{children}</div> : null}\n    </div>\n  );\n}\n\nEdmCraterField.displayName = \"EdmCraterField\";\n",
      "type": "registry:ui",
      "target": "components/ui/edm-crater-field.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff"
    },
    "dark": {
      "ns-muted": "#8f8f8f"
    }
  },
  "meta": {
    "collection": "loud",
    "tags": [
      "background",
      "hero",
      "canvas",
      "webgl",
      "shader",
      "metal",
      "erosion",
      "cursor",
      "decorative"
    ],
    "instruction": "Build <EdmCraterField paused? children? className? style?> as a full-bleed WebGL1 hero whose surface is a small CPU-side signed-height erosion buffer (a Float32Array sized off the container's SMALLER dimension at TEX_TEXELS_PER_MIN_DIM=220 texels across that dimension, so texels are uniform px in both axes regardless of aspect), decayed and stamped on the CPU every real frame, uploaded as a single-channel gl.LUMINANCE texture (0..255 packing signed height -1..1 via v*0.5+0.5), and read back in the fragment shader for a normal-from-heightfield + achromatic environment lighting pass — the same technique family as registry/loud/weld-pool/component.tsx's height field, simplified to a 3-source studio (env()) since a mostly-flat pitted plate needs less environment structure than a mirror pool to read as metal. REAL NUMBERS (from docs/specs/r9/edm-crater-field.md): discharge (birth) rate 14 craters/s uniform-random position; crater radius 0.9%-2.2% of the smaller container dimension per discharge; crater lifetime 5.5s birth-to-fully-faded, modeled as exponential decay of the WHOLE buffer each frame by exp(-dt/DECAY_TAU) with DECAY_TAU = 5.5/3 (~95% faded after three time constants); steady-state resident population target 14/s * 5.5s ~= 77 craters, which falls out of birth-rate=decay-rate rather than being enforced as a cap. STAMP SHAPE: each discharge additively stamps into the buffer — a recessed bowl (h = -DEPTH*(1-t^2), t = d/(1-RIM_FRACTION), for the inner 85% of the radius) plus a raised recast rim across the outer RIM_FRACTION=0.15 of the radius peaking at RIM_HEIGHT_MULT=1.15x the bowl depth via a half-sine profile — never a simple disc, the rim is what makes it read as EDM rather than a generic pit. STEADY STATE IS THE WHOLE POINT: this is the fix for the exact 'process that finishes and stops' Filter-2 failure the spec was written against — birth rate (14/s) and decay rate (buffer-wide exponential, constant regardless of occupancy) are BOTH constant and independent, so the field can never accumulate toward a saturated frame; it turns its population over continuously instead. WARM-UP: an erosion buffer has no honest t=0 (an empty plate reads as unloaded, not as freshly machined), so on every mount, every real resize, and every reduced-motion/paused transition, `warmup()` runs the exact same `simulate()` step function used by the live per-frame loop in fixed 0.2s chunks for WARMUP_SECONDS=10 (~5.5 decay time-constants, comfortably past steady state) BEFORE the first paint — this is the same pattern registry/loud/dye-whorl/component.tsx uses (its 150-260 fixed-step spin), scaled down because this sim is a decay+stamp buffer rather than a Navier-Stokes solver. The live (non-reduced) warm-up seeds from Date.now()-derived entropy (so different mounts show different compositions); the reduced-motion/paused warm-up seeds from a FIXED constant, STATIC_SEED=20260827, through the SAME mulberry32 PRNG and the SAME simulate() path, so the freeze frame is byte-reproducible rather than one-shot noise — named FREEZE_PHASE=steady-state-lock in the spec. POINTER: pointermove sets a target boost (boostTarget=1) that eases toward boostAmt every frame via a per-dt exponential (1 - exp(-dt/(POINTER_BOOST_DECAY_MS/1000)), POINTER_BOOST_DECAY_MS=600) rather than an elapsed-since-last-event timer, so continuous hovering (which fires pointermove far more often than once per rAF) still ramps the boost up instead of re-arming a 'just changed' clock every event; while boostAmt>0.01 an ADDITIONAL local stream of craters spawns at LOCAL_BOOST_RATE=28/s scaled by boostAmt, positioned by a uniform-disc sample (angle * sqrt(radial) so density is uniform, not centre-biased) within POINTER_RADIUS_CSS=150px of the pointer — reading as the electrode dwelling there, 3x the local density of the ambient 14/s field. pointerleave eases boostTarget back to 0 over the same curve. MUST NOT: tint craters or rims with --ns-accent (the exact standing defect registry/loud/edge-yield, granule-churn and shear-billow shipped, called out explicitly in docs/showpiece-recipe.md) — this component never reads --ns-accent at all, the pointer's only effect is WHERE sparks land, never their colour; there is no interactive control on this component, so accent has no legitimate use here either. TOKENS: five luminance stops (c0 darkest .. c4 lightest) derived from --background, --foreground, --ns-muted, --border via getComputedStyle(document.documentElement) at mount, re-read on a MutationObserver watching documentElement's class (redraw only when staticMode, since the live loop already redraws every frame) — NO PAINT BEFORE THE FIRST READ: readColors() runs synchronously before the first resize()/draw() call. Dark theme biases the ramp toward true black/white (bias=-0.08); light theme (checked first, per the recipe's 'light theme is the harder case') compresses toward --ns-muted/--background with a smaller positive bias so pit floors and rim highlights both stay inside the ramp without crossing into pure white/black or --border-adjacent values. RENDER HOST: an internal GLSurface class (mirroring weld-pool's) owns the WebGL1 context, one program, one fullscreen triangle pair, lazily-resolved uniform locations. DPR is capped at 1.5 (matches weld-pool's full-bleed-area-dominates rationale) with a simple two-tier adaptive scale (SCALES=[1,0.7]) that steps down only after ~900ms of a sustained over-budget (24ms) frame-time EMA and climbs back only after a much longer clean stretch that doubles per failure — lighter than weld-pool's three-tier ladder since this shader's per-pixel cost (one texture sample, a handful of exp()/pow() calls) is far cheaper than a warped fbm field. `ResizeObserver` reallocates the erosion buffer (a fresh Float32Array, not a resampled one — a resize is rare relative to the 5.5s crater lifetime) and re-runs warmup(); `IntersectionObserver` (threshold 0) and `visibilitychange` both pause the single rAF loop; `webglcontextlost`/`restored` rebuild the texture and context cleanly. The canvas is `aria-hidden` decoration with `w-full h-full`; children render over the field in a `relative z-[1]` layer and need a token scrim, since the field spans most of the value range and a crater can land under any line of type."
  },
  "type": "registry:ui"
}