← Commit history
Publish 0.3.0
45 files changed
+22766−143
README.md+51−37SKILL.md+29−11install.sh+2−2package.json+7−5page.json+7−7readme.html+55−28src/FIELD-ROUTER.md+194src/TILING-REVEAL.md+262src/checks/frames.mjs+217src/checks/timing.mjs+197src/circuit-animation-conductor.js+47−5src/circuit-animation-growth.js+347src/circuit-animation-handshake.js+20−5src/circuit-animation-reflection.js+604src/circuit-background-reveal.js+2779src/circuit-background-v6.js+461src/circuit-background-v7.js+1428src/circuit-background-v8.js+1506src/circuit-background-v9.js+1506src/circuit-field-hybrid-client-v8.js+422src/circuit-field-hybrid-client-v9.js+422src/circuit-field-hybrid-v8.js+232src/circuit-field-hybrid-v9.js+232src/circuit-field-hybrid-worker-v8.js+191src/circuit-field-hybrid-worker-v9.js+191src/circuit-field-stream-client.js+418src/circuit-field-stream-worker.js+185src/circuit-field-stream.js+775src/circuit-geometry-v9.js+1112src/circuit-obstacles-v9.js+405src/circuit-reveal-flow.js+391src/circuit-reveal-scroll.js+812src/circuit-reveal-stream-v8.js+1072src/circuit-reveal-stream.js+1042src/circuit-trace-stager-v8.js+132src/index-reveal.html+530src/index-v6.html+574src/index-v7.html+1053src/index-v8.html+1061src/index-v9.html+1138src/index.html+599−31src/playground.html+12−5src/serve-classic.mjs+8src/serve.sh+4−4src/server.js+34−3README.md+51−37@@ -25,21 +25,22 @@ backdrop. | Router | A\* nets between placed terminal formations | flow field and vortex trace packing | | Wrap | torus occupancy grid (no seam, no crossings) | reserved grid nodes (no crossings) | | Headless output | `generate-tile.mjs` writes an SVG tile | `generateCircuitField()` returns geometry |-| Motion | cursor-fed signal fountain | conductor **or** handshake system |-| Entry file | `circuit-background.js` | `circuit-background-v5.js` |-| Live demo | [traces-fuyou1ziuokn.adom.cloud](https://traces-fuyou1ziuokn.adom.cloud) | [circuit-y2uq81e4dp1d.adom.cloud](https://circuit-y2uq81e4dp1d.adom.cloud) |+| Motion | signal fountain or progressive reveal | three reveal modes and five ambient systems |+| Entry file | `circuit-background.js` or `circuit-background-reveal.js` | `circuit-background-v9.js` |+| Live demo | [classic tile](/adom/circuit-trace-generators/render/src/index-classic.html) and [tile reveal](/adom/circuit-trace-generators/render/src/index-reveal.html) | [v9 field](/adom/circuit-trace-generators/render/src/index.html) | Both ship `createCircuitBackground(mount, options)` returning `{ regenerate, exportSvg, destroy }`, both are seeded (the same seed and dimensions give identical geometry), and both honour `prefers-reduced-motion`. -**Both demos run live, hosted on this page.** These are the real `src/` engines,+**All three demos run live, hosted on this page.** These are the real `src/` engines, served by the wiki straight from this page's repo, so they need no container and will not go dark: -- ▶ **[Open the interactive playground](/adom/circuit-trace-generators/render/src/playground.html)** · both demos embedded as live boards on one page-- ▶ **[Launch the tiling-router demo](/adom/circuit-trace-generators/render/src/index-classic.html)** on its own-- ▶ **[Launch the field-router demo](/adom/circuit-trace-generators/render/src/index.html)** on its own+- **[Open the interactive playground](/adom/circuit-trace-generators/render/src/playground.html)** with all three demos on one page+- **[Launch the tiling-router demo](/adom/circuit-trace-generators/render/src/index-classic.html)** on its own+- **[Launch the tiling-reveal demo](/adom/circuit-trace-generators/render/src/index-reveal.html)** on its own+- **[Launch the field-router demo](/adom/circuit-trace-generators/render/src/index.html)** on its own --- @@ -122,13 +123,26 @@ const tile = generateCircuitTile({ seed: "traces", turnPenalty: 0.8 }); const svg = tileSvg(tile, { background: "#0d1117" }); ``` +### Progressive reveal++[Launch the tiling-reveal demo](/adom/circuit-trace-generators/render/src/index-reveal.html).++`circuit-background-reveal.js` grows the same tile geometry on a canvas above the+static SVG. It redraws only routes that are moving or cooling, then clears the+canvas after the glow reaches zero. The handoff reveals the exact SVG without a+brightness dip or color jump.++Reveal styles are **Etch**, **Flood**, **Sweep**, **Bloom**, and **Scatter**.++See [`src/TILING-REVEAL.md`](src/TILING-REVEAL.md) for the measured implementation notes.+ --- -## 2. Field router: `circuit-background-v5.js`+## 2. Field router: `circuit-background-v9.js` [](/adom/circuit-trace-generators/render/src/index.html) -▶ **[Launch the live field-router demo](/adom/circuit-trace-generators/render/src/index.html)** · switch geometry presets, ride the four animation systems, export the current SVG.+**[Launch the live field-router demo](/adom/circuit-trace-generators/render/src/index.html)** to switch geometry, obstacle, reveal, and ambient presets or export the current SVG. No tile. A deterministic planar trace-packing pass fills one continuous field at the mount's real dimensions with hundreds of independent routes. A rotatable@@ -137,8 +151,9 @@ runs, and gentle swirls, and *channel attraction* collects nearby routes into natural local buses. Every occupied grid node is reserved, so separate traces never cross. -`v5` is the animation shell over `v4`'s geometry. `v2` and `v3` are earlier-iterations, kept for reference.+Version 9 separates geometry, obstacles, reveal, and ambient motion. It can avoid+or outline embedded marks, reveal by time or scroll progress, and append seeded+world chunks without moving existing geometry. Versions 2 through 8 remain for reference. ### Tuning @@ -154,11 +169,13 @@ count, route-length distribution, stroke, via count, and orientation mix), **Dense**, **Diagonal sweep**, **Broad swirl**, **Sparse**. Geometry presets never touch motion settings; the two preset rows are independent. -### Animation systems+### Ambient systems -Four presets, in the demo's Animation row:+Five presets are available in the demo's Animation row: - **None** mounts only the static SVG and creates no animation layer at all.+- **Adom reflection** (`circuit-animation-reflection.js`) sends a restrained+ brand-color sheen across a precomposed trace mask. - **Conductor** (`circuit-animation-conductor.js`) is the full system: ambient currents, breathing endpoint nodes, core and halo packets, convoys, timed spatial waves, pointer wake, endpoint flashes.@@ -179,14 +196,19 @@ Four presets, in the demo's Animation row: ### API ```js-import { createCircuitBackground } from "./circuit-background-v5.js";+import { createCircuitBackground } from "./circuit-background-v9.js"; const circuit = createCircuitBackground(document.querySelector("#hero-circuit"), { seed: "product-launch", fill: 0.668, swirl: 0.28, channelAttraction: 0.78,- animationSystem: "handshake",+ obstaclePreset: "adom",+ obstacleMode: "outline-wrap",+ revealSystem: "scroll",+ continuousGeneration: true,+ animationSystem: "reflection",+ liveliness: 0.82, motion: true, }); @@ -210,13 +232,14 @@ overflow, and leaves pointer interaction to the surrounding page. ### On this page (no setup, always up) -Both demos are the actual `src/` files, rendered by the wiki straight from this+All three demos are the actual `src/` files, rendered by the wiki straight from this page's repo: | Surface | Live on the wiki | | --- | --- |-| Both, embedded on one page | [render/src/playground.html](/adom/circuit-trace-generators/render/src/playground.html) |+| All three, embedded on one page | [render/src/playground.html](/adom/circuit-trace-generators/render/src/playground.html) | | Tiling router | [render/src/index-classic.html](/adom/circuit-trace-generators/render/src/index-classic.html) |+| Tiling reveal | [render/src/index-reveal.html](/adom/circuit-trace-generators/render/src/index-reveal.html) | | Field router | [render/src/index.html](/adom/circuit-trace-generators/render/src/index.html) | These need no container and do not expire. They run in the render sandbox, which@@ -225,8 +248,7 @@ embeds each demo as an iframe, which works because the page is public. ### Locally -The two projects share one working directory, `~/project/circuit-generator`, and-run on separate ports:+The two projects live in adjacent source directories and run on separate ports: ```bash cd ~/project/circuit-generator@@ -234,33 +256,25 @@ cd ~/project/circuit-generator # Tiling router, http://localhost:8930 node serve-classic.mjs # serves index-classic.html + circuit-background.js +cd ~/project/circuit-generator-codex+ # Field router, http://localhost:8124 ./serve.sh # serves index.html via server.js ``` -### Container port mappings (ephemeral)--These were the original public URLs on container `beziswazskpw`. They only work-while that container serves them, so prefer the wiki-hosted demos above:--| Demo | Port | URL |-| --- | --- | --- |-| Tiling router | 8930 | <https://traces-fuyou1ziuokn.adom.cloud> |-| Field router | 8124 | <https://circuit-y2uq81e4dp1d.adom.cloud> |- ## File map -Both projects live side by side in one directory, which is the single most-confusing thing about the source. This is the split, mirrored under `src/` in-this package:+The two local source directories are combined under `src/` in this package: | File | Belongs to | | --- | --- | | `circuit-background.js` | tiling router (engine) |-| `index-classic.html`, `serve-classic.mjs` | tiling router (demo, port 8930) |+| `circuit-background-reveal.js` | tiling router (progressive reveal) |+| `index-classic.html`, `index-reveal.html` | tiling demos | | `generate-tile.mjs` | tiling router (CLI) |-| `circuit-background-v5.js` | field router (entry: animation shell) |-| `circuit-background-v4.js` | field router (geometry) |-| `circuit-animation-conductor.js`, `circuit-animation-handshake.js` | field router (motion) |-| `circuit-background-v2.js`, `circuit-background-v3.js` | field router (earlier iterations) |+| `circuit-background-v9.js` | field router entry |+| `circuit-geometry-v9.js`, `circuit-obstacles-v9.js` | field geometry and obstacles |+| `circuit-reveal-*.js` | field reveal systems |+| `circuit-animation-*.js` | field ambient systems | | `index.html`, `server.js`, `serve.sh` | field router (demo, port 8124) |+| `TILING-REVEAL.md`, `FIELD-ROUTER.md` | full implementation notes |
SKILL.md+29−11@@ -1,6 +1,6 @@ --- name: circuit-trace-generators-description: Generate the Adom Nitrogen circuit-trace background as seeded SVG, either a repeating 900x450 tile you can use as a CSS background-image or one continuous non-repeating field sized to a mount. Use when a page needs the PCB-trace backdrop, when asked to "generate a circuit background", "make a PCB trace pattern", "circuit tile", "nitrogen hero background", or when tuning trace density, bus width, swirl, or the routed-light animation.+description: Generate the Adom Nitrogen circuit-trace background as seeded SVG, either a repeating 900x450 torus tile, a progressive tile reveal, or one continuous v9 field with obstacle routing and scroll-driven growth. Use when asked to "generate a circuit background", "make a PCB trace pattern", "reveal circuit traces", "route around the ADOM wordmark", "circuit tile", or "nitrogen hero background". user-invocable: true --- @@ -11,7 +11,10 @@ Two engines. Pick by whether the output must repeat. ## Need a repeatable texture: tiling router Emits a `900×450` tile routed on a torus, so it repeats in both axes with no-visible seam and no traces cross the boundary.+visible seam and no traces cross the boundary. It has two presentation modes:++- `index-classic.html` shows the complete board with ambient signal presets.+- `index-reveal.html` grows the same tile with Etch, Flood, Sweep, Bloom, or Scatter. ```bash node src/generate-tile.mjs --seed traces --out tile.svg@@ -23,28 +26,42 @@ longer, calmer runs), `--bus-width`, `--formations`, `--density`, `--weave`, `--cramp`, `--horizontal-bias`, `--net-reach`, `--jog-bias`, `--stub-chance`, `--inline-via-chance`, `--combs`. `--transparent` drops the board fill. +The reveal entry is `circuit-background-reveal.js`. It uses a canvas above the+static SVG so the router can keep one cheap tiled definition. The canvas hands+off only after its glow cools to zero, which avoids a brightness dip or color jump.+ ## Need a bespoke backdrop: field router -One continuous field at the mount's real size, packed with a flow field and-seeded vortices. Mount it in a page:+Version 9 builds one continuous field at the mount's real size. It can reserve or+outline embedded marks, grow by time or scroll progress, and append seeded world+chunks without moving existing geometry. ```js-import { createCircuitBackground } from "./src/circuit-background-v5.js";+import { createCircuitBackground } from "./src/circuit-background-v9.js"; const circuit = createCircuitBackground(document.querySelector("#hero"), { seed: "product-launch",- animationSystem: "handshake", // "none" | "conductor" | "handshake"+ obstaclePreset: "adom",+ obstacleMode: "outline-wrap",+ revealSystem: "scroll",+ continuousGeneration: true,+ animationSystem: "reflection", motion: true, }); ``` -Reach for `animationSystem: "handshake"` on a dense board. It caps concurrent-transactions at 3, so per-frame cost does not grow with geometry. `"none"` mounts-a static SVG with no animation layer at all.+Geometry controls include density, route length, flow direction, swirl, channel+attraction, feature scale, and obstacle placement. Reveal choices are Instant,+Flow sweep, and Scroll weave. Scroll weave can run as a finite field or as an+append-only continuous world. Existing traces never move or repeat when it grows.++Ambient choices are None, Adom reflection, Original conductor, Routed field, and+Adom handshake. Reach for `animationSystem: "handshake"` on a dense board. It+caps concurrent transactions, so per-frame cost does not grow with geometry. For geometry without a DOM, call `generateCircuitField(options)` and render `pathData(trace.points)` yourself. Each trace carries `points`, `length`,-`viaStart`, and `viaEnd`.+`viaStart`, and `viaEnd`. Regular and contour traces have annular vias at both ends. ## Both @@ -52,4 +69,5 @@ Seeded, so the same seed and dimensions give identical geometry. Dependency-free ES modules. Board `#0d1117`, traces `#151b25`, routed light `#00e6dc`, `#64abff`, `#c5b3ff`. Both honour `prefers-reduced-motion`. -See the page README for the full parameter reference and the two live demos.+See the page overview for all three live demos. The Files tab includes+`src/TILING-REVEAL.md` and `src/FIELD-ROUTER.md` for the full implementation notes.
install.sh+2−2@@ -1,10 +1,10 @@ #!/bin/sh set -e -# The engines are dependency-free ES modules — there is nothing to compile or+# The engines are dependency-free ES modules. There is nothing to compile or # link. Installing just puts them on disk; point your page's import at src/, # or run the tile CLI straight out of the module directory. echo "installed: circuit-trace-generators"-echo " engines: $PWD/src/circuit-background.js (tiling), $PWD/src/circuit-background-v5.js (field)"+echo " engines: $PWD/src/circuit-background.js (tile), $PWD/src/circuit-background-reveal.js (tile reveal), $PWD/src/circuit-background-v9.js (field)" echo " tile CLI: node $PWD/src/generate-tile.mjs --seed traces --out tile.svg"
package.json+7−5@@ -2,8 +2,8 @@ "slug": "circuit-trace-generators", "title": "Circuit Trace Generators", "type": "app",- "version": "0.2.0",- "description": "Two dependency-free, seeded SVG generators for the Adom Nitrogen hero background: a tiling router that emits a seamless 900x450 PCB-trace tile from a torus occupancy grid, and a field router that packs one continuous non-repeating trace field using a flow field and seeded vortices.",+ "version": "0.3.0",+ "description": "Two dependency-free, seeded circuit-background generators: a seamless torus tile with ambient or progressive reveal, and the v9 continuous field with obstacles, scroll reveal, and five ambient systems.", "tags": [ "svg", "generative",@@ -17,9 +17,11 @@ "make a PCB trace background", "nitrogen hero background", "seamless circuit tile",- "procedural trace pattern"+ "procedural trace pattern",+ "reveal circuit traces",+ "ADOM wordmark circuit background" ],- "discovery_pitch": "Reach for this when a page needs the Adom circuit-trace backdrop: either a seamless tile you can repeat as a CSS background-image, or one continuous generated field sized to the mount.",+ "discovery_pitch": "Use this when a page needs the Adom circuit-trace backdrop: a seamless tile, a progressive tile reveal, or a continuous v9 field with obstacle routing and scroll-driven growth.", "sample_prompts": [ { "label": "Seamless tile",@@ -36,7 +38,7 @@ }, "hero": { "headline": "Circuit Trace Generators",- "subhead": "Two seeded SVG routers for the Nitrogen hero background: one tiles a torus, one packs a continuous field.",+ "subhead": "Seeded PCB traces as a seamless tile, progressive reveal, or continuous v9 field.", "screenshot": "docs/hero.png", "accent": "#00e6dc" }
page.json+7−7@@ -2,8 +2,8 @@ "slug": "circuit-trace-generators", "title": "Circuit Trace Generators", "type": "app",- "version": "0.2.0",- "description": "Two dependency-free, seeded SVG generators for the Adom Nitrogen hero background: a tiling router that emits a seamless 900x450 PCB-trace tile from a torus occupancy grid, and a field router that packs one continuous non-repeating trace field using a flow field and seeded vortices.",+ "version": "0.3.0",+ "description": "Two dependency-free, seeded circuit-background generators: a seamless torus tile with ambient or progressive reveal, and the v9 continuous field with obstacles, scroll reveal, and five ambient systems.", "tags": [ "svg", "generative",@@ -17,9 +17,11 @@ "make a PCB trace background", "nitrogen hero background", "seamless circuit tile",- "procedural trace pattern"+ "procedural trace pattern",+ "reveal circuit traces",+ "ADOM wordmark circuit background" ],- "discovery_pitch": "Reach for this when a page needs the Adom circuit-trace backdrop: either a seamless tile you can repeat as a CSS background-image, or one continuous generated field sized to the mount.",+ "discovery_pitch": "Use this when a page needs the Adom circuit-trace backdrop: a seamless tile, a progressive tile reveal, or a continuous v9 field with obstacle routing and scroll-driven growth.", "sample_prompts": [ { "label": "Seamless tile",@@ -41,9 +43,7 @@ "screenshot": "screenshots/hero.png", "accent": "#00e6dc" },- "visibility": {- "public": true- },+ "visibility": "public", "org": "adom", "author": { "name": "AdityaAngajala",
readme.html+55−28@@ -56,21 +56,28 @@ <h1>Circuit Trace Generators <span class="pill">live</span></h1> <p class="lede">Two dependency-free, seeded SVG generators that draw the Adom <strong>Nitrogen</strong> hero background, procedural PCB traces, vias, and routed- light. Both are embedded and running below. Drag the sliders, switch presets, and+ light. All three demos are embedded below. Drag the sliders, switch presets, and move the pointer over each board.</p> </header> <!-- ================= LIVE DEMOS ================= --> <section class="demo">- <h2>1 · Tiling router <span class="accent">·</span> seamless torus tile</h2>+ <h2>1 · Tiling router <span class="accent">·</span> repeating torus tile</h2> <p class="meta">Occupancy-grid A* router on a torus. Twelve generation knobs, a cursor-fed signal fountain, and five animation presets. Engine: <code>circuit-background.js</code>.</p> <iframe class="frame" src="/adom/circuit-trace-generators/render/src/index-classic.html" title="Tiling router, live interactive demo" scrolling="no" loading="lazy"></iframe> <p class="open">▶ <a href="/adom/circuit-trace-generators/render/src/index-classic.html" target="_blank" rel="noopener">Open this demo full screen</a></p> </section> <section class="demo">- <h2>2 · Field router <span class="accent">·</span> continuous packed field</h2>- <p class="meta">Flow-field and vortex trace packing, sized to the mount. Five geometry presets and four animation systems. Entry: <code>circuit-background-v5.js</code>.</p>+ <h2>2 · Tiling reveal <span class="accent">·</span> progressive route growth</h2>+ <p class="meta">The same torus tile grows through Etch, Flood, Sweep, Bloom, or Scatter, then hands off to the exact static SVG. Entry: <code>circuit-background-reveal.js</code>.</p>+ <iframe class="frame" src="/adom/circuit-trace-generators/render/src/index-reveal.html" title="Tiling reveal, live interactive demo" scrolling="no" loading="lazy"></iframe>+ <p class="open">▶ <a href="/adom/circuit-trace-generators/render/src/index-reveal.html" target="_blank" rel="noopener">Open this demo full screen</a></p>+ </section>++ <section class="demo">+ <h2>3 · Field router <span class="accent">·</span> continuous packed field</h2>+ <p class="meta">Version 9 adds obstacle routing, flow or scroll reveal, append-only continuous generation, and five ambient systems. Entry: <code>circuit-background-v9.js</code>.</p> <iframe class="frame" src="/adom/circuit-trace-generators/render/src/index.html" title="Field router, live interactive demo" scrolling="no" loading="lazy"></iframe> <p class="open">▶ <a href="/adom/circuit-trace-generators/render/src/index.html" target="_blank" rel="noopener">Open this demo full screen</a></p> </section>@@ -99,8 +106,8 @@ <tr><td>Router</td><td>A* nets between placed terminal formations</td><td>flow field and vortex trace packing</td></tr> <tr><td>Wrap</td><td>torus occupancy grid (no seam, no crossings)</td><td>reserved grid nodes (no crossings)</td></tr> <tr><td>Headless output</td><td><code>generate-tile.mjs</code> writes an SVG tile</td><td><code>generateCircuitField()</code> returns geometry</td></tr>- <tr><td>Motion</td><td>cursor-fed signal fountain</td><td>conductor or handshake system</td></tr>- <tr><td>Entry file</td><td><code>circuit-background.js</code></td><td><code>circuit-background-v5.js</code></td></tr>+ <tr><td>Motion</td><td>signal fountain or progressive reveal</td><td>three reveal modes and five ambient systems</td></tr>+ <tr><td>Entry file</td><td><code>circuit-background.js</code> or <code>circuit-background-reveal.js</code></td><td><code>circuit-background-v9.js</code></td></tr> </table> <p>Both ship <code>createCircuitBackground(mount, options)</code> returning@@ -141,6 +148,13 @@ <strong>Fireflies</strong>, <strong>Swarm</strong>, <strong>Cursor sparks</strong>, <strong>Slow streams</strong>.</p> + <h3>Progressive reveal</h3>+ <p><code>circuit-background-reveal.js</code> grows the same geometry with+ <strong>Etch</strong>, <strong>Flood</strong>, <strong>Sweep</strong>,+ <strong>Bloom</strong>, or <strong>Scatter</strong>. A canvas layer draws only+ moving or cooling routes, then clears after the glow reaches zero and reveals+ the exact static SVG beneath it.</p>+ <h3>Headless CLI</h3> <pre><code>node generate-tile.mjs --seed traces --out tile.svg node generate-tile.mjs --seed foo --turn-penalty 0.8 --combs 0 --transparent > tile.svg</code></pre>@@ -150,42 +164,50 @@ node generate-tile.mjs --seed foo --turn-penalty 0.8 --combs 0 --transparent > <div> <!-- ============ FIELD ============ --> <h2>2 · Field router</h2>- <p><code>circuit-background-v5.js</code>. No tile. A deterministic planar- trace-packing pass fills one continuous field at the mount's real dimensions with- hundreds of independent routes. A rotatable vector field plus seeded, low-frequency- vortices organise long carriers, diagonal runs, and gentle swirls, and- <em>channel attraction</em> collects nearby routes into local buses. <code>v5</code>- is the animation shell over <code>v4</code>'s geometry.</p>+ <p><code>circuit-background-v9.js</code> builds one continuous field at the+ mount's real dimensions. Version 9 separates geometry, obstacles, reveal, and+ ambient motion so each system can change without regenerating the others.</p> - <h3>Tuning</h3>+ <h3>Routing and obstacles</h3> <p><code>fill</code>, <code>routeLength</code>, <code>horizontalFlow</code>, <code>flowAngle</code>, <code>diagonalFlow</code>, <code>longFlow</code>, <code>swirl</code>, <code>swirlScale</code>, <code>jogLength</code>, <code>channelAttraction</code>, <code>edgeDensity</code>, <code>featureScale</code>.- Geometry presets: <strong>Original match</strong> (default), <strong>Dense</strong>,- <strong>Diagonal sweep</strong>, <strong>Broad swirl</strong>, <strong>Sparse</strong>.</p>+ Obstacles can avoid, outline, or outline and wrap rectangles, ellipses, polygons,+ rings, and wordmarks. <code>obstaclePreset: "adom"</code> uses the built-in mark.</p> - <h3>Animation systems</h3>+ <h3>Reveal</h3>+ <ul>+ <li><strong>Instant</strong> mounts the finished field.</li>+ <li><strong>Flow sweep</strong> grows each via-to-via route on a timed front.</li>+ <li><strong>Scroll weave</strong> unlocks routes from page progress and can append new seeded world sections without moving existing geometry.</li>+ </ul>++ <h3>Ambient systems</h3> <ul> <li><strong>None</strong> mounts only the static SVG.</li>- <li><strong>Conductor</strong> (<code>circuit-animation-conductor.js</code>): ambient currents, breathing nodes, core and halo packets, convoys, spatial waves, pointer wake.</li>- <li><strong>Routed field</strong> (<code>animationSystem: "adom"</code>, in <code>v4</code>): a slow 18° sweep plus periodic blooms near the cursor, capped at three.</li>- <li><strong>Handshake</strong> (<code>circuit-animation-handshake.js</code>): each transaction charges a source via, traverses one trace once, settles, and acks back. Only <code>maxHandshakes</code> (3) coexist, so per-frame cost does not grow with density. Reach for it on a dense board.</li>+ <li><strong>Adom reflection</strong> sends a restrained brand-color sheen across a precomposed trace mask.</li>+ <li><strong>Original conductor</strong> runs currents, nodes, packets, convoys, waves, and pointer wake.</li>+ <li><strong>Routed field</strong> keeps the legacy spatial sweep and bloom system.</li>+ <li><strong>Adom handshake</strong> caps sparse via-to-via request and acknowledgement transactions.</li> </ul> <h3>API</h3>- <pre><code>import { createCircuitBackground } from "./circuit-background-v5.js";+ <pre><code>import { createCircuitBackground } from "./circuit-background-v9.js"; const circuit = createCircuitBackground(mount, { seed: "product-launch",- animationSystem: "handshake", // none | conductor | routed | handshake+ obstaclePreset: "adom",+ obstacleMode: "outline-wrap",+ revealSystem: "scroll",+ continuousGeneration: true,+ animationSystem: "reflection", motion: true, }); circuit.regenerate({ seed: "another-layout" }); const svg = circuit.exportSvg(); // static, no motion layers</code></pre> <p><code>generateCircuitField(options)</code> returns deterministic geometry with no DOM. Each trace carries <code>points</code>, <code>length</code>,- <code>viaStart</code>, <code>viaEnd</code>; <code>pathData(points)</code> makes SVG.</p> </div> </div> @@ -196,25 +218,30 @@ const svg = circuit.exportSvg(); // static, no motion layers</code></pre> <table> <tr><th>Surface</th><th>Live on the wiki</th></tr> <tr><td>Tiling router</td><td><a href="/adom/circuit-trace-generators/render/src/index-classic.html">render/src/index-classic.html</a></td></tr>+ <tr><td>Tiling reveal</td><td><a href="/adom/circuit-trace-generators/render/src/index-reveal.html">render/src/index-reveal.html</a></td></tr> <tr><td>Field router</td><td><a href="/adom/circuit-trace-generators/render/src/index.html">render/src/index.html</a></td></tr> </table>- <p>Locally the two projects share one working directory and run on separate ports:</p>+ <p>Locally the generators live in adjacent source directories and run on separate ports:</p> <pre><code>cd ~/project/circuit-generator node serve-classic.mjs # tiling router, http://localhost:8930++cd ~/project/circuit-generator-codex ./serve.sh # field router, http://localhost:8124</code></pre> <!-- ================= FILE MAP ================= --> <h2>File map</h2>- <p>Both projects live side by side in one directory, mirrored under <code>src/</code> in this page's repo:</p>+ <p>The two local source directories are combined under <code>src/</code> in this page's repo:</p> <table> <tr><th>File</th><th>Belongs to</th></tr> <tr><td><code>circuit-background.js</code></td><td>tiling router (engine)</td></tr>- <tr><td><code>index-classic.html</code>, <code>serve-classic.mjs</code></td><td>tiling router (demo, port 8930)</td></tr>+ <tr><td><code>circuit-background-reveal.js</code></td><td>tiling router (progressive reveal)</td></tr>+ <tr><td><code>index-classic.html</code>, <code>index-reveal.html</code></td><td>tiling demos</td></tr> <tr><td><code>generate-tile.mjs</code></td><td>tiling router (CLI)</td></tr>- <tr><td><code>circuit-background-v5.js</code></td><td>field router (entry: animation shell)</td></tr>- <tr><td><code>circuit-background-v4.js</code></td><td>field router (geometry)</td></tr>- <tr><td><code>circuit-animation-conductor.js</code>, <code>circuit-animation-handshake.js</code></td><td>field router (motion)</td></tr>+ <tr><td><code>circuit-background-v9.js</code></td><td>field router entry</td></tr>+ <tr><td><code>circuit-geometry-v9.js</code>, <code>circuit-obstacles-v9.js</code></td><td>field geometry and obstacles</td></tr>+ <tr><td><code>circuit-reveal-*.js</code>, <code>circuit-animation-*.js</code></td><td>field reveal and ambient motion</td></tr> <tr><td><code>index.html</code>, <code>server.js</code>, <code>serve.sh</code></td><td>field router (demo, port 8124)</td></tr>+ <tr><td><code>TILING-REVEAL.md</code>, <code>FIELD-ROUTER.md</code></td><td>full implementation notes</td></tr> </table> <footer>
src/FIELD-ROUTER.mdadded+194@@ -0,0 +1,194 @@+# Procedural circuit background++A dependency-free, seeded SVG generator modeled on the Nitrogen landing-page+background. The active engine is `circuit-background-v9.js`. Version 8 is frozen+at `/v8`, and version 9 is available at `/` and `/v9`.++The reference measurements used by the generator are:++- a `7.895` unit routing grid;+- `1.58` unit traces in `#151b25`;+- horizontal and vertical channels with short 45° chamfers;+- `3.34 / 1.76` unit annular vias;+- Adom's teal to blue to purple signature gradient for routed light.++Unlike the source artwork, the generator does not repeat a tile. It creates one+continuous field for the mount's real dimensions. A deterministic planar trace-packing pass+fills that field with hundreds of independent routes. A rotatable vector field and+seeded, low-frequency vortices organize long carriers, diagonal runs, and gentle+swirls; channel attraction collects nearby routes into natural local buses,+and reserves every occupied grid node. Separate traces therefore do not cross or+overlap.++## Run the demo++```bash+cd /home/adom/project/circuit-generator-codex+./serve.sh+```++Open `http://localhost:8124`. The v9 demo opens on **Original match**, using the+same obstacle-free layout as v8. **ADOM embed** is the last generation preset. Dense,+Diagonal sweep, Broad swirl, and Sparse remain available. The parameter panel exposes+visual density, average route length,+primary-flow balance, flow angle, diagonal flow, long-carrier density, swirl+strength and scale, jog size, channel attraction, and obstacle placement. Movement+power tunes the selected animation. Export SVG downloads the current field without+motion layers.++The embedded-mark controls offer three routing modes. Avoid reserves the shape as+negative space. Outline adds via-to-via traces along the exact contour. Outline ++wrap also pulls nearby routes into tangent lanes around the contour. Size, position,+clearance, and edge pull can be changed without affecting the reveal or ambient+animation presets.++Generation, Reveal, and Animation are separate control groups. Geometry presets never+change motion settings. **Dense** captures the high-density, thin-feature+look and **Sparse** the opposite end: few long bundled runs at a large feature+scale, so most of the field stays open. Visual density controls packing+independently, while Circuit scale+proportionally changes routing pitch, trace width, via rings, and routed-light+geometry as one coherent motif. Every generated trace has a full annular via at+both endpoints.++Reveal is independent from ambient animation. Instant mounts the complete board. Flow sweep grows every route from its source via to its destination via on a timed routing front. Scroll weave uses page progress only to make ordered routes eligible. A separate time-based queue grows each route to completion, so new traces keep resolving near the lower viewport without scrubbing when the reader scrolls quickly. Directional, radial, edge, and scatter spawn patterns can be tuned with angle, swirl, glow, duration, launch rate, active-trace count, scroll-speed response, and reveal lead controls.++Scroll weave can run as a finite field or an append-only continuous field. Continuous mode keeps one seeded world grid and one shared occupancy map, generates fixed chunks ahead during idle time, and extends the page only after the next section is ready. Existing geometry never moves or repeats when the field grows. Every appended trace still has a start via and an end via.++Ambient animation remains a separate choice: None, Adom reflection, Original conductor, Routed field, and Adom handshake. None creates no ambient layer. Adom reflection sends a slow brand-color sheen across a precomposed trace mask. Original conductor preserves the earlier currents and waves. Routed field keeps the legacy spatial field and owns its trace lifecycle, so Reveal is disabled while it is selected. Adom handshake runs a small number of via-to-via request and acknowledgement transactions. Reduced-motion preferences complete the reveal and disable ambient motion.++Reveal presets are exported as `REVEAL_PRESETS`:++- **Instant**: the generated circuit appears complete.+- **Flow sweep**: a timed, warped front grows each complete via-to-via route.+- **Scroll weave**: scrolling queues independent trace growth and can append new world sections continuously.++Ambient presets are exported as `ANIMATION_PRESETS`:++- **None**: no ambient animation layer.+- **Adom reflection**: a restrained masked brand-color reflection.+- **Original conductor**: the complete current, signal, and wave system.+- **Routed field**: the legacy spatial field and bloom system.+- **Adom handshake**: sparse via-to-via request and acknowledgement motion.++## Use it in another page++```html+<div id="hero-circuit"></div>+<script type="module">+ import { createCircuitBackground } from "./circuit-background-v9.js";++ const circuit = createCircuitBackground(+ document.querySelector("#hero-circuit"),+ {+ seed: "product-launch",+ fill: 0.668,+ routeLength: 0.78,+ horizontalFlow: 0.82,+ flowAngle: 0,+ diagonalFlow: 0.58,+ longFlow: 0.18,+ swirl: 0.28,+ swirlScale: 0.8,+ jogLength: 0.72,+ channelAttraction: 0.78,+ featureScale: 1,+ obstaclePreset: "adom",+ obstacleMode: "outline-wrap",+ obstacleScale: 0.68,+ obstacleX: 0.5,+ obstacleY: 0.66,+ obstacleClearance: 1.1,+ obstaclePull: 0.82,+ revealSystem: "scroll",+ spawnMode: "flow",+ spawnAngle: 90,+ traceDuration: 950,+ revealLaunchRate: 24,+ maxActiveTraces: 72,+ scrollSpeedResponse: 0.6,+ unlockLead: 0.025,+ continuousGeneration: true,+ generationAheadScreens: 2,+ animationSystem: "conductor",+ liveliness: 0.82,+ motion: true,+ },+ );++ // Same seed and dimensions produce identical geometry.+ circuit.regenerate({ seed: "another-layout" });++ // Reveal timing and spawn behavior can change without regenerating geometry.+ circuit.setReveal({ traceDuration: 1100, spawnAngle: 35, spawnSwirl: 0.12 });++ // Ambient animation can change without replaying the trace reveal.+ circuit.setAnimation({ animationSystem: "reflection", motion: true });++ // Trigger the selected ambient animation from a point in SVG coordinates.+ circuit.triggerAnimation({ x: 240, y: 180 });++ // Scroll progress can also be advanced from a custom page controller.+ circuit.setRevealProgress(0.5);++ // Export exactly what is mounted, without the motion layers.+ const svg = circuit.exportSvg();++ // Remove observers, listeners, timers, and generated DOM.+ // circuit.destroy();+</script>+```++The mount must have a real width and height. The helper observes resizes, clips+overflow, respects `prefers-reduced-motion`, and leaves pointer interaction to the+surrounding page. Pointer movement and clicks use the interaction language of the+selected animation preset.++## Geometry API++`generateCircuitField(options)` returns deterministic trace geometry without+touching the DOM. Each trace contains `points`, `length`, `viaStart`, and `viaEnd`.+`pathData(points)` converts one trace to SVG path data. Every regular and contour+trace has distinct start and end points with annular vias.++### Obstacles++Set `obstaclePreset: "adom"` for the built-in official wordmark. Programmatic callers+can also pass an `obstacles` array. Supported types are `rect`, `ellipse`, `polygon`,+`rings`, and `wordmark`. Coordinates are normalized to the field unless+`space: "world"` is set.++```js+const field = generateCircuitField({+ seed: "launch",+ width: 1200,+ height: 700,+ obstacleMode: "outline-wrap",+ obstacleClearance: 1.2,+ obstaclePull: 0.9,+ obstacles: [+ { type: "rect", x: 0.22, y: 0.3, width: 0.18, height: 0.12 },+ { type: "ellipse", x: 0.76, y: 0.34, width: 0.16, height: 0.2 },+ { type: "polygon", points: [[0.38, 0.76], [0.5, 0.56], [0.62, 0.76]] },+ ],+});+```++The default ADOM obstacle belongs to the first canonical page in continuous-scroll+mode, so the wordmark appears once. Later generated pages continue the same seeded+routing field without repeating it.++Useful options include `seed`, `width`, `height`, `pitch`, `fill`, `routeLength`,+`horizontalFlow`, `flowAngle`, `diagonalFlow`, `longFlow`, `swirl`, `swirlScale`,+`jogLength`, `channelAttraction`, `edgeDensity`, `featureScale`, `traceColor`,+`traceWidth`, `obstaclePreset`, `obstacleMode`, `obstacleScale`, `obstacleX`,+`obstacleY`, `obstacleClearance`, `obstaclePull`, `obstacles`, `revealSystem`,+`revealMotion`, `spawnMode`, `spawnAngle`,+`spawnSwirl`, `spawnOriginX`, `spawnOriginY`, `traceDuration`, `revealLaunchRate`,+`scrollSpeedResponse`, `unlockLead`, `maxActiveTraces`, `continuousGeneration`,+`generationAheadScreens`,+`animationSystem`, `liveliness`, `motion`, `signalInterval`,+`waveInterval`, `ambientCurrentCount`, `ambientNodeCount`, `handshakeInterval`,+`handshakeSpeed`, `handshakeLength`, `maxHandshakes`, `revealDuration`,+`revealAngle`, `revealGlow`, `reflectionStrength`, `reflectionCycle`,+`reflectionWidth`, and `reflectionAngle`.
src/TILING-REVEAL.mdadded+262@@ -0,0 +1,262 @@+# Reveal build, the board growing itself in++A copy of the occupancy-grid engine that **grows** the board instead of showing+it finished. Nothing in the original files changed:++| | classic | reveal |+| --- | --- | --- |+| engine | `circuit-background.js` | `circuit-background-reveal.js` |+| page | `index-classic.html` | `index-reveal.html` |+| URL (port 8930) | `/` | `/reveal` |++## What happens++Copper grows out across the background as one front: each route draws itself out+of an end via, with a white-hot head riding the growing tip and pads landing as+the tip reaches them. When the last route lands, the hot layer cross-fades into+the real SVG artwork.++## The look: heat, not paint++A single bright colour everywhere reads as a neon sheet, not as something being+made. Two rules fix that:++- **Copper cools.** The tip is near-white, the colour sits just behind it, and+ everything already laid fades exponentially (`revealCool`) toward a dim+ settled trace. At any instant the screen shows a bright rim, a warm wake, and+ a quiet interior, depth instead of one flat brightness. The default is **25+ ms**, the bottom of the knob and the shortest the engine can honour (the+ tail's tightening floors at 24), which leaves each route a wake about a+ tip-length long rather than a board that stays warm. Even there the fade only+ removes 48.7% per frame at 60fps, still short of the >50% a multiplicative+ fade needs to reach zero on its own, so the generation buffers below are doing+ real work at every setting.+- **Colour comes in regions.** Hue is sampled from a smooth screen-space noise+ field (`revealZone` px) across the engine's own teal → blue → violet ramp, so+ the board grows in broad zones of colour rather than confetti or one tone.++The settled copper keeps a trace of its zone's hue (`revealSettle`), so the+closing cross-fade into the uniform near-black artwork is a settling, not a cut.++## Timing, the same motion language as the live signals++The reveal and the idle signal animation are one system, so the reveal borrows+the signal system's timing rules rather than inventing its own:++- **Constant speed, linear.** A tip travels at `revealSpeed` units/sec, the same+ units and the same default (420) as `signalSpeed`. It is never eased and never+ scaled by a route's length, so every tip on screen moves at one pace and a long+ bus takes longer than a short comb tap.+- **The same stroke stack**: a ~2.4-wide core over a 7-wide glow, like a signal's+ head and halo.+- **The same arrival blip.** A pad grows into place and rings out, the ring runs+ from the pad radius out to ~8 over `revealBlip`, matching the ring a signal+ leaves when it lands on a via.+- **The same palette** (`revealPalette` is the signal palette verbatim).++Nothing appears or vanishes in one frame:++| moment | before | now |+| --- | --- | --- |+| board at the start | cut to hidden | fades out over 260 ms under the growth |+| a route's head | popped in, vanished on landing | fades in (130 ms), fades out after landing (260 ms) |+| a pad | stamped at full size | scales up and rings out before being stamped into the settled layer |+| the via hole | drilled when the pop ended | annular from the first frame |+| signals after the reveal | a dozen appeared mid-flight at once | the fountain fills from empty at its own cadence |+| resize mid-reveal | restarted the whole growth | settles, but only on a REAL size change; the observer also fires when nothing moved, which was ending the reveal ~200 ms in |+| the handoff to the static board | cross-faded, dipped and shifted hue | invisible: the board comes up under an opaque canvas, then only the glow fades |++**The layer that was missing.** The single loudest "traces pop in fully formed"+symptom had nothing to do with the schedule: the final composite drew only the+settled and tip layers, so the two heat generations were sized, cleared, faded,+rotated and stroked into every frame, and never reached the screen. A route's+copper lives ONLY in the heat buffer until it lands, so every route was invisible+while it grew and appeared whole the instant it was stamped into the settled+layer. All that was visible mid-growth was the tip spark, and there was no glow+at all. Measured by running the engine against a recording canvas: before, 2 of 4+layers were drawn into but never composited; after, all 4 composite and 3.5M px+of stroke per reveal reaches the screen through the heat buffer.++The release queue was also sorted by **metric**, not by delay, while the release+loop walks it with a single cursor. Jitter (±37 ms) is ~80x wider than the gap+between neighbouring start times (0.91 ms median), which left 84% of the queue+out of order and head-of-line blocked routes up to 71 ms behind the cursor before+letting them out in one burst, the opposite of what the jitter is for. It is now+sorted by delay.++A route starts growing when it is first **drawn**, not at the wall-clock moment+it was scheduled (`startedAt`, capped at `REVEAL_CATCHUP` ms of catch-up).+Deriving growth from the schedule means any slow frame, a GC pause, a busy tab,+a machine waking up, releases every route whose start time has passed *already+fully grown*: they pop into existence instead of animating. Measured before the+fix, with ~700 ms hitches in the frame stream: **941 of 2070 routes were born+complete**, the median route born 106 px long against a typical length of ~78 px.+After: **zero**, and never more than 16 px. Pads are timed off the same start, so+a late route does not sprinkle its pads ahead of its own tip, and the closing+tail waits for the growth to finish rather than for the clock.++Start times also carry ±35 ms of scatter (`REVEAL_JITTER`). Without it the first+wave of short routes all landed on the same frame and their pads popped together+, a visible batch. Measured frame-to-frame ink change went from 7.8% of the board+to 3.0%, and the only frames above 2.5% are now the mid-point of the closing+cross-fade, where a fade is supposed to be steep.++### The glow, and why it now reaches exactly zero++The glow accumulates in a buffer that is faded a little every frame, one fill,+whatever is warm. That is what keeps it O(1). But a multiplicative fade never+reaches zero: at 8 bits a pixel stops moving as soon as `alpha x decay` rounds+back to itself, so a multiply only lands on 0 if it removes more than half per+frame. Measured at a 150 ms heat fade (5.19%/frame): alpha ran+255 → 151 → 31 → **9, and stayed 9 forever**, 3.5% of `#00e6dc` sitting on the+copper permanently, turning rgb(21, 27, 37) into rgb(20, 34, 43). That residue is+why the growing board read lighter and bluer than the finished one. Canvas has no+subtractive alpha operation, so no choice of fade curve fixes it.++The fix is a multiply by **zero**, applied where it costs nothing: the buffer is+kept in two **generations**. New glow always goes into the current one. The other+keeps decaying but is also composited through a falling ramp, and once that ramp+reaches zero its buffer is cleared outright. Every pixel therefore ends at exactly+zero, the clear happens at a moment when it changes nothing on screen, and the+per-frame cost is still two fills and two composites regardless of how much of the+board is glowing.++(An earlier attempt derived the whole glow from the routes every frame, in+floating point. It was exact, but its cost scales with how much copper is warm,+at a long heat fade that is the whole board, and it showed.)++Verified live at a 150 ms fade, sampling every fully-opaque pixel of the growth+layer: the dominant colour is rgb(21, 27, 37) at t = 1.5 s, 3 s and 5 s, the+artwork's own copper, exactly. Frame pacing with it: **4.2 ms median, 9.2 ms p95**.++### Matching the static board exactly++Measured against the SVG board it hands over to (same seed, same density, ink+weighted by coverage):++| how the copper is laid | coverage | vs SVG | ink colour |+| --- | --- | --- | --- |+| SVG | 0.14129 |, | rgb(19.9, 25.8, 35.4) |+| one stroke per route, butt caps + miter joins | 0.14125 | −0.03% | rgb(19.9, 25.8, 35.4) |+| per-frame pieces (what it used to do) | 0.14261 | +0.93% | rgb(19.8, 25.7, 35.4) |++The colour was never the problem, it is identical either way. What differed was+weight: stroking a route in per-frame pieces blends each piece's antialiased edge+over the last one, leaving the canvas board ~1% denser than the SVG. So a route+in progress is now redrawn whole on its own layer each frame, and stamped into+the persistent layer exactly once when it lands, with the artwork's own caps and+joins. Cost of redrawing the in-flight routes: **0.28 ms/frame** (only ~4% of the+board is growing at any instant; stroking the entire board once costs 7 ms).++That layer sits UNDER the glow. Copper painted over its own glow reads as a dark+line with a coloured fringe instead of hot metal.++The tail is two phases, and that ordering matters. First the remaining glow is+cooled to nothing, the time constant tightens over `handoff`+(`clamp(revealCool x 1.6, 120, 1100)`) ms so the glow leaves *as glow*, at its+own rate. That floor was 260 ms, which at a short heat fade left the+finished board sitting untouched for ~150 ms with nothing left to cool; at the+25 ms default the whole reveal is now 4.3 s end to end instead of 5.3 s, with+the growth itself unchanged. Only then does the canvas dissolve+(`REVEAL_HANDOFF`, 260 ms), by which point it holds nothing but copper identical+to the SVG already at full opacity beneath it. Fading the canvas while it was+still glowing yanked the warm rim away instead of letting it cool, which reads as+a colour change, most obviously with **heat fade at minimum**, where the fade and+the decay ran at the same short duration. Measured at the dissolve: peak glow+above the board colour drops 187 → 16 (−97%) before anything fades.++The handoff deserves its own note. Cross-fading the growth layer out while the+SVG faded in looks obvious for two reasons: alpha compositing is not additive, so+two complementary alphas over identical copper dip to ~75% opacity halfway+through; and the settled copper carried a little of its zone's hue, so the whole+board changed colour at the same moment. Now the settled layer is stroked in the+artwork's exact colour (`revealSettle: 1`), the real SVG snaps to full opacity+underneath the still-opaque canvas the instant growth ends, and the canvas fades+off the top of it, so all that disappears is the glow. The growth+layers also match `devicePixelRatio` (capped at 2), or a soft board would hand+over to a crisp one.++**A trap worth remembering:** Chrome restores form-control values a beat after a+reload and fires `change` on each one. The tuning sliders' change handler+regenerates the board, so every reload silently kicked off two or three extra+reveals a few seconds in, which looked exactly like the animation randomly+restarting. `autocomplete="off"` on the form fixes it.++## Why it is a canvas, not an animated SVG++The board is ONE tile in `<defs>`, instanced ~25× by `<use>`. That instancing is+what makes the background cheap, and it is also why the obvious implementations+do not work:++- **Web Animations on the referenced content paint nothing.** Chrome runs them+ on the original element, `getComputedStyle` shows the dash offset advancing+ perfectly, but `<use>` instances mirror DOM and attribute state only, not the+ animation's effect. The board looked frozen while the DOM said it was growing.+ (Do not "verify" an animation by reading the DOM. Look at pixels.)+- **Writing attributes every frame does propagate, but costs ~260 ms/frame.**+ Every mutation on referenced content resyncs all 25 instances.++So the reveal renders on a `<canvas>` above the SVG, and the SVG is hidden until+the handoff. Two layers: **settled** (persistent, each route stamped once, when+it lands) and **work** (cleared every frame, growing copper, its glow, the heads+and the pads). Measured: **8.4 ms median frame, 13 ms p95** on a 3000×2000+viewport.++What keeps it cheap:++- **Landed copper is free.** A route is stroked into the persistent layer exactly+ once; after that it costs nothing to keep on screen. Only what is still moving+ or still warm is redrawn.+- **Screen-space scheduling.** Every (route × screen tile) is its own run with+ its own start time, so the growth is one front across the whole background+ rather than the same blob repeated in each tile. ~11k runs sort once at start;+ per-frame work tracks only what is moving.++Start times are spread by **ink**, not by run count: a third of the records are+pad-only formations with no line to draw, and pacing by count gave the reveal a+two-second opening where only vias sprinkled in, which read as a field of dots+rather than anything growing.++## Styles (`REVEAL_PRESETS`)++- **Instant**, off; the board is there.+- **Etch**, build order: pads, then the nets between them, then filler, then tap+ combs. The router's own passes, replayed everywhere at once.+- **Flood**, outward from the cursor (or centre), nudged by how many hops of+ routing separate each trace from its tile's seed, so the front follows copper.+- **Sweep**, a shallow diagonal scan across the screen.+- **Bloom**, rings expanding from the cursor.+- **Scatter**, no order; the whole board stipples in.++## Config++`reveal`, `revealDuration` (whole board), `revealSpeed` (units/sec a tip+travels), `revealHead`, `revealBlip`, `revealSpark`, `revealPalette`,+`revealTip`, `revealZone`, `revealSwell`, `revealBloom`, `revealCool` (heat time+constant), `revealSettle`. All six styles and seven knobs are on the page;+**Replay ⟳** regrows the board without re-routing it+(`circuit.replayReveal(style)`).++Signals wait for the reveal to finish before spawning, a pulse running down a+trace that is not there yet reads as a glitch. `prefers-reduced-motion` skips the+reveal entirely, and exporting mid-reveal snaps to the finished board first, so+downloads are never half-grown.++## Verifying changes++Headless Chrome in this container never produces a screenshot, `--screenshot`+hangs even on a `data:` URL, with or without virtual time, so the offline check+`node checks/frames.mjs`: it runs the REAL engine against a recording canvas on a+synthetic rAF clock and reports which layers reach the visible context+and how much stroke goes with them. That is what caught the missing heat+composite; reading the draw code had not. `node checks/timing.mjs` does the same+for the schedule (route durations, queue ordering, release bursts) without any+DOM at all. `COOL=150 node checks/frames.mjs` exercises the generation rotation,+which never fires at the default 1200 ms cool within one reveal.++The pup window is usually occluded, so Chrome paint-throttles it to ~1 Hz and+screenshots lag by seconds, several rounds of "it still looks wrong" were stale+frames. To capture an exact instant, freeze the page (cancel its timers and+rAF) and take the screenshot after a few seconds, or have the page rasterize+itself: clone the SVG, serialize, draw it into a canvas, and read the data URL+back through `browser_eval`.
src/checks/frames.mjsadded+217@@ -0,0 +1,217 @@+// Runs the REAL engine against a recording canvas on a synthetic clock, and+// asks the only question that matters for "popping": on how many frames is a+// route visible while it is still incomplete? A route that only ever shows up+// at full length popped, however good its schedule was.+//+// usage: node checks/frames.mjs [engine.js] (default: the reveal engine)+import { copyFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const source = process.argv[2] || join(here, "..", "circuit-background-reveal.js");+// Node reads .js as CommonJS without a package.json, so import a .mjs copy.+const enginePath = join(tmpdir(), `reveal-engine-${process.pid}.mjs`);+copyFileSync(source, enginePath);++const layers = new Map(); // canvas -> name+let nextId = 0;++// Every stroke/fill is recorded against the canvas it landed on. Path lengths+// are accumulated so we can compare a partial route with a complete route.+function makeContext(canvas) {+ const ctx = {+ canvas,+ _path: [],+ _len: 0,+ globalAlpha: 1,+ globalCompositeOperation: "source-over",+ strokeStyle: "#000",+ fillStyle: "#000",+ lineWidth: 1,+ lineCap: "butt",+ lineJoin: "miter",+ setTransform() {},+ save() {},+ restore() {},+ clearRect() {+ canvas.ops.push({ op: "clear" });+ },+ fillRect() {},+ beginPath() {+ ctx._path = [];+ ctx._len = 0;+ },+ moveTo(x, y) {+ ctx._path = [[x, y]];+ },+ lineTo(x, y) {+ const p = ctx._path[ctx._path.length - 1];+ if (p) ctx._len += Math.hypot(x - p[0], y - p[1]);+ ctx._path.push([x, y]);+ },+ arc() {+ ctx._path.push(["arc"]);+ },+ stroke() {+ if (ctx._len > 0) canvas.ops.push({ op: "stroke", len: ctx._len, alpha: ctx.globalAlpha });+ },+ fill() {+ canvas.ops.push({ op: "fill", alpha: ctx.globalAlpha });+ },+ drawImage(src) {+ canvas.ops.push({ op: "draw", from: layers.get(src) || "?", alpha: ctx.globalAlpha });+ },+ };+ return ctx;+}++function makeCanvas() {+ const canvas = {+ _id: nextId++,+ width: 0,+ height: 0,+ style: {},+ ops: [],+ getContext: () => canvas._ctx,+ };+ canvas._ctx = makeContext(canvas);+ return canvas;+}++const noopEl = () => {+ const el = {+ style: {},+ children: [],+ dataset: {},+ setAttribute() {},+ getAttribute: () => null,+ removeAttribute() {},+ appendChild(c) {+ el.children.push(c);+ return c;+ },+ append(...c) {+ el.children.push(...c);+ },+ insertBefore(c) {+ el.children.unshift(c);+ return c;+ },+ get firstChild() {+ return el.children[0] || null;+ },+ prepend(c) {+ el.children.unshift(c);+ return c;+ },+ removeChild() {},+ remove() {},+ replaceChildren() {+ el.children = [];+ },+ addEventListener() {},+ removeEventListener() {},+ querySelector: () => null,+ querySelectorAll: () => [],+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 1400, height: 900 }),+ clientWidth: 1400,+ clientHeight: 900,+ cloneNode: () => noopEl(),+ contains: () => false,+ };+ return el;+};++let clock = 0;+const rafQueue = [];+globalThis.performance = { now: () => clock };+globalThis.ResizeObserver = class {+ observe() {}+ disconnect() {}+};+globalThis.document = {+ hidden: false,+ createElement(tag) {+ if (tag === "canvas") {+ const c = makeCanvas();+ layers.set(c, `canvas#${c._id}`);+ return c;+ }+ return noopEl();+ },+ createElementNS: () => noopEl(),+ addEventListener() {},+ removeEventListener() {},+};+globalThis.window = {+ devicePixelRatio: 1,+ requestAnimationFrame(fn) {+ rafQueue.push(fn);+ return rafQueue.length;+ },+ cancelAnimationFrame() {},+ setTimeout: () => 0,+ clearTimeout() {},+ setInterval: () => 0,+ clearInterval() {},+ matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ getComputedStyle: () => ({ getPropertyValue: () => "#0d1117" }),+};+globalThis.getComputedStyle = globalThis.window.getComputedStyle;+globalThis.devicePixelRatio = 1;+globalThis.Element = class Element {};+globalThis.SVGElement = class SVGElement extends Element {};++const { createCircuitBackground } = await import(enginePath);++const mount = Object.assign(new globalThis.Element(), noopEl());+const circuit = createCircuitBackground(mount, { seed: "nitrogen", reveal: "flood", animate: false, ...(process.env.COOL ? { revealCool: Number(process.env.COOL) } : {}) });++// The visible canvas is the one the engine prepends to the mount.+const visible = mount.children.find((c) => c.ops);+layers.set(visible, "VISIBLE");++// Name the offscreen layers by the order the engine creates them:+// settled, heat A, heat B, tip (see ensureRevealCanvas)+const offscreen = [...layers.keys()].filter((c) => c !== visible && c.ops);+const names = ["settled", "heatA", "heatB", "tip"];+offscreen.slice(-4).forEach((c, i) => layers.set(c, names[i] || `extra${i}`));++const FRAME = 16.7;+const seen = new Map(); // route -> {partial, whole}+let frames = 0;+let compositedFrom = new Set();++while (rafQueue.length && frames < 700) {+ const batch = rafQueue.splice(0, rafQueue.length);+ clock += FRAME;+ for (const c of layers.keys()) c.ops.length = 0;+ for (const fn of batch) fn(clock);+ frames += 1;++ // which layers actually reached the screen this frame?+ const drawn = new Set(visible.ops.filter((o) => o.op === "draw" && o.alpha > 0.001).map((o) => o.from));+ drawn.forEach((d) => compositedFrom.add(d));++ // stroke length that reached the screen, split by layer+ for (const [canvas, name] of layers) {+ if (canvas === visible || !drawn.has(name)) continue;+ const len = canvas.ops.filter((o) => o.op === "stroke").reduce((a, o) => a + o.len, 0);+ const rec = seen.get(name) || { frames: 0, len: 0 };+ if (len > 0) rec.frames += 1;+ rec.len += len;+ seen.set(name, rec);+ }+}++console.log(`engine: ${source}`);+console.log(`frames simulated: ${frames}`);+console.log(`layers ever composited to the visible canvas: ${[...compositedFrom].sort().join(", ") || "(none)"}`);+const never = names.filter((n) => !compositedFrom.has(n));+console.log(`layers drawn into but NEVER composited: ${never.join(", ") || "(none)"}`);+for (const [name, rec] of seen) {+ console.log(` ${name}: painted on ${rec.frames} frames, ${Math.round(rec.len)}px of stroke reached the screen`);+}+
src/checks/timing.mjsadded+197@@ -0,0 +1,197 @@+// Timing audit of the reveal schedule, offline. Replicates buildSchedule's math+// against the real generated tile, then simulates the release loop at a fixed+// frame clock and asks the only question that matters: how many frames does+// each route spend PARTIALLY drawn? One frame or fewer == it popped.+import { copyFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, dirname } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const enginePath = join(tmpdir(), `reveal-tile-${process.pid}.mjs`);+copyFileSync(join(here, "..", "circuit-background-reveal.js"), enginePath);+const { generateCircuitTile, DEFAULTS } = await import(enginePath);++const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));+function hashSeed(input) {+ let h = 2166136261;+ for (let i = 0; i < input.length; i += 1) {+ h ^= input.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}+function mulberry32(seed) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const REVEAL_JITTER = 70;+const REVEAL_CATCHUP = 40;++const cfg = { ...DEFAULTS, reveal: "flood", seed: "nitrogen" };+const tile = generateCircuitTile(cfg);+const scale = cfg.scale;+const viewWidth = 1400;+const viewHeight = 900;++// buildRevealGeometry+const geometry = tile.traces.map((trace) => {+ const points = trace.points.map(([x, y]) => [x * scale, y * scale]);+ let len = 0;+ for (let i = 1; i < points.length; i += 1) {+ len += Math.hypot(points[i][0] - points[i - 1][0], points[i][1] - points[i - 1][1]);+ }+ const anchor = trace.points[0] || trace.vias[0] || [0, 0];+ return {+ length: len,+ drawable: points.length >= 2,+ vias: trace.vias,+ anchor: [anchor[0] * scale, anchor[1] * scale],+ };+});++const tileWidth = tile.width * scale;+const tileHeight = tile.height * scale;+const tilesAcross = Math.ceil(viewWidth / tileWidth);+const tilesDown = Math.ceil(viewHeight / tileHeight);+const topOffset = -tile.height / 2;+const focusX = viewWidth / 2;+const focusY = viewHeight / 2;+const revealRandom = mulberry32(hashSeed(`${cfg.seed}:reveal:${cfg.reveal}`));++// flood depths are unavailable offline; distance-only ordering ("bloom"-ish).+// Ordering shifts which run sits where, not the size of the numbers below.+const runs = [];+for (let row = -1; row <= tilesDown; row += 1) {+ for (let column = -1; column <= tilesAcross; column += 1) {+ const x = column * tileWidth;+ const y = row * tileHeight + topOffset * scale;+ if (x > viewWidth || y > viewHeight) continue;+ if (x + tileWidth < 0 || y + tileHeight < 0) continue;+ geometry.forEach((entry) => {+ const ax = clamp(x + entry.anchor[0], 0, viewWidth);+ const ay = clamp(y + entry.anchor[1], 0, viewHeight);+ runs.push({+ geometry: entry,+ metric: Math.hypot(ax - focusX, ay - focusY),+ jitter: revealRandom(),+ nudge: revealRandom(),+ });+ });+ }+}+runs.sort((a, b) => a.metric - b.metric || a.jitter - b.jitter);++const speed = (cfg.revealSpeed * scale) / 1000;+let longest = 0;+for (const run of runs) longest = Math.max(longest, run.geometry.length / speed);+const lengths = geometry.map((e) => e.length).sort((a, b) => a - b);+const median = Math.max(1, lengths[Math.floor(lengths.length / 2)] || 1);+const padWeight = median * 0.15;+let total = 0;+for (const run of runs) total += run.geometry.length + padWeight;+const window_ = Math.max(0, cfg.revealDuration - longest);++let cursor = 0;+for (const run of runs) {+ run.duration = run.geometry.length / speed;+ run.delay = Math.max(0, (cursor / total) * window_ + (run.nudge - 0.5) * REVEAL_JITTER);+ cursor += run.geometry.length + padWeight;+}+let stretch = Infinity;+for (const run of runs) {+ if (run.delay > 0) stretch = Math.min(stretch, (cfg.revealDuration - run.duration) / run.delay);+}+if (Number.isFinite(stretch) && stretch > 0) for (const run of runs) run.delay *= stretch;++const instances = runs.filter((r) => r.geometry.drawable).sort((a, b) => a.delay - b.delay);++const pct = (arr, p) => arr[Math.min(arr.length - 1, Math.floor(arr.length * p))];+const durs = instances.map((r) => r.duration).sort((a, b) => a - b);+console.log(`runs total ${runs.length}, drawable ${instances.length}, stretch ${stretch.toFixed(3)}`);+console.log(`longest route ${longest.toFixed(0)}ms, window ${window_.toFixed(0)}ms, padWeight ${padWeight.toFixed(1)}px`);+console.log(+ `route duration ms: min ${durs[0].toFixed(1)} p10 ${pct(durs, 0.1).toFixed(1)} ` ++ `median ${pct(durs, 0.5).toFixed(1)} p90 ${pct(durs, 0.9).toFixed(1)} max ${durs[durs.length - 1].toFixed(1)}`,+);+for (const f of [16.7, 33, 50]) {+ const n = durs.filter((d) => d <= f).length;+ console.log(` routes finishing within one ${f}ms frame: ${n} (${((100 * n) / durs.length).toFixed(1)}%)`);+}++// how far out of delay-order was the release queue BEFORE the sort?+let inversions = 0;+let worstBacklog = 0;+let peak = -Infinity;+const unsorted = runs.filter((r) => r.geometry.drawable);+for (let i = 0; i < unsorted.length; i += 1) {+ if (unsorted[i].delay < peak) {+ inversions += 1;+ worstBacklog = Math.max(worstBacklog, peak - unsorted[i].delay);+ }+ peak = Math.max(peak, unsorted[i].delay);+}+console.log(+ `delay-order before sorting: ${inversions}/${unsorted.length} out of order (${((100 * inversions) / unsorted.length).toFixed(1)}%), ` ++ `worst run held back ${worstBacklog.toFixed(0)}ms behind the queue head`,+);+const steps = [];+for (let i = 1; i < instances.length; i += 1) steps.push(instances[i].delay - instances[i - 1].delay);+steps.sort((a, b) => a - b);+console.log(`consecutive delay step: median ${pct(steps, 0.5).toFixed(2)}ms vs jitter amplitude ${(REVEAL_JITTER * stretch).toFixed(0)}ms`);++// --- simulate the real release + growth loop at a fixed frame clock ---+function simulate(frameMs, label) {+ for (const r of instances) {+ r.drawn = 0;+ r.startedAt = undefined;+ r.frames = 0;+ r.bornAt = 0;+ }+ const live = new Set();+ let next = 0;+ let time = 0;+ const bursts = [];+ const end = cfg.revealDuration + longest + 1000;+ while (time < end) {+ let released = 0;+ while (next < instances.length && instances[next].delay <= time) {+ const e = instances[next];+ e.startedAt = Math.max(e.delay, time - REVEAL_CATCHUP);+ live.add(e);+ next += 1;+ released += 1;+ }+ bursts.push(released);+ for (const run of [...live]) {+ const grown = Math.min(run.geometry.length, (time - run.startedAt) * speed);+ if (run.drawn === 0) run.bornAt = grown;+ if (grown > 0 && grown < run.geometry.length) run.frames += 1;+ run.drawn = grown;+ if (grown >= run.geometry.length) live.delete(run);+ }+ time += frameMs;+ }+ const popped = instances.filter((r) => r.frames <= 1);+ const bornWhole = instances.filter((r) => r.bornAt >= r.geometry.length - 0.01);+ bursts.sort((a, b) => b - a);+ const fr = instances.map((r) => r.frames).sort((a, b) => a - b);+ console.log(+ `\n@${frameMs}ms frames (${label}): partially-drawn frames per route — ` ++ `min ${fr[0]} p10 ${pct(fr, 0.1)} median ${pct(fr, 0.5)} p90 ${pct(fr, 0.9)}`,+ );+ console.log(+ ` routes animated in <=1 frame: ${popped.length}/${instances.length} ` ++ `(${((100 * popped.length) / instances.length).toFixed(1)}%) born fully grown: ${bornWhole.length}`,+ );+ console.log(` biggest single-frame release bursts: ${bursts.slice(0, 6).join(", ")}`);+}+simulate(16.7, "60fps");+simulate(33, "30fps");+simulate(60, "hitching");
src/circuit-animation-conductor.js+47−5@@ -33,6 +33,51 @@ function shuffle(random, values) { return values; } +function compareTraceDistance(a, b) {+ return a.distance - b.distance || a.index - b.index;+}++function compareTraceKey(distance, index, ranked) {+ return distance - ranked.distance || index - ranked.index;+}++function siftDownTraceDistance(heap, index) {+ while (true) {+ const left = index * 2 + 1;+ if (left >= heap.length) return;+ const right = left + 1;+ let largest = left;+ if (right < heap.length && compareTraceDistance(heap[left], heap[right]) < 0) largest = right;+ if (compareTraceDistance(heap[index], heap[largest]) >= 0) return;+ [heap[index], heap[largest]] = [heap[largest], heap[index]];+ index = largest;+ }+}++function nearestTraces(traces, origin, count) {+ if (!(count > 0)) return [];+ const nearest = [];+ for (let index = 0; index < traces.length; index += 1) {+ const trace = traces[index];+ const midpoint = trace.points[Math.floor(trace.points.length / 2)];+ const distance = Math.hypot(midpoint[0] - origin.x, midpoint[1] - origin.y);+ if (nearest.length < count) {+ nearest.push({ trace, distance, index });+ let child = nearest.length - 1;+ while (child > 0) {+ const parent = Math.floor((child - 1) / 2);+ if (compareTraceDistance(nearest[parent], nearest[child]) >= 0) break;+ [nearest[parent], nearest[child]] = [nearest[child], nearest[parent]];+ child = parent;+ }+ } else if (compareTraceKey(distance, index, nearest[0]) < 0) {+ nearest[0] = { trace, distance, index };+ siftDownTraceDistance(nearest, 0);+ }+ }+ return nearest.sort(compareTraceDistance);+}+ export function createConductorAnimation(svg, field, config, random) { const ambientLayer = svgElement("g", { "data-animation": "conductor-ambient", fill: "none", "pointer-events": "none",@@ -249,11 +294,8 @@ export function createConductorAnimation(svg, field, config, random) { }; const selectedColor = weighted(random, config.signalColors); ripple(source, selectedColor);- const ranked = field.traces.map((trace) => {- const midpoint = trace.points[Math.floor(trace.points.length / 2)];- return { trace, distance: Math.hypot(midpoint[0] - source.x, midpoint[1] - source.y) };- }).sort((a, b) => a.distance - b.distance);- const count = Math.min(ranked.length, Math.max(6, Math.round(6 + life() * 8)));+ const count = Math.min(field.traces.length, Math.max(6, Math.round(6 + life() * 8)));+ const ranked = nearestTraces(field.traces, source, count); const outerDistance = ranked[count - 1]?.distance || 1; for (let index = 0; index < count; index += 1) { const { trace, distance } = ranked[index];
src/circuit-animation-growth.jsadded+347@@ -0,0 +1,347 @@+const SVG_NS = "http://www.w3.org/2000/svg";++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x} ${y}`).join(" ");+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function brandColor(x, width) {+ const position = clamp(x / Math.max(1, width));+ if (position < 0.5) return `hsl(${176 + position * 58} 92% 63%)`;+ return `hsl(${205 + (position - 0.5) * 86} 91% 70%)`;+}++function clearRevealStyle(visual) {+ visual.path.setAttribute("d", visual.originalPathData);+ visual.path.removeAttribute("stroke-dasharray");+ visual.path.removeAttribute("stroke-dashoffset");+ visual.path.style.removeProperty("opacity");+ visual.path.style.removeProperty("will-change");+ for (const via of [visual.startVia, visual.endVia]) {+ via?.style.removeProperty("opacity");+ via?.style.removeProperty("will-change");+ }+}++export function createTraceGrowthAnimation(svg, field, config, random, { traceLayer = null } = {}) {+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const staticLayer = traceLayer || svg.querySelector("[data-static-traces]");+ const glowLayer = svgElement("g", {+ "data-animation": "trace-growth",+ "aria-hidden": "true",+ });+ glowLayer.style.mixBlendMode = "screen";+ svg.append(glowLayer);++ const traceGroups = [...staticLayer.querySelectorAll("[data-circuit-trace]")];+ const visuals = field.traces.map((trace, index) => {+ const group = traceGroups[index];+ return {+ index,+ trace,+ group,+ path: group.querySelector("[data-trace-path]"),+ startVia: group.querySelector('[data-trace-via="start"]'),+ endVia: group.querySelector('[data-trace-via="end"]'),+ sourceVia: null,+ destinationVia: null,+ overlay: null,+ startedAt: 0,+ duration: 0,+ desiredStart: 0,+ length: Math.max(1, trace.length),+ originalPathData: group.querySelector("[data-trace-path]").getAttribute("d"),+ revealed: true,+ };+ });++ let ordered = [];+ let active = new Map();+ let nextIndex = 0;+ let timelineStart = 0;+ let frameRequest = 0;+ let frameCount = 0;+ let lastFrameTime = 0;+ let running = false;+ let completed = true;++ const scale = Math.max(0.25, config.featureScale || 1);+ const life = clamp(config.liveliness || 0, 0, 1.5);+ const speedFactor = clamp(0.72 + life * 0.36, 0.72, 1.26);+ const glowStrength = clamp((config.growthGlow ?? 0.82) * (0.68 + life * 0.25), 0.1, 1.15);+ const maxActive = clamp(Math.round(16 + Math.sqrt(visuals.length) * 1.55), 22, 54);+ const targetFrameRate = visuals.length > 1200 ? 30 : visuals.length > 600 ? 45 : 60;+ const frameInterval = 1000 / targetFrameRate;++ function removeOverlay(visual) {+ visual.overlay?.group.remove();+ visual.overlay = null;+ }++ function completeVisual(visual) {+ if (visual.revealed) return;+ clearRevealStyle(visual);+ removeOverlay(visual);+ visual.revealed = true;+ }++ function finish() {+ if (completed && !running && active.size === 0) return;+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ running = false;+ completed = true;+ for (const visual of visuals) completeVisual(visual);+ glowLayer.replaceChildren();+ active.clear();+ nextIndex = ordered.length;+ }++ function prepareTimeline() {+ const requestedAngle = Number(config.growthAngle);+ const generatedAngle = Number(config.flowAngle);+ const angleDegrees = Number.isFinite(requestedAngle)+ ? requestedAngle+ : Number.isFinite(generatedAngle)+ ? generatedAngle+ : 24;+ const angle = (angleDegrees * Math.PI) / 180;+ const direction = [Math.cos(angle), Math.sin(angle)];+ const across = [-direction[1], direction[0]];+ const span = Math.max(field.width, field.height);+ const phase = random() * Math.PI * 2;+ const entries = visuals.map((visual) => {+ const points = visual.trace.points;+ const first = points[0];+ const last = points.at(-1);+ const midpoint = points[Math.floor(points.length / 2)];+ const potential = (point) => {+ const projection = point[0] * direction[0] + point[1] * direction[1];+ const cross = point[0] * across[0] + point[1] * across[1];+ return projection+ + Math.sin((cross / Math.max(1, span)) * Math.PI * 3.1 + phase) * span * 0.065;+ };+ const reverse = potential(first) > potential(last);+ const orientedPoints = reverse ? [...points].reverse() : points;+ visual.path.setAttribute("d", pathData(orientedPoints));+ visual.sourceVia = reverse ? visual.endVia : visual.startVia;+ visual.destinationVia = reverse ? visual.startVia : visual.endVia;++ const localVariation = (random() - 0.5) * span * 0.045;+ return { visual, key: potential(midpoint) + localVariation };+ });++ entries.sort((first, second) => first.key - second.key || first.visual.index - second.visual.index);+ const minimum = entries[0]?.key || 0;+ const maximum = entries.at(-1)?.key || minimum + 1;+ const duration = clamp(config.growthDuration ?? 7600, 2600, 18000) / speedFactor;+ const startWindow = Math.max(900, duration - 1750);+ const range = Math.max(1, maximum - minimum);+ const baseDurations = entries.map(({ visual }) => (+ clamp(260 + Math.pow(visual.length, 0.88) * 5.6, 420, 3200) / speedFactor+ ));+ const averageDuration = baseDurations.reduce((sum, value) => sum + value, 0)+ / Math.max(1, baseDurations.length);+ const targetAverage = maxActive * startWindow * 0.82 / Math.max(1, entries.length);+ const durationScale = clamp(targetAverage / Math.max(1, averageDuration), 0.05, 1);+ const minimumDuration = clamp(160 * Math.sqrt(360 / Math.max(1, entries.length)), 52, 180);++ for (const [rank, entry] of entries.entries()) {+ const spatial = clamp((entry.key - minimum) / range);+ const orderedRank = entries.length > 1 ? rank / (entries.length - 1) : 0;+ entry.visual.desiredStart = (spatial * 0.78 + orderedRank * 0.22) * startWindow;+ entry.visual.duration = clamp(+ baseDurations[rank] * durationScale,+ minimumDuration,+ 3200 / speedFactor,+ );+ }+ return entries.map((entry) => entry.visual);+ }++ function prepareVisuals() {+ for (const visual of visuals) {+ removeOverlay(visual);+ visual.path.setAttribute("stroke-dasharray", `${visual.length} ${visual.length + 1}`);+ visual.path.setAttribute("stroke-dashoffset", String(visual.length));+ visual.path.style.opacity = "0";+ visual.revealed = false;+ for (const via of [visual.startVia, visual.endVia]) {+ if (!via) continue;+ via.style.opacity = "0";+ }+ }+ }++ function createOverlay(visual) {+ const color = brandColor(+ visual.trace.points[Math.floor(visual.trace.points.length / 2)][0],+ field.width,+ );+ const headLength = clamp(visual.length * 0.16, 12 * scale, 42 * scale);+ const pathAttributes = {+ d: visual.path.getAttribute("d"),+ fill: "none",+ stroke: color,+ "stroke-linecap": "round",+ "stroke-linejoin": "round",+ "stroke-dasharray": `${headLength} ${visual.length + headLength}`,+ "stroke-dashoffset": headLength,+ };+ const group = svgElement("g", { "data-growth-active": visual.index });+ const halo = svgElement("path", {+ ...pathAttributes,+ "stroke-width": config.traceWidth * scale * 4.2,+ opacity: 0,+ });+ const core = svgElement("path", {+ ...pathAttributes,+ "stroke-width": config.traceWidth * scale * 1.35,+ opacity: 0,+ });+ const source = visual.trace.points[0];+ const destination = visual.trace.points.at(-1);+ const sourcePoint = visual.sourceVia === visual.startVia ? source : destination;+ const destinationPoint = visual.destinationVia === visual.endVia ? destination : source;+ const sourceRing = svgElement("circle", {+ cx: sourcePoint[0], cy: sourcePoint[1], r: config.viaOuterRadius * scale,+ fill: "none", stroke: color, "stroke-width": Math.max(0.8, config.traceWidth * scale), opacity: 0,+ });+ const destinationRing = svgElement("circle", {+ cx: destinationPoint[0], cy: destinationPoint[1], r: config.viaOuterRadius * scale,+ fill: "none", stroke: color, "stroke-width": Math.max(0.8, config.traceWidth * scale), opacity: 0,+ });+ group.append(halo, core, sourceRing, destinationRing);+ glowLayer.append(group);+ return { group, halo, core, sourceRing, destinationRing, headLength };+ }++ function activate(visual, timestamp) {+ visual.startedAt = timestamp;+ visual.overlay = createOverlay(visual);+ active.set(visual.index, visual);+ }++ function drawVisual(visual, timestamp) {+ const progress = clamp((timestamp - visual.startedAt) / visual.duration);+ const routed = smoothstep(progress);+ const drawn = visual.length * routed;+ const energy = Math.sin(Math.PI * progress) * glowStrength;+ const sourceEnergy = 1 - smoothstep(progress / 0.28);+ const destinationEnergy = smoothstep((progress - 0.76) / 0.24);+ const overlay = visual.overlay;++ visual.path.setAttribute("stroke-dashoffset", String(visual.length - drawn));+ visual.path.style.opacity = String(clamp(0.46 + routed * 0.54));+ if (visual.sourceVia) visual.sourceVia.style.opacity = String(smoothstep(progress / 0.12));+ if (visual.destinationVia) visual.destinationVia.style.opacity = String(destinationEnergy);++ const dashOffset = overlay.headLength - drawn;+ overlay.halo.setAttribute("stroke-dashoffset", String(dashOffset));+ overlay.core.setAttribute("stroke-dashoffset", String(dashOffset));+ overlay.halo.setAttribute("opacity", String(energy * 0.16));+ overlay.core.setAttribute("opacity", String(energy * 0.92));+ overlay.sourceRing.setAttribute("r", String(config.viaOuterRadius * scale * (1 + sourceEnergy * 1.9)));+ overlay.sourceRing.setAttribute("opacity", String(sourceEnergy * glowStrength * 0.72));+ overlay.destinationRing.setAttribute("r", String(config.viaOuterRadius * scale * (1 + destinationEnergy * 1.35)));+ overlay.destinationRing.setAttribute("opacity", String((1 - destinationEnergy) * destinationEnergy * 3.2 * glowStrength));++ if (progress < 1) return false;+ completeVisual(visual);+ return true;+ }++ function renderFrame(timestamp) {+ frameRequest = window.requestAnimationFrame(renderFrame);+ const frameElapsed = lastFrameTime ? timestamp - lastFrameTime : frameInterval;+ if (frameElapsed < frameInterval) return;+ lastFrameTime = lastFrameTime+ ? timestamp - (frameElapsed % frameInterval)+ : timestamp;+ frameCount += 1;+ const elapsed = timestamp - timelineStart;++ while (+ nextIndex < ordered.length+ && ordered[nextIndex].desiredStart <= elapsed+ && active.size < maxActive+ ) {+ activate(ordered[nextIndex], timestamp);+ nextIndex += 1;+ }++ for (const [index, visual] of active) {+ if (!drawVisual(visual, timestamp)) continue;+ active.delete(index);+ }++ if (nextIndex >= ordered.length && active.size === 0) finish();+ }++ function start() {+ finish();+ ordered = prepareTimeline();+ nextIndex = 0;+ frameCount = 0;+ lastFrameTime = 0;+ if (!config.motion || reducedMotion || life <= 0.02 || ordered.length === 0) return false;+ prepareVisuals();+ running = true;+ completed = false;+ timelineStart = performance.now();+ frameRequest = window.requestAnimationFrame(renderFrame);+ return true;+ }++ function stop() {+ finish();+ }++ function destroy() {+ finish();+ document.removeEventListener("visibilitychange", onVisibilityChange);+ glowLayer.remove();+ }++ function onVisibilityChange() {+ if (document.hidden && running) finish();+ }++ return {+ start,+ stop,+ trigger: start,+ destroy,+ get stats() {+ return {+ system: "trace-growth",+ animationNodes: glowLayer.childElementCount,+ activeTraces: active.size,+ revealedTraces: nextIndex - active.size,+ traceCount: visuals.length,+ maximumActiveTraces: maxActive,+ targetFrameRate,+ frameCount,+ running,+ completed,+ reducedMotion,+ };+ },+ };++ document.addEventListener("visibilitychange", onVisibilityChange);+}
src/circuit-animation-handshake.js+20−5@@ -1,4 +1,6 @@ const TAU = Math.PI * 2;+const CANVAS_PIXEL_BUDGET = 1_450_000;+const CONTINUOUS_CANVAS_MAX_DIMENSION = 8192; function clamp(value, minimum = 0, maximum = 1) { return Math.max(minimum, Math.min(maximum, value));@@ -84,8 +86,19 @@ export function createHandshakeAnimation(mount, field, config, random, { reading const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; const pixelWidth = Math.max(1, mount.clientWidth); const pixelHeight = Math.max(1, mount.clientHeight);- const pixelBudgetRatio = Math.sqrt(1_450_000 / Math.max(1, pixelWidth * pixelHeight));- const pixelRatio = Math.max(1, Math.min(window.devicePixelRatio || 1, 1.5, pixelBudgetRatio));+ const pixelBudgetRatio = Math.sqrt(CANVAS_PIXEL_BUDGET / Math.max(1, pixelWidth * pixelHeight));+ const legacyPixelRatio = Math.max(0.45, Math.min(window.devicePixelRatio || 1, 1.5, pixelBudgetRatio));+ const continuousGeneration = config.continuousGeneration === true;+ const pixelRatio = continuousGeneration+ ? Math.min(+ window.devicePixelRatio || 1,+ 1.5,+ pixelBudgetRatio,+ CONTINUOUS_CANVAS_MAX_DIMENSION / pixelWidth,+ CONTINUOUS_CANVAS_MAX_DIMENSION / pixelHeight,+ )+ : legacyPixelRatio;+ const roundDimension = continuousGeneration ? Math.floor : Math.round; const canvas = document.createElement("canvas"); canvas.setAttribute("aria-hidden", "true"); canvas.setAttribute("data-animation", "via-handshake-canvas");@@ -99,13 +112,15 @@ export function createHandshakeAnimation(mount, field, config, random, { reading zIndex: "1", contain: "strict", });- canvas.width = Math.max(1, Math.round(pixelWidth * pixelRatio));- canvas.height = Math.max(1, Math.round(pixelHeight * pixelRatio));+ canvas.width = Math.max(1, roundDimension(pixelWidth * pixelRatio));+ canvas.height = Math.max(1, roundDimension(pixelHeight * pixelRatio)); mount.appendChild(canvas); const context = canvas.getContext("2d", { alpha: true, desynchronized: true }) || canvas.getContext("2d");- const targetFrameRate = canvas.width * canvas.height > 1_200_000 ? 30 : 45;+ const frameRatePixelCount = Math.max(1, Math.round(pixelWidth * legacyPixelRatio))+ * Math.max(1, Math.round(pixelHeight * legacyPixelRatio));+ const targetFrameRate = frameRatePixelCount > 1_200_000 ? 30 : 45; const frameInterval = 1000 / targetFrameRate; const scale = Math.max(0.25, config.featureScale); const maxTransactions = Math.max(1, Math.min(4, Math.round(config.maxHandshakes || 3)));
src/circuit-animation-reflection.jsadded+604@@ -0,0 +1,604 @@+const TAU = Math.PI * 2;+const CANVAS_PIXEL_BUDGET = 1_500_000;+const CONTINUOUS_CANVAS_MAX_DIMENSION = 8192;++export const REFLECTION_DEFAULTS = Object.freeze({+ reflectionStrength: 0.58,+ reflectionCycle: 14800,+ reflectionWidth: 0.3,+ reflectionAngle: 18,+ reflectionDrift: 6,+ reflectionRest: 0.12,+ reflectionQuiet: 0.84,+ reflectionPointer: true,+ reflectionColors: Object.freeze(["#00e6dc", "#49a9ff", "#a58cff"]),+});++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function colorWithAlpha(color, alpha) {+ const amount = clamp(alpha);+ const hexadecimal = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(color).trim());+ if (hexadecimal) {+ const value = hexadecimal[1].length === 3+ ? hexadecimal[1].split("").map((character) => `${character}${character}`).join("")+ : hexadecimal[1];+ const red = Number.parseInt(value.slice(0, 2), 16);+ const green = Number.parseInt(value.slice(2, 4), 16);+ const blue = Number.parseInt(value.slice(4, 6), 16);+ return `rgba(${red}, ${green}, ${blue}, ${amount})`;+ }++ const rgb = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(String(color));+ if (rgb) return `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${amount})`;+ return amount < 0.001 ? "rgba(0, 0, 0, 0)" : color;+}++function paletteFor(settings) {+ const colors = Array.isArray(settings.reflectionColors)+ ? settings.reflectionColors.filter(Boolean)+ : [];+ return [+ colors[0] || REFLECTION_DEFAULTS.reflectionColors[0],+ colors[1] || colors[0] || REFLECTION_DEFAULTS.reflectionColors[1],+ colors[2] || colors[1] || colors[0] || REFLECTION_DEFAULTS.reflectionColors[2],+ ];+}++function tracePath(context, points) {+ if (!points?.length) return false;+ context.beginPath();+ context.moveTo(points[0][0], points[0][1]);+ for (let index = 1; index < points.length; index += 1) {+ context.lineTo(points[index][0], points[index][1]);+ }+ context.stroke();+ return true;+}++function projectionRange(width, height, xAxis, yAxis) {+ const projections = [+ 0,+ width * xAxis,+ height * yAxis,+ width * xAxis + height * yAxis,+ ];+ return {+ minimum: Math.min(...projections),+ maximum: Math.max(...projections),+ };+}++export function createReflectionAnimation(+ mount,+ field,+ config = {},+ random = Math.random,+ { readingZone = null } = {},+) {+ if (!mount?.appendChild) throw new TypeError("mount must be a DOM element");+ if (!field?.traces || !Number.isFinite(field.width) || !Number.isFinite(field.height)) {+ throw new TypeError("field must contain width, height, and traces");+ }++ let settings = { ...REFLECTION_DEFAULTS, ...config };+ const randomValue = typeof random === "function" ? random : Math.random;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ let destroyed = false;+ let requested = false;+ let running = false;+ let frameRequest;+ let frameCount = 0;+ let lastPaintTime = 0;+ let targetFrameRate = 45;+ let frameInterval = 1000 / targetFrameRate;+ let pixelRatio = 1;+ let pointer = null;+ let sweepVisible = false;+ const pulses = [];+ const phaseOffset = randomValue() * Math.max(1000, settings.reflectionCycle);++ const canvas = document.createElement("canvas");+ canvas.setAttribute("aria-hidden", "true");+ canvas.setAttribute("data-animation", "adom-reflection-canvas");+ Object.assign(canvas.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ zIndex: "1",+ contain: "strict",+ mixBlendMode: config.reflectionBlendMode || "screen",+ });+ mount.appendChild(canvas);++ const context = canvas.getContext("2d", { alpha: true, desynchronized: true })+ || canvas.getContext("2d");+ const maskCanvas = document.createElement("canvas");+ let maskContext = maskCanvas.getContext("2d", { alpha: true });++ function life() {+ return clamp(Number(settings.liveliness) || 0, 0, 1.5);+ }++ function featureScale() {+ return Math.max(0.25, Number(settings.featureScale) || 1);+ }++ function shouldRun() {+ return !destroyed+ && !reducedMotion+ && settings.motion !== false+ && life() > 0.02+ && Boolean(context);+ }++ function readingEllipse() {+ const mountRect = mount.getBoundingClientRect();+ const zoneRect = readingZone?.getBoundingClientRect?.();+ if (+ zoneRect+ && mountRect.width > 0+ && mountRect.height > 0+ && zoneRect.width > 0+ && zoneRect.height > 0+ ) {+ const scaleX = field.width / mountRect.width;+ const scaleY = field.height / mountRect.height;+ const paddingX = Math.max(52, zoneRect.width * 0.14);+ const paddingY = Math.max(38, zoneRect.height * 0.17);+ return {+ x: (zoneRect.left + zoneRect.width * 0.5 - mountRect.left) * scaleX,+ y: (zoneRect.top + zoneRect.height * 0.5 - mountRect.top) * scaleY,+ radiusX: (zoneRect.width * 0.5 + paddingX) * scaleX,+ radiusY: (zoneRect.height * 0.5 + paddingY) * scaleY,+ };+ }++ return {+ x: field.width * 0.5,+ y: field.height * 0.48,+ radiusX: field.width * 0.34,+ radiusY: field.height * 0.28,+ };+ }++ function removeViaHoles() {+ const innerRadius = Math.max(0, Number(settings.viaInnerRadius) || 0) * featureScale();+ if (innerRadius <= 0) return;+ maskContext.globalCompositeOperation = "destination-out";+ for (const trace of field.traces) {+ const endpoints = [];+ if (trace.viaStart && trace.points?.length) endpoints.push(trace.points[0]);+ if (trace.viaEnd && trace.points?.length) endpoints.push(trace.points.at(-1));+ for (const point of endpoints) {+ maskContext.beginPath();+ maskContext.arc(point[0], point[1], innerRadius, 0, TAU);+ maskContext.fill();+ }+ }+ }++ function softenReadingZone() {+ const strength = clamp(Number(settings.reflectionQuiet), 0, 0.98);+ if (strength <= 0) return;+ const quiet = readingEllipse();+ const layers = 10;+ const layerAlpha = 1 - ((1 - strength) ** (1 / layers));+ maskContext.globalCompositeOperation = "destination-out";+ maskContext.fillStyle = "#000";+ maskContext.globalAlpha = layerAlpha;+ for (let index = 0; index < layers; index += 1) {+ const amount = index / (layers - 1);+ const size = 1 - amount * 0.58;+ maskContext.beginPath();+ maskContext.ellipse(+ quiet.x,+ quiet.y,+ Math.max(1, quiet.radiusX * size),+ Math.max(1, quiet.radiusY * size),+ 0,+ 0,+ TAU,+ );+ maskContext.fill();+ }+ maskContext.globalAlpha = 1;+ }++ function buildMask() {+ if (!maskContext || !maskCanvas.width || !maskCanvas.height) return;+ maskContext.setTransform(1, 0, 0, 1, 0, 0);+ maskContext.clearRect(0, 0, maskCanvas.width, maskCanvas.height);+ maskContext.setTransform(+ maskCanvas.width / field.width,+ 0,+ 0,+ maskCanvas.height / field.height,+ 0,+ 0,+ );+ maskContext.globalCompositeOperation = "source-over";+ maskContext.globalAlpha = 1;+ maskContext.strokeStyle = "#fff";+ maskContext.fillStyle = "#fff";+ maskContext.lineWidth = Math.max(0.2, Number(settings.traceWidth) || 1.58) * featureScale();+ maskContext.lineCap = "butt";+ maskContext.lineJoin = "miter";++ for (const trace of field.traces) tracePath(maskContext, trace.points);++ const outerRadius = Math.max(0, Number(settings.viaOuterRadius) || 0) * featureScale();+ if (outerRadius > 0) {+ for (const trace of field.traces) {+ const endpoints = [];+ if (trace.viaStart && trace.points?.length) endpoints.push(trace.points[0]);+ if (trace.viaEnd && trace.points?.length) endpoints.push(trace.points.at(-1));+ for (const point of endpoints) {+ maskContext.beginPath();+ maskContext.arc(point[0], point[1], outerRadius, 0, TAU);+ maskContext.fill();+ }+ }+ }++ removeViaHoles();+ softenReadingZone();+ maskContext.setTransform(1, 0, 0, 1, 0, 0);+ maskContext.globalCompositeOperation = "source-over";+ maskContext.globalAlpha = 1;+ }++ function sizeCanvases() {+ const width = Math.max(1, mount.clientWidth);+ const height = Math.max(1, mount.clientHeight);+ const pixelBudgetRatio = Math.sqrt(CANVAS_PIXEL_BUDGET / Math.max(1, width * height));+ const legacyPixelRatio = clamp(+ Math.min(window.devicePixelRatio || 1, 1.5, pixelBudgetRatio),+ 0.45,+ 1.5,+ );+ const continuousGeneration = settings.continuousGeneration === true;+ pixelRatio = continuousGeneration+ ? Math.min(+ window.devicePixelRatio || 1,+ 1.5,+ pixelBudgetRatio,+ CONTINUOUS_CANVAS_MAX_DIMENSION / width,+ CONTINUOUS_CANVAS_MAX_DIMENSION / height,+ )+ : legacyPixelRatio;+ const roundDimension = continuousGeneration ? Math.floor : Math.round;+ const nextWidth = Math.max(1, roundDimension(width * pixelRatio));+ const nextHeight = Math.max(1, roundDimension(height * pixelRatio));+ if (canvas.width !== nextWidth) canvas.width = nextWidth;+ if (canvas.height !== nextHeight) canvas.height = nextHeight;+ if (maskCanvas.width !== nextWidth) maskCanvas.width = nextWidth;+ if (maskCanvas.height !== nextHeight) maskCanvas.height = nextHeight;+ if (context) {+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, canvas.width, canvas.height);+ }+ const frameRatePixelCount = Math.max(1, Math.round(width * legacyPixelRatio))+ * Math.max(1, Math.round(height * legacyPixelRatio));+ targetFrameRate = frameRatePixelCount > 1_100_000 ? 30 : 45;+ frameInterval = 1000 / targetFrameRate;+ buildMask();+ }++ function reflectionStrength() {+ const configured = clamp(Number(settings.reflectionStrength), 0, 1.4);+ return configured * clamp(0.56 + life() * 0.34, 0.32, 1);+ }++ function drawSweep(timestamp) {+ const cycle = Math.max(4800, Number(settings.reflectionCycle) || REFLECTION_DEFAULTS.reflectionCycle)+ / clamp(0.84 + life() * 0.12, 0.72, 1.1);+ const rest = clamp(Number(settings.reflectionRest), 0, 0.42);+ const travelPortion = 1 - rest;+ const phase = ((timestamp + phaseOffset) % cycle) / cycle;+ if (phase >= travelPortion) {+ sweepVisible = false;+ return;+ }++ sweepVisible = true;+ const progress = phase / travelPortion;+ const easedProgress = clamp(progress + Math.sin(progress * TAU) * 0.038);+ const drift = (Number(settings.reflectionDrift) || 0)+ * Math.sin(timestamp / 23000 * TAU + phaseOffset / cycle * TAU);+ const angle = ((Number(settings.reflectionAngle) || 0) + drift) * Math.PI / 180;+ const xAxis = Math.cos(angle);+ const yAxis = Math.sin(angle);+ const range = projectionRange(field.width, field.height, xAxis, yAxis);+ const diagonal = Math.hypot(field.width, field.height);+ const width = diagonal * clamp(Number(settings.reflectionWidth), 0.08, 0.72);+ const center = range.minimum - width+ + easedProgress * (range.maximum - range.minimum + width * 2);+ const palette = paletteFor(settings);+ const strength = reflectionStrength();++ const start = center - width * 0.5;+ const end = center + width * 0.5;+ const sheen = context.createLinearGradient(+ xAxis * start,+ yAxis * start,+ xAxis * end,+ yAxis * end,+ );+ sheen.addColorStop(0, colorWithAlpha(palette[0], 0));+ sheen.addColorStop(0.14, colorWithAlpha(palette[0], 0.12));+ sheen.addColorStop(0.31, colorWithAlpha(palette[0], 0.82));+ sheen.addColorStop(0.5, colorWithAlpha(palette[1], 1));+ sheen.addColorStop(0.7, colorWithAlpha(palette[2], 0.76));+ sheen.addColorStop(0.88, colorWithAlpha(palette[2], 0.1));+ sheen.addColorStop(1, colorWithAlpha(palette[2], 0));+ context.globalAlpha = strength;+ context.fillStyle = sheen;+ context.fillRect(0, 0, field.width, field.height);++ const edgeWidth = width * 0.1;+ const edgeCenter = center - width * 0.035;+ const edge = context.createLinearGradient(+ xAxis * (edgeCenter - edgeWidth),+ yAxis * (edgeCenter - edgeWidth),+ xAxis * (edgeCenter + edgeWidth),+ yAxis * (edgeCenter + edgeWidth),+ );+ edge.addColorStop(0, colorWithAlpha(palette[0], 0));+ edge.addColorStop(0.44, colorWithAlpha(palette[1], 0.28));+ edge.addColorStop(0.5, colorWithAlpha("#c9ffff", 0.88));+ edge.addColorStop(0.57, colorWithAlpha(palette[2], 0.24));+ edge.addColorStop(1, colorWithAlpha(palette[2], 0));+ context.globalAlpha = strength * 0.24;+ context.fillStyle = edge;+ context.fillRect(0, 0, field.width, field.height);+ }++ function drawPointerReflection(timestamp) {+ if (!settings.reflectionPointer || !pointer) return;+ const age = timestamp - pointer.at;+ if (age < 0 || age > 1800) return;+ const fade = 1 - smoothstep(age / 1800);+ const radius = Math.hypot(field.width, field.height) * 0.085;+ const palette = paletteFor(settings);+ const glow = context.createRadialGradient(+ pointer.x,+ pointer.y,+ 0,+ pointer.x,+ pointer.y,+ radius,+ );+ glow.addColorStop(0, colorWithAlpha(palette[0], 0.7));+ glow.addColorStop(0.42, colorWithAlpha(palette[1], 0.32));+ glow.addColorStop(1, colorWithAlpha(palette[2], 0));+ context.globalAlpha = reflectionStrength() * fade * 0.2;+ context.fillStyle = glow;+ context.fillRect(+ pointer.x - radius,+ pointer.y - radius,+ radius * 2,+ radius * 2,+ );+ }++ function drawPulses(timestamp) {+ const diagonal = Math.hypot(field.width, field.height);+ const palette = paletteFor(settings);+ for (let index = pulses.length - 1; index >= 0; index -= 1) {+ const pulse = pulses[index];+ const progress = (timestamp - pulse.startedAt) / pulse.duration;+ if (progress >= 1) {+ pulses.splice(index, 1);+ continue;+ }+ const eased = smoothstep(progress);+ const radius = diagonal * (0.025 + eased * 0.22);+ const ring = context.createRadialGradient(+ pulse.x,+ pulse.y,+ 0,+ pulse.x,+ pulse.y,+ radius,+ );+ ring.addColorStop(0, colorWithAlpha(pulse.color, 0));+ ring.addColorStop(0.58, colorWithAlpha(pulse.color, 0));+ ring.addColorStop(0.78, colorWithAlpha(pulse.color, 0.64));+ ring.addColorStop(0.9, colorWithAlpha(palette[1], 0.34));+ ring.addColorStop(1, colorWithAlpha(palette[2], 0));+ context.globalAlpha = reflectionStrength() * (1 - smoothstep(progress)) * 0.5;+ context.fillStyle = ring;+ context.fillRect(+ pulse.x - radius,+ pulse.y - radius,+ radius * 2,+ radius * 2,+ );+ }+ }++ function paint(timestamp) {+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, canvas.width, canvas.height);+ context.setTransform(+ canvas.width / field.width,+ 0,+ 0,+ canvas.height / field.height,+ 0,+ 0,+ );+ context.globalCompositeOperation = "source-over";+ drawSweep(timestamp);+ drawPointerReflection(timestamp);+ drawPulses(timestamp);++ context.setTransform(1, 0, 0, 1, 0, 0);+ context.globalAlpha = 1;+ context.globalCompositeOperation = "destination-in";+ context.drawImage(maskCanvas, 0, 0);+ context.globalCompositeOperation = "source-over";+ }++ function renderFrame(timestamp) {+ if (!running || destroyed || !canvas.isConnected) return;+ frameRequest = window.requestAnimationFrame(renderFrame);+ const elapsed = lastPaintTime ? timestamp - lastPaintTime : frameInterval;+ if (elapsed < frameInterval) return;+ lastPaintTime = lastPaintTime ? timestamp - (elapsed % frameInterval) : timestamp;+ frameCount += 1;+ paint(timestamp);+ }++ function halt(clear = true) {+ running = false;+ window.cancelAnimationFrame(frameRequest);+ frameRequest = undefined;+ lastPaintTime = 0;+ if (clear && context) {+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, canvas.width, canvas.height);+ }+ }++ function begin() {+ if (running || !requested || !shouldRun() || document.hidden) return;+ running = true;+ lastPaintTime = 0;+ frameRequest = window.requestAnimationFrame(renderFrame);+ }++ function start() {+ requested = true;+ begin();+ }++ function stop() {+ requested = false;+ halt();+ }++ function pointerMoved(point) {+ pointer = point ? { ...point, at: performance.now() } : null;+ }++ function pointerLeft() {+ if (pointer) pointer.at = performance.now() - 1800;+ }++ function trigger(origin = null) {+ if (!running || reducedMotion || settings.motion === false) return false;+ const point = origin || {+ x: field.width * (0.2 + randomValue() * 0.6),+ y: field.height * (0.22 + randomValue() * 0.56),+ };+ const palette = paletteFor(settings);+ const colorIndex = clamp(Math.floor(point.x / Math.max(1, field.width) * 3), 0, 2);+ if (pulses.length >= 2) pulses.shift();+ pulses.push({+ x: clamp(point.x, 0, field.width),+ y: clamp(point.y, 0, field.height),+ color: palette[colorIndex],+ startedAt: performance.now(),+ duration: 1180,+ });+ return true;+ }++ function update(nextConfig = {}) {+ if (destroyed) return api;+ settings = { ...settings, ...nextConfig };+ canvas.style.mixBlendMode = settings.reflectionBlendMode || "screen";+ sizeCanvases();+ if (!shouldRun()) halt();+ else if (requested) begin();+ return api;+ }++ function resize() {+ if (!destroyed) sizeCanvases();+ return api;+ }++ function onPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) halt();+ else if (requested) begin();+ }++ function onVisibilityChange() {+ if (document.hidden) halt(false);+ else if (requested) begin();+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ stop();+ pulses.length = 0;+ pointer = null;+ document.removeEventListener("visibilitychange", onVisibilityChange);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onPreferenceChange);+ } else {+ motionPreference.removeListener?.(onPreferenceChange);+ }+ canvas.remove();+ canvas.width = 0;+ canvas.height = 0;+ maskCanvas.width = 0;+ maskCanvas.height = 0;+ maskContext = null;+ }++ const api = {+ start,+ stop,+ destroy,+ update,+ resize,+ pointerMoved,+ pointerLeft,+ clicked: trigger,+ trigger,+ get stats() {+ return {+ system: "adom-reflection",+ renderer: "canvas-precomposed-trace-mask",+ animationNodes: canvas.isConnected ? 1 : 0,+ activeReflections: Number(sweepVisible) + pulses.length,+ activePulses: pulses.length,+ frameCount,+ targetFrameRate,+ rendererPixelRatio: pixelRatio,+ maskTraceCount: field.traces.length,+ perFrameTraceBudget: 0,+ quietZoneProtected: true,+ readingZoneTracked: Boolean(readingZone),+ reducedMotion,+ running,+ };+ },+ };++ sizeCanvases();+ document.addEventListener("visibilitychange", onVisibilityChange);+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onPreferenceChange);+ } else {+ motionPreference.addListener?.(onPreferenceChange);+ }+ return api;+}
src/circuit-background-reveal.jsadded+2779@@ -0,0 +1,2779 @@+const SVG_NS = "http://www.w3.org/2000/svg";++// Geometry constants measured from the reference artwork (adom.inc hero):+// a 114 x 57 cell routing grid with a 150/19 ~= 7.895 unit pitch, 1.58 unit+// traces, and 3.34 / 1.76 annular vias sitting exactly on grid nodes.+const DEFAULTS = Object.freeze({+ seed: "traces",+ tileWidth: 900,+ tileHeight: 450,+ pitch: 150 / 19,+ scale: 1000 / 900,+ density: 1.05,+ traceColor: "#151b25",+ traceWidth: 1.58,+ viaOuterRadius: 3.34,+ viaInnerRadius: 1.76,+ // --- generation tuning -----------------------------------------------+ formations: 96, // terminal groups (via ladders/rows) per tile+ busWidth: 1, // scales pins per formation => bundle width+ turnPenalty: 0.55, // higher = longer, calmer runs+ weave: 0.22, // preference for 2-lane spacing between neighbors+ cramp: 0.4, // aversion to 1-lane spacing outside bundles+ horizontalBias: 0.6, // 0.5 = isotropic, higher = more horizontal flow+ netReach: 42, // max cells a net may span+ jogBias: 5, // preferred endpoint misalignment => staircase jogs+ stubChance: 0, // leftover pins that get short escape stubs+ inlineViaChance: 0.03, // per-step chance of a mid-trace via+ combs: 8, // max tap-comb motifs per tile+ signalColors: [+ ["#00e6dc", 0.6],+ ["#64abff", 0.25],+ ["#c5b3ff", 0.15],+ ],+ signals: true,+ interactive: true,+ // --- reveal: the board etching itself in instead of appearing whole ----+ reveal: "flood", // off | etch | flood | sweep | bloom | scatter+ revealDuration: 3400, // ms from the first trace starting to the last one landing+ revealSpeed: 420, // units/sec a tip travels — the same pace as signalSpeed+ revealHead: 46, // units of lit copper behind the tip (a signal's head is 120)+ revealBlip: 500, // ms for a pad to land and ring out, matching the signal blip+ revealSpark: true, // white-hot tip riding the growing end of each trace+ // Copper reads as COOLING METAL, not a lit wire: a near-white tip, the zone's+ // colour just behind it, then an exponential fade to a dim settled trace.+ // Growth is coloured by a smooth screen-space field over this ramp, so the+ // board comes in as broad regions of hue instead of one flat neon sheet.+ revealPalette: ["#00e6dc", "#64abff", "#c5b3ff"], // the signal palette, exactly+ revealTip: "#e8fffd", // the hottest point, at the growing end+ revealZone: 380, // px scale of the colour regions (bigger = broader zones)+ revealSwell: 1.35, // how much fatter copper is while hot+ revealBloom: 0.18, // opacity of the wide glow around the tip+ // ms time constant for laid copper to fade to settled. 25 is the shortest the+ // engine can honour — the tail's tightening floors at 24 — and leaves a wake+ // of roughly a tip-length behind each route rather than a warm board.+ revealCool: 25,+ revealSettle: 1, // how far settled copper sits toward the board colour; 1 =+ // exactly the artwork, which is what makes the handoff invisible. Lower it+ // for a tinted board while it grows, at the cost of a visible swap.+ signalInterval: 240, // passive spawn cadence — a fresh signal appears near the cursor this often+ maxSignals: 12, // fill target for the ambient fountain (maxBurstSignals is the hard ceiling)+ spawnRadius: 110, // spawn scatter around the pointer (soft jitter, not a hard cutoff)+ signalSpeed: 420,+ signalLength: 120,+ burstBoost: 7, // click: how many extra signals join at once+ hopSurvival: 0.4, // per-hop survival for PASSIVE signals; low = short-lived, high = long chains+ burstSurvival: 0.72, // per-hop survival for CLICKED signals — tuned independently of hopSurvival+ hopRadius: 440, // a surviving signal hops to a via within this range+ colorDrift: 0.18, // chance per hop that a chain crossfades to a new color+ maxBurstSignals: 25,+});++// 8 directions, clockwise from east; even indices are cardinal.+const DIR8 = [+ [1, 0],+ [1, 1],+ [0, 1],+ [-1, 1],+ [-1, 0],+ [-1, -1],+ [0, -1],+ [1, -1],+];++// Walker start-direction weights derived from horizontalBias (0.5 = even).+function startDirectionWeights(horizontalBias) {+ const ew = 0.48 * horizontalBias;+ const ns = 0.24 * (1 - horizontalBias);+ const diagonal = Math.max(0.005, (1 - 2 * ew - 2 * ns) / 4);+ return [+ [0, ew],+ [4, ew],+ [2, ns],+ [6, ns],+ [1, diagonal],+ [3, diagonal],+ [5, diagonal],+ [7, diagonal],+ ];+}++let instanceCount = 0;++function svgEl(name, attrs = {}) {+ const node = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attrs)) {+ node.setAttribute(key, String(value));+ }+ return node;+}++function hashSeed(input) {+ let hash = 2166136261;+ for (const char of String(input)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function weightedChoice(random, entries) {+ let roll = random();+ for (const [value, weight] of entries) {+ roll -= weight;+ if (roll <= 0) return value;+ }+ return entries[0][0];+}++// --- routing engine ---------------------------------------------------------+//+// Occupancy lives on a doubled ("half step") grid wrapped on a torus: every+// cell step claims its end node and the midpoint it crosses, which blocks+// same-lane overlap and any crossing (two diagonals share a midpoint, a+// diagonal crosses a cardinal only through a node). The torus wrap is what+// makes the finished tile seamless.++function createRouter(random, columns, rows) {+ const wide = columns * 2;+ const tall = rows * 2;+ // Occupancy as a flat typed array — this sits in the A* hot path.+ const occupied = new Uint8Array(wide * tall);+ const viaNodes = new Uint8Array(wide * tall);++ const halfKey = (hx, hy) => (((hy % tall) + tall) % tall) * wide + (((hx % wide) + wide) % wide);+ const nodeKey = (x, y) => halfKey(x * 2, y * 2);++ function claim(trace, key) {+ occupied[key] = 1;+ trace.claims.push(key);+ trace.ownKeys.add(key);+ }++ return {+ columns,+ rows,+ nodeKey,+ nodeFree: (x, y) => !occupied[nodeKey(x, y)],+ crowding(x, y) {+ let count = 0;+ for (let dy = -4; dy <= 4; dy += 2) {+ for (let dx = -4; dx <= 4; dx += 2) {+ if (occupied[nodeKey(x + dx, y + dy)]) count += 1;+ }+ }+ return count;+ },+ stepFree(x, y, direction) {+ const [dx, dy] = DIR8[direction];+ return (+ !occupied[halfKey(x * 2 + dx, y * 2 + dy)] &&+ !occupied[halfKey(x * 2 + dx * 2, y * 2 + dy * 2)]+ );+ },+ // Like stepFree, but the destination node may be the (already-claimed)+ // goal pin the route is allowed to land on.+ routeStepFree(x, y, direction, goalKey) {+ const [dx, dy] = DIR8[direction];+ if (occupied[halfKey(x * 2 + dx, y * 2 + dy)]) return false;+ const node = halfKey(x * 2 + dx * 2, y * 2 + dy * 2);+ return node === goalKey || !occupied[node];+ },+ // How close the nearest parallel neighbor sits, perpendicular to travel:+ // 1 = one lane away (cramped), 2 = two lanes away (the reference's even+ // weave), 0 = open field. The A* cost prefers 2 and avoids 1.+ laneNeighbors(x, y, direction) {+ const [dx, dy] = DIR8[direction];+ if (occupied[nodeKey(x - dy, y + dx)] || occupied[nodeKey(x + dy, y - dx)]) return 1;+ if (occupied[nodeKey(x - dy * 2, y + dx * 2)] || occupied[nodeKey(x + dy * 2, y - dx * 2)]) return 2;+ return 0;+ },+ claimNode(trace, x, y) {+ claim(trace, nodeKey(x, y));+ },+ claimStep(trace, x, y, direction) {+ const [dx, dy] = DIR8[direction];+ claim(trace, halfKey(x * 2 + dx, y * 2 + dy));+ let count = 1;+ const node = halfKey(x * 2 + dx * 2, y * 2 + dy * 2);+ if (!occupied[node]) {+ claim(trace, node);+ count = 2;+ }+ trace.stepClaims.push(count);+ },+ // Remove the record's most recent step and exactly the claims it made.+ // Only valid while nothing later than that step has claimed (sealEnd+ // never trims past the record's own last via).+ unclaimLastStep(record) {+ const count = record.stepClaims.pop() || 0;+ for (let index = 0; index < count; index += 1) {+ const key = record.claims.pop();+ occupied[key] = 0;+ record.ownKeys.delete(key);+ }+ const step = record.steps.pop();+ record.end = [record.end[0] - DIR8[step][0], record.end[1] - DIR8[step][1]];+ },+ // A via may not sit on or cardinally beside another via (their annular+ // rings would overlap at one-pitch spacing), and the four diagonal+ // midpoints around it must not carry someone else's trace.+ viaAllowed(trace, x, y) {+ for (const [dx, dy] of [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]) {+ if (viaNodes[nodeKey(x + dx, y + dy)]) return false;+ }+ for (const [dx, dy] of [[1, 1], [1, -1], [-1, 1], [-1, -1]]) {+ const key = halfKey(x * 2 + dx, y * 2 + dy);+ if (occupied[key] && !trace.ownKeys.has(key)) return false;+ }+ return true;+ },+ placeVia(trace, x, y) {+ viaNodes[nodeKey(x, y)] = 1;+ trace.viaCells.push([x, y]);+ trace.viaSteps.add(trace.steps.length);+ for (const [dx, dy] of [[1, 1], [1, -1], [-1, 1], [-1, -1]]) {+ const key = halfKey(x * 2 + dx, y * 2 + dy);+ if (!occupied[key]) claim(trace, key);+ }+ },+ rollback(trace) {+ for (const key of trace.claims) occupied[key] = 0;+ for (const [x, y] of trace.viaCells) viaNodes[nodeKey(x, y)] = 0;+ },+ };+}++function newTraceRecord(x, y) {+ return {+ start: [x, y],+ end: [x, y],+ steps: [],+ claims: [],+ stepClaims: [], // claims added per step, so ends can be trimmed precisely+ ownKeys: new Set(),+ viaCells: [],+ viaSteps: new Set(),+ };+}++// Every trace must end on a via. If the end position has no clearance, trim+// the trace back one step at a time (never past its own last via) until a+// via fits. Returns false when no compliant ending exists.+function sealEnd(router, record, minSteps) {+ for (;;) {+ if (record.viaSteps.has(record.steps.length)) return true;+ const [x, y] = record.end;+ if (router.viaAllowed(record, x, y)) {+ router.placeVia(record, x, y);+ return true;+ }+ const floor = Math.max(minSteps, record.viaSteps.size ? Math.max(...record.viaSteps) : 0);+ if (record.steps.length <= floor) return false;+ router.unclaimLastStep(record);+ }+}++// --- A* net router ----------------------------------------------------------+//+// Routes run between terminal formations the way a human lays out a board:+// they escape a pin, join a corridor beside existing traces (hug bonus), pay+// for every 45 degree turn (long calm runs), pay a small surcharge for+// sustained diagonals (the reference uses short 45 degree jogs), and finish+// into the far pin. States are (node, incoming direction) so turn costs are+// exact. Everything wraps on the torus.++class MinHeap {+ constructor() {+ this.costs = [];+ this.values = [];+ }++ get size() {+ return this.costs.length;+ }++ push(cost, value) {+ const { costs, values } = this;+ let index = costs.length;+ costs.push(cost);+ values.push(value);+ while (index > 0) {+ const parent = (index - 1) >> 1;+ if (costs[parent] <= costs[index]) break;+ [costs[parent], costs[index]] = [costs[index], costs[parent]];+ [values[parent], values[index]] = [values[index], values[parent]];+ index = parent;+ }+ }++ pop() {+ const { costs, values } = this;+ const top = values[0];+ const lastCost = costs.pop();+ const lastValue = values.pop();+ if (costs.length) {+ costs[0] = lastCost;+ values[0] = lastValue;+ let index = 0;+ for (;;) {+ const left = index * 2 + 1;+ const right = left + 1;+ let smallest = index;+ if (left < costs.length && costs[left] < costs[smallest]) smallest = left;+ if (right < costs.length && costs[right] < costs[smallest]) smallest = right;+ if (smallest === index) break;+ [costs[smallest], costs[index]] = [costs[index], costs[smallest]];+ [values[smallest], values[index]] = [values[index], values[smallest]];+ index = smallest;+ }+ }+ return top;+ }+}++function createPathfinder(router, columns, rows, config) {+ const turnPenalty = config.turnPenalty;+ const crampPenalty = config.cramp;+ const weaveBonus = config.weave;+ const stateCount = columns * rows * 8;+ const bestCost = new Float64Array(stateCount);+ const seen = new Int32Array(stateCount);+ const closed = new Int32Array(stateCount);+ const parent = new Int32Array(stateCount);+ let generation = 0;++ const wrapX = (value) => ((value % columns) + columns) % columns;+ const wrapY = (value) => ((value % rows) + rows) % rows;++ // start: {x, y, direction}; goal: {x, y, arrivals: Set<direction>}+ // bundleMode flips the lane preference: followers rejoining their bundle+ // WANT to ride one lane off their neighbor.+ return function route(random, start, goal, why = {}, bundleMode = false) {+ generation += 1;+ const heap = new MinHeap();+ const goalX = wrapX(goal.x);+ const goalY = wrapY(goal.y);+ const goalKey = router.nodeKey(goalX, goalY);++ const heuristic = (x, y) => {+ let dx = Math.abs(x - goalX);+ dx = Math.min(dx, columns - dx);+ let dy = Math.abs(y - goalY);+ dy = Math.min(dy, rows - dy);+ return Math.max(dx, dy) + 0.42 * Math.min(dx, dy);+ };++ const startX = wrapX(start.x);+ const startY = wrapY(start.y);+ // Seed the facing direction free, and the two perpendiculars at a small+ // cost — a pin whose lane is congested can still hook out sideways.+ const h0 = heuristic(startX, startY);+ for (const [turn, cost] of [[0, 0], [2, 0.9], [6, 0.9]]) {+ const startState = (startY * columns + startX) * 8 + ((start.direction + turn) % 8);+ seen[startState] = generation;+ bestCost[startState] = cost;+ parent[startState] = -1;+ heap.push(cost + h0, startState);+ }++ const straightestFirst = heuristic(startX, startY);+ let goalState = -1;+ let expansions = 0;+ const TURNS = [0, 1, 7];++ // Weighted A* (heuristic scaled below): meaningfully faster, and the mild+ // suboptimality reads as organic hand-routing rather than error.+ while (heap.size && expansions < 9000) {+ expansions += 1;+ const state = heap.pop();+ if (closed[state] === generation) continue;+ closed[state] = generation;+ const direction = state % 8;+ const nodeIndex = (state - direction) / 8;+ const x = nodeIndex % columns;+ const y = (nodeIndex - x) / columns;++ if (x === goalX && y === goalY) {+ if (goal.arrivals.has(direction)) {+ goalState = state;+ break;+ }+ continue;+ }++ const cost = bestCost[state];+ for (const turn of TURNS) {+ const next = (direction + turn) % 8;+ if (!router.routeStepFree(x, y, next, goalKey)) continue;+ const nx = wrapX(x + DIR8[next][0]);+ const ny = wrapY(y + DIR8[next][1]);+ let stepCost = next % 2 === 0 ? 1 : 1.414;+ if (turn !== 0) stepCost += turnPenalty;+ const lane = router.laneNeighbors(nx, ny, next);+ if (bundleMode) {+ if (lane === 1) stepCost -= 0.22;+ } else if (lane === 1) stepCost += crampPenalty;+ else if (lane === 2) stepCost -= weaveBonus;+ stepCost += random() * 0.05;+ const nextState = (ny * columns + nx) * 8 + next;+ const total = cost + stepCost;+ if (seen[nextState] === generation && bestCost[nextState] <= total) continue;+ seen[nextState] = generation;+ bestCost[nextState] = total;+ parent[nextState] = state;+ heap.push(total + heuristic(nx, ny) * 1.2, nextState);+ }+ }++ if (goalState < 0) {+ why.reason = heap.size ? "expansions" : "exhausted";+ return null;+ }+ const directions = [];+ let cursor = goalState;+ while (parent[cursor] >= 0) {+ directions.push(cursor % 8);+ cursor = parent[cursor];+ }+ directions.reverse();+ // Reject absurd detours (torus wrap can produce them when hemmed in).+ if (directions.length > straightestFirst * 2.4 + 12) {+ why.reason = "detour";+ return null;+ }+ return directions;+ };+}++// --- terminal formations ----------------------------------------------------+//+// The reference pattern's vias are not sprinkled at random: they sit in small+// deliberate formations — diagonal ladders (staggered bus fanouts), rows, and+// singles — and traces escape them on a consistent side. Formations are placed+// with best-candidate sampling so the tile keeps even coverage and breathing+// room between groups.++function placeFormations(random, router, columns, rows, count, config) {+ const formations = [];+ const centers = [];+ const busWidth = config.busWidth;+ const horizontalEscape = Math.min(0.95, config.horizontalBias + 0.02);+ const rowSplit = 0.52 + 0.26 * config.horizontalBias;+ const wrapDist = (a, b, m) => {+ const d = Math.abs(a - b) % m;+ return Math.min(d, m - d);+ };++ for (let index = 0; index < count; index += 1) {+ let best = null;+ let bestClearance = -1;+ for (let candidate = 0; candidate < 8; candidate += 1) {+ const x = Math.floor(random() * columns);+ const y = Math.floor(random() * rows);+ let clearance = Infinity;+ for (const [cx, cy] of centers) {+ clearance = Math.min(+ clearance,+ Math.hypot(wrapDist(x, cx, columns), wrapDist(y, cy, rows)),+ );+ }+ if (clearance > bestClearance) {+ bestClearance = clearance;+ best = [x, y];+ }+ }++ const [x, y] = best;+ const roll = random();+ const pins = [];+ let signature;+ if (roll < 0.52) {+ // Diagonal via ladder — the staggered bus-fanout motif.+ const length = Math.max(2, Math.min(8, Math.round((3 + random() * 4) * busWidth)));+ const slope = random() < 0.5 ? -1 : 1;+ const escape = random() < horizontalEscape ? 0 : 4;+ signature = `ladder${slope}`;+ for (let k = 0; k < length; k += 1) pins.push({ x: x + k, y: y + k * slope, escape });+ } else if (roll < rowSplit) {+ // Vertical via row (2-cell spacing), horizontal escapes.+ const length = Math.max(2, Math.min(6, Math.round((2 + random() * 2) * busWidth)));+ const escape = random() < 0.5 ? 0 : 4;+ signature = "vrow";+ for (let k = 0; k < length; k += 1) pins.push({ x, y: y + k * 2, escape });+ } else if (roll < 0.78) {+ // Horizontal via row, vertical escapes.+ const length = Math.max(2, Math.min(6, Math.round((2 + random() * 2) * busWidth)));+ const escape = random() < 0.5 ? 2 : 6;+ signature = "hrow";+ for (let k = 0; k < length; k += 1) pins.push({ x: x + k * 2, y, escape });+ } else {+ signature = "solo";+ pins.push({ x, y, escape: [0, 4, 2, 6][Math.floor(random() * 4)] });+ }++ // Reserve the pin nodes now; the via graphics are only placed when a net+ // or stub actually connects, so a formation that stays unconnected leaves+ // no orphaned via row behind.+ const record = newTraceRecord(pins[0].x, pins[0].y);+ let placeable = true;+ for (const pin of pins) {+ if (!router.nodeFree(pin.x, pin.y)) {+ placeable = false;+ break;+ }+ router.claimNode(record, pin.x, pin.y);+ }+ if (!placeable) {+ router.rollback(record);+ continue;+ }+ centers.push([x, y]);+ formations.push({ pins: pins.map((pin) => ({ ...pin, used: false })), record, signature });+ }+ return formations;+}++// Start a trace record at a pin with its mandatory via already in place.+// Returns null when the pin has no via clearance (the pin is then skipped —+// every trace must begin on a via).+function startAtPin(router, pin) {+ const record = newTraceRecord(pin.x, pin.y);+ if (!router.viaAllowed(record, pin.x, pin.y)) return null;+ router.placeVia(record, pin.x, pin.y);+ return record;+}++function signedWrap(delta, modulus) {+ let d = ((delta % modulus) + modulus) % modulus;+ if (d > modulus / 2) d -= modulus;+ return d;+}++// A route may enter a pin from the facing side or hook in from up to 90+// degrees off — only a straight-through backside entry is forbidden.+const ARRIVALS = DIR8.map((_, escape) => {+ const reverse = (escape + 4) % 8;+ return new Set([+ (reverse + 6) % 8,+ (reverse + 7) % 8,+ reverse,+ (reverse + 1) % 8,+ (reverse + 2) % 8,+ ]);+});++// Route bundles of nets between compatible formations. Only the FIRST pin+// pair is routed with A*; the remaining pins get pure translated copies of+// the leader. Translation is what the reference does: neighbors that bend at+// the same places, producing nested chevrons and group staircases. Followers+// that hit an obstruction stop early and drop their via there — a natural+// fanout.+function routeNets(random, router, route, formations, addRecord, stats, config) {+ const majorFor = (escape) => (escape === 0 || escape === 4 ? 0 : 1);+ const sameNode = (x1, y1, x2, y2) =>+ router.nodeKey(x1, y1) === router.nodeKey(x2, y2);++ for (const formation of formations) {+ const minePins = formation.pins.filter((pin) => !pin.used);+ if (!minePins.length) continue;++ const escape = formation.pins[0].escape;+ const axis = majorFor(escape);+ // Find a partner formation whose pins face back toward this one; a+ // partner with the same shape nests perfectly under translation.+ let partner = null;+ let partnerScore = Infinity;+ for (const other of formations) {+ if (other === formation) continue;+ const otherFree = other.pins.filter((pin) => !pin.used);+ if (!otherFree.length) continue;+ if (other.pins[0].escape !== (escape + 4) % 8) continue;+ const dx = signedWrap(other.pins[0].x - formation.pins[0].x, router.columns);+ const dy = signedWrap(other.pins[0].y - formation.pins[0].y, router.rows);+ const major = axis === 0 ? dx : dy;+ const minor = axis === 0 ? dy : dx;+ const forward = escape === 0 || escape === 2 ? major : -major;+ if (forward < 8 || forward > config.netReach) continue;+ if (Math.abs(minor) > 12) continue;+ // Prefer a few cells of misalignment: it forces the staircase jogs the+ // reference is full of. Perfect alignment yields sterile laser lines.+ let score =+ Math.abs(Math.abs(minor) - config.jogBias) * 0.8 ++ Math.abs(forward - 22) * 0.3 ++ random() * 5;+ if (other.signature === formation.signature) score -= 4;+ if (score < partnerScore) {+ partnerScore = score;+ partner = other;+ }+ }+ if (!partner) continue;++ const minorOf = (pin) => (axis === 0 ? pin.y : pin.x);+ const mine = minePins.sort((a, b) => minorOf(a) - minorOf(b));+ const theirs = partner.pins+ .filter((pin) => !pin.used)+ .sort((a, b) => minorOf(a) - minorOf(b));+ const pairCount = Math.min(mine.length, theirs.length);+ if (!pairCount) continue;++ // Leader. Both pin vias go in before routing — every trace begins and+ // ends on a via, so a net is only viable if both terminals have+ // clearance.+ const leadFrom = mine[0];+ const leadTo = theirs[0];+ const leadRecord = startAtPin(router, leadFrom);+ if (!leadRecord) continue;+ if (!router.viaAllowed(leadRecord, leadTo.x, leadTo.y)) {+ router.rollback(leadRecord);+ continue;+ }+ router.placeVia(leadRecord, leadTo.x, leadTo.y);+ const why = {};+ const directions = route(+ random,+ { x: leadFrom.x, y: leadFrom.y, direction: leadFrom.escape },+ { x: leadTo.x, y: leadTo.y, arrivals: ARRIVALS[leadTo.escape] },+ why,+ );+ if (!directions) {+ router.rollback(leadRecord);+ stats.leaderFails += 1;+ stats[why.reason] = (stats[why.reason] || 0) + 1;+ continue;+ }+ stats.leaders += 1;+ stats.followerTries += pairCount - 1;+ {+ let x = leadFrom.x;+ let y = leadFrom.y;+ for (const step of directions) {+ router.claimStep(leadRecord, x, y, step);+ x += DIR8[step][0];+ y += DIR8[step][1];+ leadRecord.steps.push(step);+ }+ leadRecord.end = [x, y];+ leadFrom.used = true;+ leadTo.used = true;+ addRecord(leadRecord);+ }++ // Followers: translated copies pin-by-pin. A follower whose translated+ // corridor is blocked early gets rerouted with A* in bundle mode so it+ // wraps the obstacle and rejoins the group. Every follower starts on its+ // pin via and seals its far end with a via (trimming back if needed).+ for (let index = 1; index < pairCount; index += 1) {+ const from = mine[index];+ const to = theirs[index];+ const goalKey = router.nodeKey(to.x, to.y);++ const record = startAtPin(router, from);+ if (!record) {+ stats.followerFails += 1;+ continue;+ }++ const clearSteps = () => {+ while (record.steps.length) router.unclaimLastStep(record);+ };+ const layTranslation = () => {+ let x = from.x;+ let y = from.y;+ for (const step of directions) {+ if (!router.routeStepFree(x, y, step, goalKey)) break;+ router.claimStep(record, x, y, step);+ x += DIR8[step][0];+ y += DIR8[step][1];+ record.steps.push(step);+ if (sameNode(x, y, to.x, to.y)) break;+ }+ record.end = [x, y];+ };++ layTranslation();+ let reached = sameNode(record.end[0], record.end[1], to.x, to.y);+ if (!reached && record.steps.length < Math.max(6, Math.floor(directions.length * 0.6))) {+ clearSteps();+ const alt = route(+ random,+ { x: from.x, y: from.y, direction: from.escape },+ { x: to.x, y: to.y, arrivals: ARRIVALS[to.escape] },+ {},+ true,+ );+ if (alt) {+ let x = from.x;+ let y = from.y;+ for (const step of alt) {+ router.claimStep(record, x, y, step);+ x += DIR8[step][0];+ y += DIR8[step][1];+ record.steps.push(step);+ }+ record.end = [x, y];+ reached = true;+ stats.followersRerouted += 1;+ } else {+ layTranslation();+ reached = sameNode(record.end[0], record.end[1], to.x, to.y);+ }+ }++ if (record.steps.length < 4 || !sealEnd(router, record, 4)) {+ router.rollback(record);+ stats.followerFails += 1;+ continue;+ }+ from.used = true;+ if (sameNode(record.end[0], record.end[1], to.x, to.y)) {+ to.used = true;+ stats.followersFull += 1;+ } else {+ stats.followersPartial += 1;+ }+ addRecord(record);+ }+ }+}++// Tap combs: short perpendicular stubs dropping off a long run at a regular+// pitch, each ending in a via — the power-rail tap motif that punctuates the+// reference artwork.+function tapCombs(random, router, records, addRecord, config) {+ const runs = [];+ for (const record of records) {+ let x = record.start[0];+ let y = record.start[1];+ let runX = x;+ let runY = y;+ let runDir = -1;+ let runLen = 0;+ const flush = () => {+ if (runDir >= 0 && runDir % 2 === 0 && runLen >= 8) {+ runs.push({ x: runX, y: runY, dir: runDir, len: runLen });+ }+ };+ for (const step of record.steps) {+ if (step === runDir) runLen += 1;+ else {+ flush();+ runDir = step;+ runX = x;+ runY = y;+ runLen = 1;+ }+ x += DIR8[step][0];+ y += DIR8[step][1];+ }+ flush();+ }++ let combs = 0;+ for (const run of runs) {+ if (combs >= config.combs || random() >= 0.28) continue;+ const [dx, dy] = DIR8[run.dir];+ const side = random() < 0.5 ? 1 : -1;+ const px = -dy * side;+ const py = dx * side;+ const tapDir = DIR8.findIndex(([tx, ty]) => tx === px && ty === py);+ const teeth = 2 + Math.floor(random() * 3);+ // Depth 2-3: the junction via and tip via need a two-cell gap to clear+ // each other's annular rings.+ const depth = 2 + (random() < 0.35 ? 1 : 0);+ const span = teeth * 2;+ if (run.len < span + 2) continue;+ const offset = 1 + Math.floor(random() * (run.len - span - 1));+ const made = [];+ for (let tooth = 0; tooth < teeth; tooth += 1) {+ const bx = run.x + dx * (offset + tooth * 2);+ const by = run.y + dy * (offset + tooth * 2);+ // The tap starts ON the parent trace (a T junction, marked with its+ // own via) and steps outward to a tip via.+ const record = newTraceRecord(bx, by);+ if (!router.viaAllowed(record, bx, by)) continue;+ router.placeVia(record, bx, by);+ let cx = bx;+ let cy = by;+ for (let d = 0; d < depth; d += 1) {+ if (!router.stepFree(cx, cy, tapDir)) break;+ router.claimStep(record, cx, cy, tapDir);+ cx += px;+ cy += py;+ record.steps.push(tapDir);+ }+ record.end = [cx, cy];+ if (record.steps.length < 2 || !sealEnd(router, record, 2)) {+ router.rollback(record);+ continue;+ }+ made.push(record);+ }+ if (made.length >= 2) {+ for (const record of made) addRecord(record);+ combs += 1;+ } else {+ for (const record of made) router.rollback(record);+ }+ }+}++// Short bare-ended escape stubs for pins that never got a net — the reference+// is full of these little launches.+function routeStubs(random, router, formations, addRecord, config) {+ for (const formation of formations) {+ for (const pin of formation.pins) {+ if (pin.used || random() >= config.stubChance) continue;+ const record = startAtPin(router, pin);+ if (!record) continue;+ let x = pin.x;+ let y = pin.y;+ let direction = pin.escape;+ const length = 2 + Math.floor(random() * 5);+ for (let step = 0; step < length; step += 1) {+ if (step > 0 && random() < 0.2) {+ const jog = (direction + (random() < 0.5 ? 1 : 7)) % 8;+ if (router.stepFree(x, y, jog)) direction = jog;+ }+ if (!router.stepFree(x, y, direction)) break;+ router.claimStep(record, x, y, direction);+ x += DIR8[direction][0];+ y += DIR8[direction][1];+ record.steps.push(direction);+ }+ record.end = [x, y];+ if (record.steps.length < 2 || !sealEnd(router, record, 2)) {+ router.rollback(record);+ continue;+ }+ pin.used = true;+ addRecord(record);+ }+ }+}++// Translated companions for a filler walk — same idea as the net followers:+// staggered trims and via ladders at the ends, bending wherever the base+// bends. In the reference almost nothing travels alone.+function replicateWalk(random, router, base, addRecord) {+ if (random() >= 0.55 || base.steps.length < 8) return;+ let horizontalSteps = 0;+ let verticalSteps = 0;+ for (const step of base.steps) {+ if (step === 0 || step === 4) horizontalSteps += 1;+ else if (step === 2 || step === 6) verticalSteps += 1;+ }+ const horizontal = horizontalSteps >= verticalSteps;+ const spacing = random() < 0.7 ? 1 : 2;+ const side = random() < 0.5 ? 1 : -1;+ const shift = horizontal ? [0, spacing * side] : [spacing * side, 0];+ const copies = 1 + Math.floor(random() * 3);+ const trimStartUnit = random() < 0.5 ? 1 : 0;+ const trimEndUnit = random() < 0.8 ? 1 : 2;++ for (let copy = 1; copy <= copies; copy += 1) {+ const trimStart = copy * trimStartUnit;+ const trimEnd = copy * trimEndUnit;+ if (base.steps.length - trimStart - trimEnd < 5) break;+ let x = base.start[0] + shift[0] * copy;+ let y = base.start[1] + shift[1] * copy;+ for (let index = 0; index < trimStart; index += 1) {+ x += DIR8[base.steps[index]][0];+ y += DIR8[base.steps[index]][1];+ }+ if (!router.nodeFree(x, y) || !router.viaAllowed(SCRATCH_RECORD, x, y)) continue;+ const record = newTraceRecord(x, y);+ router.claimNode(record, x, y);+ router.placeVia(record, x, y); // every trace starts on a via+ for (let index = trimStart; index < base.steps.length - trimEnd; index += 1) {+ const step = base.steps[index];+ if (!router.stepFree(x, y, step)) break;+ router.claimStep(record, x, y, step);+ x += DIR8[step][0];+ y += DIR8[step][1];+ record.steps.push(step);+ }+ record.end = [x, y];+ if (record.steps.length < 5 || !sealEnd(router, record, 5)) {+ router.rollback(record);+ continue;+ }+ addRecord(record);+ }+}++// --- filler walker ----------------------------------------------------------+//+// A small amount of free-roaming texture between the routed bundles, using the+// same collision rules. Kept from the earlier engine but used sparingly.++const SCRATCH_RECORD = { ownKeys: new Set() };++function walkTrace(random, router, config, startWeights) {+ let sx = -1;+ let sy = -1;+ let bestCrowding = Infinity;+ for (let attempt = 0, found = 0; attempt < 24 && found < 3; attempt += 1) {+ const x = Math.floor(random() * router.columns);+ const y = Math.floor(random() * router.rows);+ if (!router.nodeFree(x, y) || !router.viaAllowed(SCRATCH_RECORD, x, y)) continue;+ found += 1;+ const crowding = router.crowding(x, y);+ if (crowding < bestCrowding) {+ bestCrowding = crowding;+ sx = x;+ sy = y;+ }+ }+ if (sx < 0) return null;++ const trace = newTraceRecord(sx, sy);+ router.claimNode(trace, sx, sy);+ router.placeVia(trace, sx, sy); // every trace starts on a via++ let direction = weightedChoice(random, startWeights);+ let lastCardinal = direction % 2 === 0 ? direction : (direction + (random() < 0.5 ? 1 : 7)) % 8;+ const budget = 14 + Math.floor(random() * 22);+ let x = sx;+ let y = sy;+ let sinceVia = 4;+ let turnStreak = 0; // consecutive same-side turns; capped to avoid closed loops++ while (trace.steps.length < budget) {+ const cardinal = direction % 2 === 0;+ const runLength = cardinal+ ? 3 + Math.floor(random() * random() * 9)+ : 1 + Math.floor(random() * 3);++ for (let step = 0; step < runLength && trace.steps.length < budget; step += 1) {+ if (!router.stepFree(x, y, direction)) break;+ router.claimStep(trace, x, y, direction);+ x += DIR8[direction][0];+ y += DIR8[direction][1];+ trace.steps.push(direction);+ sinceVia += 1;+ if (+ cardinal &&+ sinceVia > 4 &&+ trace.steps.length < budget - 2 &&+ random() < config.inlineViaChance &&+ router.viaAllowed(trace, x, y)+ ) {+ router.placeVia(trace, x, y);+ sinceVia = 0;+ }+ }++ if (trace.steps.length >= budget) break;++ let next;+ if (cardinal) {+ // Curling the same way repeatedly closes octagon loops; alternate.+ const side = Math.abs(turnStreak) >= 3 ? -Math.sign(turnStreak) : random() < 0.5 ? 1 : -1;+ next = (direction + (side > 0 ? 1 : 7)) % 8;+ } else {+ const optionA = (direction + 1) % 8;+ const optionB = (direction + 7) % 8;+ const preferPrevious = (optionA === lastCardinal || optionB === lastCardinal) && random() < 0.7;+ next = preferPrevious ? lastCardinal : random() < 0.5 ? optionA : optionB;+ }+ if (!router.stepFree(x, y, next)) {+ const mirrored = (direction + (8 - ((next - direction + 8) % 8))) % 8;+ if (!router.stepFree(x, y, mirrored)) break;+ next = mirrored;+ }+ const turnSide = ((next - direction + 8) % 8) === 1 ? 1 : -1;+ turnStreak = Math.sign(turnStreak) === turnSide ? turnStreak + turnSide : turnSide;+ direction = next;+ if (direction % 2 === 0) lastCardinal = direction;+ }++ trace.end = [x, y];+ if (trace.steps.length < 7 || !sealEnd(router, trace, 7)) {+ router.rollback(trace);+ return null;+ }+ return trace;+}++function toTileTrace(record, pitch) {+ const points = [[record.start[0], record.start[1]]];+ let previous = -1;+ let [x, y] = record.start;+ for (const step of record.steps) {+ x += DIR8[step][0];+ y += DIR8[step][1];+ if (step === previous) points[points.length - 1] = [x, y];+ else points.push([x, y]);+ previous = step;+ }+ const scaled = points.map(([px, py]) => [px * pitch, py * pitch]);+ let length = 0;+ for (let index = 1; index < scaled.length; index += 1) {+ length += Math.hypot(+ scaled[index][0] - scaled[index - 1][0],+ scaled[index][1] - scaled[index - 1][1],+ );+ }+ return {+ points: scaled,+ length,+ vias: record.viaCells.map(([vx, vy]) => [vx * pitch, vy * pitch]),+ };+}++export function generateCircuitTile(options = {}) {+ const config = { ...DEFAULTS, ...options };+ const random = mulberry32(hashSeed(config.seed));+ const columns = Math.round(config.tileWidth / config.pitch);+ const rows = Math.round(config.tileHeight / config.pitch);+ const router = createRouter(random, columns, rows);+ const route = createPathfinder(router, columns, rows, config);+ const startWeights = startDirectionWeights(config.horizontalBias);++ const records = [];+ let routedSteps = 0;+ const addRecord = (record) => {+ records.push(record);+ routedSteps += record.steps.length;+ };++ // 1. Terminal formations: via ladders, rows, singles.+ const formations = placeFormations(+ random,+ router,+ columns,+ rows,+ Math.round(config.formations * config.density),+ config,+ );+ for (const formation of formations) records.push(formation.record);++ // 2. Nets between formations — the flow. Two passes so pins left over from+ // the first pairing find another partner.+ const stats = {+ formations: formations.length,+ leaders: 0,+ leaderFails: 0,+ followerTries: 0,+ followersFull: 0,+ followersPartial: 0,+ followersRerouted: 0,+ followerFails: 0,+ };+ routeNets(random, router, route, formations, addRecord, stats, config);+ routeNets(random, router, route, formations, addRecord, stats, config);++ // 3. Escape stubs for leftover pins.+ routeStubs(random, router, formations, addRecord, config);++ // 4. A sprinkle of free-roaming filler until the reference ink density.+ const targetSteps = Math.round(4800 * config.density);+ let attempts = 0;+ while (routedSteps < targetSteps && attempts < 3200) {+ attempts += 1;+ const trace = walkTrace(random, router, config, startWeights);+ if (trace) {+ addRecord(trace);+ replicateWalk(random, router, trace, addRecord);+ }+ }++ // 5. Tap combs hanging off the long runs (nets and filler alike).+ if (config.combs > 0) tapCombs(random, router, [...records], addRecord, config);++ return {+ width: columns * config.pitch,+ height: rows * config.pitch,+ pitch: config.pitch,+ stats,+ traces: records.map((record) => toTileTrace(record, config.pitch)),+ };+}++export function pathData(points, offsetX = 0, offsetY = 0) {+ return points+ .map(([x, y], index) => `${index ? "L" : "M"}${(x + offsetX).toFixed(2)},${(y + offsetY).toFixed(2)}`)+ .join("");+}++// Standalone seamless tile: the geometry is drawn 3 x 3 around the viewBox and+// clipped, so traces that wrap the torus edge reappear on the opposite side.+export function tileSvg(tile, options = {}) {+ const config = { ...DEFAULTS, ...options };+ const { width, height } = tile;+ const body = [];+ for (const trace of tile.traces) {+ if (trace.points.length < 2) continue;+ body.push(+ `<path d="${pathData(trace.points)}" fill="none" stroke="${config.traceColor}" ` ++ `stroke-width="${config.traceWidth}" stroke-linecap="butt" stroke-linejoin="miter"/>`,+ );+ }+ const vias = [];+ for (const trace of tile.traces) {+ for (const [cx, cy] of trace.vias) {+ vias.push(+ `<circle cx="${cx.toFixed(2)}" cy="${cy.toFixed(2)}" r="${config.viaOuterRadius}" fill="${config.traceColor}"/>` ++ `<circle cx="${cx.toFixed(2)}" cy="${cy.toFixed(2)}" r="${config.viaInnerRadius}" fill="${config.holeColor || config.background || "#0d1117"}"/>`,+ );+ }+ }+ const uses = [];+ for (let row = -1; row <= 1; row += 1) {+ for (let column = -1; column <= 1; column += 1) {+ uses.push(`<use href="#tile" transform="translate(${column * width}, ${row * height})"/>`);+ }+ }+ const backgroundRect = config.background+ ? `<rect width="${width}" height="${height}" fill="${config.background}"/>`+ : "";+ return (+ `<?xml version="1.0" encoding="UTF-8"?>\n` ++ `<svg xmlns="${SVG_NS}" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">` ++ `<defs><g id="tile">${body.join("")}${vias.join("")}</g>` ++ `<clipPath id="edge"><rect width="${width}" height="${height}"/></clipPath></defs>` ++ `${backgroundRect}<g clip-path="url(#edge)">${uses.join("")}</g></svg>`+ );+}++// --- signal routing ---------------------------------------------------------+//+// Signals ride the real centerlines. Each trace is resampled to ~3.5 unit+// spacing and indexed in a spatial hash; when a pulse reaches the end of a+// trace it looks for a nearby, direction-aligned point on another trace (in+// this tile or a neighbor) and hops there, exactly like the reference site.++const SIGNAL_SAMPLE = 3.5;+const HOP_RADIUS = 3.5;+const HASH_CELL = 8;+const signalIndexCache = new WeakMap();++function ensureSignalIndex(tile) {+ let index = signalIndexCache.get(tile);+ if (index) return index;+ const dense = tile.traces.map((trace) => {+ if (trace.points.length < 2) return [];+ const points = [];+ for (let segment = 1; segment < trace.points.length; segment += 1) {+ const [ax, ay] = trace.points[segment - 1];+ const [bx, by] = trace.points[segment];+ const steps = Math.max(1, Math.round(Math.hypot(bx - ax, by - ay) / SIGNAL_SAMPLE));+ for (let step = segment === 1 ? 0 : 1; step <= steps; step += 1) {+ points.push([ax + ((bx - ax) * step) / steps, ay + ((by - ay) * step) / steps]);+ }+ }+ return points;+ });+ const buckets = new Map();+ dense.forEach((points, traceIndex) => {+ points.forEach((point, pointIndex) => {+ const key = `${Math.floor(point[0] / HASH_CELL)}:${Math.floor(point[1] / HASH_CELL)}`;+ let bucket = buckets.get(key);+ if (!bucket) buckets.set(key, (bucket = []));+ bucket.push([traceIndex, pointIndex]);+ });+ });+ // Trace endpoints (all mandated vias) — the launch pads for via hopping.+ const endpoints = [];+ dense.forEach((points, traceIndex) => {+ if (points.length < 6) return;+ endpoints.push({ trace: traceIndex, point: 0, direction: 1, x: points[0][0], y: points[0][1] });+ const last = points.length - 1;+ endpoints.push({ trace: traceIndex, point: last, direction: -1, x: points[last][0], y: points[last][1] });+ });+ index = { dense, buckets, endpoints };+ signalIndexCache.set(tile, index);+ return index;+}++function findHop(tile, absX, absY, dirX, dirY, visited) {+ const { dense, buckets } = ensureSignalIndex(tile);+ const baseTileX = Math.floor(absX / tile.width);+ const baseTileY = Math.floor(absY / tile.height);+ let best = null;++ for (let tileY = baseTileY - 2; tileY <= baseTileY + 2; tileY += 1) {+ for (let tileX = baseTileX - 2; tileX <= baseTileX + 2; tileX += 1) {+ const localX = absX - tileX * tile.width;+ const localY = absY - tileY * tile.height;+ const minCellX = Math.floor((localX - HOP_RADIUS) / HASH_CELL);+ const maxCellX = Math.floor((localX + HOP_RADIUS) / HASH_CELL);+ const minCellY = Math.floor((localY - HOP_RADIUS) / HASH_CELL);+ const maxCellY = Math.floor((localY + HOP_RADIUS) / HASH_CELL);+ for (let cellY = minCellY; cellY <= maxCellY; cellY += 1) {+ for (let cellX = minCellX; cellX <= maxCellX; cellX += 1) {+ const bucket = buckets.get(`${cellX}:${cellY}`);+ if (!bucket) continue;+ for (const [traceIndex, pointIndex] of bucket) {+ if (visited.has(`${traceIndex}:${tileX}:${tileY}`)) continue;+ const point = dense[traceIndex][pointIndex];+ const distance = Math.hypot(point[0] - localX, point[1] - localY);+ if (distance >= HOP_RADIUS) continue;+ if (distance >= 1.2) {+ const toward =+ ((point[0] - localX) * dirX + (point[1] - localY) * dirY) / (distance || 1);+ if (toward < 0.35) continue;+ }+ for (const hopDirection of [1, -1]) {+ const ahead = pointIndex + hopDirection * 3;+ if (ahead < 0 || ahead >= dense[traceIndex].length) continue;+ const segX = dense[traceIndex][ahead][0] - point[0];+ const segY = dense[traceIndex][ahead][1] - point[1];+ const segLength = Math.hypot(segX, segY) || 1;+ const score = (segX * dirX + segY * dirY) / segLength - distance * 0.05;+ if (!best || score > best.score) {+ best = {+ trace: traceIndex,+ tileX,+ tileY,+ point: pointIndex,+ direction: hopDirection,+ score,+ };+ }+ }+ }+ }+ }+ }+ }+ return best && best.score > 0.1 ? best : null;+}++function buildSignalPath(tile, start, budget, minLength) {+ const { dense } = ensureSignalIndex(tile);+ const visited = new Set();+ const points = [];+ let travelled = 0;+ let cursor = { ...start };++ // The walk always finishes at a trace end (a mandated via) — the budget+ // only limits further mid-route hops, never cuts a pulse off mid-trace.+ for (;;) {+ const tracePoints = dense[cursor.trace];+ visited.add(`${cursor.trace}:${cursor.tileX}:${cursor.tileY}`);+ const offsetX = cursor.tileX * tile.width;+ const offsetY = cursor.tileY * tile.height;+ for (+ let index = cursor.point;+ index >= 0 && index < tracePoints.length;+ index += cursor.direction+ ) {+ const x = tracePoints[index][0] + offsetX;+ const y = tracePoints[index][1] + offsetY;+ if (points.length) {+ const last = points[points.length - 1];+ travelled += Math.hypot(x - last[0], y - last[1]);+ }+ points.push([x, y]);+ }+ if (points.length < 2 || travelled >= budget) break;++ const last = points[points.length - 1];+ const before = points[points.length - 2];+ const stepLength = Math.hypot(last[0] - before[0], last[1] - before[1]) || 1;+ const hop = findHop(+ tile,+ last[0],+ last[1],+ (last[0] - before[0]) / stepLength,+ (last[1] - before[1]) / stepLength,+ visited,+ );+ if (!hop) break;+ cursor = hop;+ }++ return travelled >= minLength ? { points, length: travelled } : null;+}++// --- reveal choreography -----------------------------------------------------+//+// Instead of the finished board appearing at once, every trace can be hidden+// behind its own stroke-dash and then GROWN out of one of its end vias, with a+// bright spark riding the tip and each via lighting up as the tip reaches it.+// Because the geometry lives once in <defs> and every screen tile is a <use>+// of it, one animation per trace paints the growth across the whole background+// — ~235 animations, not 235 x (tiles on screen).+//+// A style only chooses the ORDER traces start in; the drawing itself is the+// same everywhere. Ranks come from SORTING the metric, not the raw value, so+// ink flows at an even rate no matter how lopsided the metric is.++const REVEAL_CELL = 12; // adjacency bucket for the flood front (~1.5 pitches)+const REVEAL_SAMPLE = 6; // polyline sampling step when bucketing+const easeOut = (t) => 1 - (1 - t) * (1 - t) * (1 - t);+const smoothstep = (t) => t * t * (3 - 2 * t);+const revealGraphCache = new WeakMap();++const clamp = (value, low, high) => (value < low ? low : value > high ? high : value);++// Distance along the trace at which each via sits, so a pad can light up+// exactly when the growing tip passes it (inline vias land mid-segment+// because collinear runs are merged into a single point pair).+function viaDistances(trace) {+ const points = trace.points;+ if (points.length < 2) return trace.vias.map(() => 0);+ const cumulative = [0];+ for (let index = 1; index < points.length; index += 1) {+ cumulative.push(+ cumulative[index - 1] ++ Math.hypot(points[index][0] - points[index - 1][0], points[index][1] - points[index - 1][1]),+ );+ }+ return trace.vias.map(([viaX, viaY]) => {+ let bestDistance = Infinity;+ let bestAlong = 0;+ for (let index = 1; index < points.length; index += 1) {+ const [ax, ay] = points[index - 1];+ const [bx, by] = points[index];+ const dx = bx - ax;+ const dy = by - ay;+ const span = dx * dx + dy * dy || 1;+ const t = clamp(((viaX - ax) * dx + (viaY - ay) * dy) / span, 0, 1);+ const px = ax + dx * t;+ const py = ay + dy * t;+ const distance = Math.hypot(px - viaX, py - viaY);+ if (distance < bestDistance) {+ bestDistance = distance;+ bestAlong = cumulative[index - 1] + Math.hypot(px - ax, py - ay);+ }+ }+ return bestAlong;+ });+}++function sampleTrace(trace, step, visit) {+ const points = trace.points;+ if (points.length < 2) {+ for (const [x, y] of trace.vias) visit(x, y);+ if (points.length === 1) visit(points[0][0], points[0][1]);+ return;+ }+ for (let index = 1; index < points.length; index += 1) {+ const [ax, ay] = points[index - 1];+ const [bx, by] = points[index];+ const steps = Math.max(1, Math.round(Math.hypot(bx - ax, by - ay) / step));+ for (let s = index === 1 ? 0 : 1; s <= steps; s += 1) {+ visit(ax + ((bx - ax) * s) / steps, ay + ((by - ay) * s) / steps);+ }+ }+}++const wrapIndex = (value, modulus) => ((value % modulus) + modulus) % modulus;++// Traces never touch (the router is crossing-free), so "connected" here means+// physically adjacent: sharing a coarse bucket with a neighbor. Buckets wrap+// on the torus, so the flood front crosses the tile seam like the traces do.+function revealAdjacency(tile) {+ let graph = revealGraphCache.get(tile);+ if (graph) return graph;+ const columns = Math.max(1, Math.round(tile.width / REVEAL_CELL));+ const rows = Math.max(1, Math.round(tile.height / REVEAL_CELL));+ const cellWidth = tile.width / columns;+ const cellHeight = tile.height / rows;+ const buckets = new Map();+ tile.traces.forEach((trace, index) => {+ sampleTrace(trace, REVEAL_SAMPLE, (x, y) => {+ const key =+ wrapIndex(Math.floor(y / cellHeight), rows) * columns ++ wrapIndex(Math.floor(x / cellWidth), columns);+ let bucket = buckets.get(key);+ if (!bucket) buckets.set(key, (bucket = new Set()));+ bucket.add(index);+ });+ });+ const neighbours = tile.traces.map(() => new Set());+ for (const [key, members] of buckets) {+ const cellX = key % columns;+ const cellY = (key - cellX) / columns;+ const near = new Set();+ for (let dy = -1; dy <= 1; dy += 1) {+ for (let dx = -1; dx <= 1; dx += 1) {+ const bucket = buckets.get(+ wrapIndex(cellY + dy, rows) * columns + wrapIndex(cellX + dx, columns),+ );+ if (bucket) for (const index of bucket) near.add(index);+ }+ }+ for (const index of members) {+ for (const other of near) if (other !== index) neighbours[index].add(other);+ }+ }+ graph = neighbours.map((set) => [...set]);+ revealGraphCache.set(tile, graph);+ return graph;+}++function torusDelta(a, b, modulus) {+ const delta = Math.abs(a - b) % modulus;+ return delta > modulus / 2 ? modulus - delta : delta;+}++// Hop count from the trace nearest the seed point, walking the adjacency+// graph — the front spreads through the routing itself, like current wetting+// the copper, rather than as a clean geometric shape.+function floodDepths(tile, anchors, seed) {+ const graph = revealAdjacency(tile);+ const depth = new Array(tile.traces.length).fill(Infinity);+ let start = 0;+ let best = Infinity;+ anchors.forEach(([x, y], index) => {+ const distance = Math.hypot(+ torusDelta(x, seed[0], tile.width),+ torusDelta(y, seed[1], tile.height),+ );+ if (distance < best) {+ best = distance;+ start = index;+ }+ });+ depth[start] = 0;+ const queue = [start];+ for (let head = 0; head < queue.length; head += 1) {+ for (const next of graph[queue[head]]) {+ if (depth[next] !== Infinity) continue;+ depth[next] = depth[queue[head]] + 1;+ queue.push(next);+ }+ }+ let deepest = 0;+ for (const value of depth) if (value !== Infinity && value > deepest) deepest = value;+ return depth.map((value) => (value === Infinity ? deepest + 1 : value));+}++// --- DOM mount ---------------------------------------------------------------++export function createCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");++ const id = `circuit-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let random = mulberry32(hashSeed(`${config.seed}:signals`));+ let tile = generateCircuitTile(config);+ let svg;+ let usesGroup;+ let signalGroup;+ let revealCanvas; // the growth is painted here, then handed off to the SVG+ let revealCtx;+ let settledCanvas; // copper at rest — persistent, never cleared+ let settledCtx;+ let heatCanvases = []; // two generations of glow: one accumulates, one retires+ let heatContexts = [];+ let tipCanvas; // the white-hot heads and the landing pads — cleared every frame+ let tipCtx;+ let viewWidth = 0; // the growth layers' size in CSS px — the backing store+ let viewHeight = 0; // may be denser, so never measure with canvas.width+ let resizeObserver;+ let activeSignals = 0;+ let signalTimer;+ let signalStartTimer;+ let revealPlan = null;+ let revealFrame = 0;+ let revealEndsAt = 0;+ let epoch = 0; // invalidates in-flight signal timeouts across regenerations+ let tilesAcross = 1;+ let tilesDown = 1;+ let topOffset = -config.tileHeight / 2;+ let pointer = null;+ const interactionTarget = mount.parentElement || mount;+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;++ const originalPosition = mount.style.position;+ const computedPosition = getComputedStyle(mount).position;+ if (computedPosition === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function buildSvg() {+ finishReveal(); // a reveal in flight belongs to the board being replaced+ svg?.remove();+ epoch += 1;+ activeSignals = 0;+ tile = generateCircuitTile(config);+ random = mulberry32(hashSeed(`${config.seed}:signals`));+ svg = svgEl("svg", {+ "aria-hidden": "true",+ focusable: "false",+ xmlns: SVG_NS,+ });+ svg.dataset.circuitBackground = "";+ Object.assign(svg.style, {+ position: "absolute",+ left: "0",+ top: "0",+ display: "block",+ maxWidth: "none",+ pointerEvents: "none",+ overflow: "visible",+ });++ const defs = svgEl("defs");+ const tileGroup = svgEl("g", { id: `${id}-tile` });+ const traceGroup = svgEl("g", {+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ const viaGroup = svgEl("g");+ for (const trace of tile.traces) {+ if (trace.points.length >= 2) {+ traceGroup.appendChild(svgEl("path", { d: pathData(trace.points) }));+ }+ for (const [cx, cy] of trace.vias) {+ viaGroup.appendChild(+ svgEl("circle", { cx, cy, r: config.viaOuterRadius, fill: config.traceColor }),+ );+ viaGroup.appendChild(+ svgEl("circle", {+ cx,+ cy,+ r: config.viaInnerRadius,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ );+ }+ }+ tileGroup.append(traceGroup, viaGroup);+ defs.appendChild(tileGroup);+ svg.appendChild(defs);++ usesGroup = svgEl("g");+ signalGroup = svgEl("g", { fill: "none" });+ svg.append(usesGroup, signalGroup);+ mount.prepend(svg);+ layout();+ runReveal();+ }++ // Pointer position in tile coordinates — the seed the radial/flood fronts+ // start from, so a reveal triggered under the cursor blooms out of it.+ function revealSeed() {+ if (!pointer || performance.now() - pointer.at > 6000) return [tile.width / 2, tile.height / 2];+ return [+ ((pointer.x % tile.width) + tile.width) % tile.width,+ ((pointer.y % tile.height) + tile.height) % tile.height,+ ];+ }++ // --- the reveal renderer ---------------------------------------------------+ //+ // The growth is painted on a CANVAS, not by animating the SVG. The board is+ // one tile in <defs>, instanced ~25x by <use>. Chrome mirrors only DOM and+ // attribute state into those instances — Web Animations on referenced content+ // run on the original and paint nothing on screen, and writing attributes+ // every frame costs ~260ms/frame because each mutation resyncs every+ // instance. Canvas also lets the reveal run in SCREEN space, so every tile of+ // the pattern grows on its own schedule and the board arrives as one front+ // instead of the same blob repeated per tile.+ //+ // Three layers, because copper should read as cooling metal, not a lit wire:+ //+ // settled persistent, never cleared — the trace at its resting colour+ // heat persistent but faded a little every frame — the glow of recently+ // laid copper, decaying exponentially into the settled layer+ // tip cleared every frame — the white-hot heads, the pads landing, and+ // the arrival rings, all of which move+ //+ // Only the newly grown piece of each route is ever stroked into the two+ // persistent layers, so per-frame cost tracks what is moving, not the board.+ //+ // MOTION LANGUAGE — deliberately the same as the live signals, so the reveal+ // and the board's idle animation read as one system:+ //+ // * tips travel at a CONSTANT speed (revealSpeed, in the same units/sec as+ // signalSpeed) with linear timing — never eased, never length-scaled+ // * the same stroke stack: ~2.4 wide core, 7 wide glow beneath it+ // * the same palette, and the same arrival blip when a pad is reached+ // (a ring from the pad radius out to ~8, fading over revealBlip ms)+ //+ // Nothing appears or vanishes in one frame: heads fade in as a route starts+ // and fade out after it lands, pads scale up and are only stamped into the+ // settled layer once their pop has finished, and the board itself fades out+ // at the start and back in at the end.++ const REVEAL_FADE_IN = 130; // ms for a head to reach full brightness+ const REVEAL_FADE_OUT = 260; // ms for a head to fade after its route lands+ const REVEAL_CLEAR = 260; // ms for the finished board to fade out at the start+ const REVEAL_JITTER = 70; // ms of scatter on start times, so landings never sync up+ const REVEAL_HANDOFF = 260; // ms to dissolve the (by then heat-free) canvas+ const REVEAL_CATCHUP = 40; // ms of growth a route may be 'born' with after a stall++ function ensureRevealCanvas() {+ if (revealCanvas) return;+ revealCanvas = document.createElement("canvas");+ Object.assign(revealCanvas.style, {+ position: "absolute",+ left: "0",+ top: "0",+ display: "block",+ pointerEvents: "none",+ });+ revealCtx = revealCanvas.getContext("2d");+ settledCanvas = document.createElement("canvas");+ settledCtx = settledCanvas.getContext("2d");+ heatCanvases = [document.createElement("canvas"), document.createElement("canvas")];+ heatContexts = heatCanvases.map((canvas) => canvas.getContext("2d"));+ tipCanvas = document.createElement("canvas");+ tipCtx = tipCanvas.getContext("2d");+ mount.prepend(revealCanvas);+ }++ // The growth layers run at CSS resolution: they are a transient overlay, and+ // full-screen backing stores at devicePixelRatio would cost four times the+ // memory for detail the cool-down immediately replaces with the crisp SVG.+ function sizeRevealCanvas() {+ const width = Math.max(1, mount.clientWidth);+ const height = Math.max(1, mount.clientHeight);+ // Match the display's density (capped, since these are full-screen buffers)+ // or the growth layer hands a soft board over to a crisp SVG.+ const ratio = clamp(window.devicePixelRatio || 1, 1, 2);+ for (const canvas of [revealCanvas, settledCanvas, ...heatCanvases, tipCanvas]) {+ canvas.width = Math.round(width * ratio);+ canvas.height = Math.round(height * ratio);+ // Draw in CSS pixels; the extra density is just resolution.+ canvas.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);+ }+ revealCanvas.style.width = `${width}px`;+ revealCanvas.style.height = `${height}px`;+ viewWidth = width;+ viewHeight = height;+ }++ // --- colour ----------------------------------------------------------------++ const parseHex = (hex) => [+ parseInt(hex.slice(1, 3), 16),+ parseInt(hex.slice(3, 5), 16),+ parseInt(hex.slice(5, 7), 16),+ ];++ function mixRgb(from, to, t) {+ return [+ Math.round(from[0] + (to[0] - from[0]) * t),+ Math.round(from[1] + (to[1] - from[1]) * t),+ Math.round(from[2] + (to[2] - from[2]) * t),+ ];+ }++ const rgbCss = (rgb) => `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`;+ const rgbaCss = (rgb, alpha) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${alpha.toFixed(3)})`;++ // Position on the palette ramp, 0..1 across all its stops.+ function rampAt(stops, t) {+ const span = (stops.length - 1) * clamp(t, 0, 1);+ const index = Math.min(stops.length - 2, Math.floor(span));+ return mixRgb(stops[index], stops[index + 1], span - index);+ }++ // A smooth screen-space value-noise field: neighbouring routes land on+ // similar values, so hue drifts in broad regions rather than per trace.+ function makeZoneField(width, height, cell, random) {+ const columns = Math.max(2, Math.ceil(width / cell) + 2);+ const rows = Math.max(2, Math.ceil(height / cell) + 2);+ const values = Array.from({ length: columns * rows }, () => random());+ const smooth = (t) => t * t * (3 - 2 * t);+ return (x, y) => {+ const gx = clamp(x / cell + 0.5, 0, columns - 1.001);+ const gy = clamp(y / cell + 0.5, 0, rows - 1.001);+ const x0 = Math.floor(gx);+ const y0 = Math.floor(gy);+ const fx = smooth(gx - x0);+ const fy = smooth(gy - y0);+ const at = (cx, cy) => values[cy * columns + cx];+ const top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * fx;+ const bottom = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * fx;+ return top + (bottom - top) * fy;+ };+ }++ // --- geometry --------------------------------------------------------------++ function segmentBetween(geometry, from, to, offsetX, offsetY) {+ const { points, cumulative } = geometry;+ const out = [];+ for (let index = 1; index < points.length; index += 1) {+ const start = cumulative[index - 1];+ const end = cumulative[index];+ if (end < from || start > to) continue;+ const span = end - start || 1;+ const lerp = (at) => [+ offsetX + points[index - 1][0] + ((points[index][0] - points[index - 1][0]) * (at - start)) / span,+ offsetY + points[index - 1][1] + ((points[index][1] - points[index - 1][1]) * (at - start)) / span,+ ];+ if (!out.length) out.push(lerp(Math.max(from, start)));+ out.push(lerp(Math.min(to, end)));+ }+ return out;+ }++ function strokePolyline(ctx, points) {+ if (points.length < 2) return;+ ctx.beginPath();+ ctx.moveTo(points[0][0], points[0][1]);+ for (let index = 1; index < points.length; index += 1) {+ ctx.lineTo(points[index][0], points[index][1]);+ }+ ctx.stroke();+ }++ // Tile geometry in canvas pixels, shared by every instance of the tile.+ function buildRevealGeometry() {+ const scale = config.scale;+ return tile.traces.map((trace) => {+ const points = trace.points.map(([x, y]) => [x * scale, y * scale]);+ const cumulative = [0];+ for (let index = 1; index < points.length; index += 1) {+ cumulative.push(+ cumulative[index - 1] ++ Math.hypot(+ points[index][0] - points[index - 1][0],+ points[index][1] - points[index - 1][1],+ ),+ );+ }+ const anchor = trace.points[0] || trace.vias[0] || [0, 0];+ return {+ points,+ cumulative,+ length: cumulative[cumulative.length - 1] || 0,+ drawable: points.length >= 2,+ vias: trace.vias.map(([x, y]) => [x * scale, y * scale]),+ viaAt: viaDistances(trace).map((at) => at * scale),+ anchor: [anchor[0] * scale, anchor[1] * scale],+ };+ });+ }++ function finishReveal() {+ if (revealFrame) window.cancelAnimationFrame(revealFrame);+ revealFrame = 0;+ revealPlan = null;+ revealEndsAt = 0;+ if (svg) svg.style.opacity = "";+ if (revealCanvas) {+ revealCtx.clearRect(0, 0, viewWidth, viewHeight);+ revealCanvas.style.display = "none";+ // hand the backing stores back; runReveal sizes them again+ for (const canvas of [settledCanvas, ...heatCanvases, tipCanvas]) {+ canvas.width = 0;+ canvas.height = 0;+ }+ }+ }++ // Where the front starts: the pointer if it moved recently, else the middle.+ function revealFocus() {+ if (!pointer || performance.now() - pointer.at > 6000) {+ return [viewWidth / 2, viewHeight * 0.42];+ }+ return [pointer.x * config.scale, (pointer.y + topOffset) * config.scale];+ }++ // The stretch of a run between two arc lengths, in the direction it grows.+ function runPiece(run, from, to) {+ const length = run.geometry.length;+ return run.reverse+ ? segmentBetween(run.geometry, length - to, length - from, run.x, run.y)+ : segmentBetween(run.geometry, from, to, run.x, run.y);+ }++ // The lit stretch behind a route's leading edge — the same shape as a+ // signal's head, a fixed length travelling at a fixed speed.+ function headPiece(run, at, share = 1) {+ const geometry = run.geometry;+ const head = config.revealHead * config.scale * share;+ return run.reverse+ ? segmentBetween(+ geometry,+ geometry.length - at,+ geometry.length - Math.max(0, at - head),+ run.x,+ run.y,+ )+ : segmentBetween(geometry, Math.max(0, at - head), at, run.x, run.y);+ }++ function tickReveal(now) {+ const plan = revealPlan;+ if (!plan) return;+ const time = now - plan.start;+ const elapsed = Math.min(64, now - plan.frameAt);+ plan.frameAt = now;++ // A route starts growing when it is first DRAWN, not at the wall-clock+ // moment it was scheduled. Deriving growth from the schedule means any slow+ // frame — a GC pause, a busy tab, a laptop waking up — releases every route+ // whose start time has passed ALREADY FULLY GROWN: they pop into existence+ // instead of animating. Clamping the catch-up costs nothing when frames are+ // healthy (time == delay) and simply slides the schedule when they are not.+ while (plan.next < plan.instances.length && plan.instances[plan.next].delay <= time) {+ const entering = plan.instances[plan.next];+ entering.startedAt = Math.max(entering.delay, time - REVEAL_CATCHUP);+ entering.viaNext = 0; // its pads are timed off the same start+ plan.live.add(entering);+ plan.next += 1;+ }++ // The glow accumulates in a buffer and is faded a little every frame — one+ // fill, regardless of how much copper is warm. But a multiplicative fade+ // never reaches zero: at 8 bits a pixel stops moving as soon as+ // alpha x decay rounds back to itself (at a 150ms fade it sticks at 9/255 —+ // 3.5% of the hot colour sitting on the copper forever, which is why the+ // growing board read lighter and bluer than the finished one), and canvas+ // has no subtractive alpha op.+ //+ // So the buffer is kept in two GENERATIONS. New glow always goes into the+ // current one; the previous one keeps decaying but is also composited+ // through a falling ramp, and once that ramp reaches zero the buffer is+ // cleared outright — a multiply by zero, applied at the moment it changes+ // nothing on screen. Every pixel therefore ends at exactly zero, and the+ // per-frame cost stays independent of how much of the board is glowing.+ if (+ plan.allLandedAt === undefined &&+ plan.next >= plan.instances.length &&+ plan.live.size === 0+ ) {+ plan.allLandedAt = time + config.revealBlip; // let the last pads ring out+ // a slid schedule moves the real end, and the signals wait on that+ revealEndsAt =+ plan.start + Math.max(plan.last, plan.allLandedAt) + plan.handoff + REVEAL_HANDOFF;+ }+ const tail = time - Math.max(plan.last, plan.allLandedAt ?? Infinity);+ const heatOut = tail > 0 ? clamp(tail / plan.handoff, 0, 1) : 0;+ // during the tail the time constant tightens, so whatever glow is left+ // finishes cooling instead of being cut off by the handoff+ const constant = Math.max(24, config.revealCool * (1 - 0.92 * heatOut));+ const fade = 1 - Math.exp(-elapsed / constant);+ for (const ctx of plan.heat) {+ ctx.globalCompositeOperation = "destination-out";+ ctx.fillStyle = `rgba(0,0,0,${fade})`;+ ctx.fillRect(0, 0, viewWidth, viewHeight);+ ctx.globalCompositeOperation = "source-over";+ }++ // Rotate generations once the older one is contributing nothing. The window+ // is several time constants wide: by the time a pixel's generation starts+ // ramping out, its own decay has it near zero anyway, so the ramp costs no+ // visible wake — it only guarantees the buffer can be cleared outright.+ const span = clamp(constant * 4, 300, 8000);+ let phase = clamp((time - plan.heatSwappedAt) / span, 0, 1);+ if (phase >= 1) {+ const retiring = plan.heat[1 - plan.heatIndex];+ retiring.clearRect(0, 0, viewWidth, viewHeight); // x0, and invisible by now+ plan.heatIndex = 1 - plan.heatIndex;+ plan.heatSwappedAt = time;+ phase = 0;+ }+ const heatCtx = plan.heat[plan.heatIndex];++ // Copper is laid at a constant speed, exactly like a signal travelling a+ // trace: linear, never eased, never scaled by the route's length.+ //+ // Only the GLOW is stroked incrementally — it is transient, so its edges+ // blending over each other costs nothing. The copper that SURVIVES is not:+ // a route is stamped into the persistent layer exactly once, when it lands,+ // with the artwork's own butt caps and miter joins. Laying it in per-frame+ // pieces blended each piece's antialiased edge over the last one, which made+ // the finished canvas board ~1% denser than the SVG it hands over to — not a+ // colour difference, but enough extra weight to read as one.+ settledCtx.lineWidth = config.traceWidth * config.scale;+ settledCtx.lineCap = "butt";+ settledCtx.lineJoin = "miter";+ heatCtx.lineWidth = config.traceWidth * config.revealSwell * config.scale;+ heatCtx.lineCap = "round";+ heatCtx.lineJoin = "round";+ for (const run of plan.live) {+ const geometry = run.geometry;+ const grown = Math.min(geometry.length, (time - run.startedAt) * plan.speed);+ if (grown > run.drawn) {+ heatCtx.strokeStyle = run.hot;+ strokePolyline(heatCtx, runPiece(run, run.drawn, grown));+ run.drawn = grown;+ }+ if (grown >= geometry.length) {+ settledCtx.strokeStyle = run.settled;+ strokePolyline(settledCtx, runPiece(run, 0, geometry.length));+ run.landedAt = run.startedAt + geometry.length / plan.speed;+ plan.live.delete(run);+ plan.fading.add(run); // its head fades out instead of vanishing+ }+ }+ for (const run of plan.fading) {+ if (time - run.landedAt > REVEAL_FADE_OUT) plan.fading.delete(run);+ }++ // Pads land as the tip passes them — timed against the route's actual+ // start, so a route that began late does not sprinkle its pads early.+ for (const run of [...plan.live, ...plan.fading]) {+ const pads = run.geometry.pads;+ while (run.viaNext < pads.length && run.startedAt + pads[run.viaNext].offset <= time) {+ const pad = pads[run.viaNext];+ plan.popping.add({+ x: run.x + pad.x,+ y: run.y + pad.y,+ at: run.startedAt + pad.offset,+ hot: run.hot,+ settled: run.settled,+ });+ run.viaNext += 1;+ }+ }+ // Pad-only formations have no route to follow, so they keep their schedule.+ while (plan.nextVia < plan.vias.length && plan.vias[plan.nextVia].at <= time) {+ plan.popping.add(plan.vias[plan.nextVia]);+ plan.nextVia += 1;+ }++ tipCtx.clearRect(0, 0, viewWidth, viewHeight);+ tipCtx.lineCap = "round";+ tipCtx.lineJoin = "round";++ // Copper of routes still growing, redrawn whole each frame — never in+ // per-frame pieces, whose antialiased edges would blend over each other.+ // `destination-over` puts it BEHIND the glow already in the buffer: a+ // growing trace has to read as hot metal, and copper painted over its own+ // glow reads as an outline. Redrawing also tops it back up against the+ // buffer's fade, so it holds full strength until it lands.+ heatCtx.globalCompositeOperation = "destination-over";+ heatCtx.lineWidth = config.traceWidth * config.scale;+ heatCtx.lineCap = "round";+ for (const run of plan.live) {+ heatCtx.strokeStyle = run.settled;+ strokePolyline(heatCtx, runPiece(run, 0, run.drawn));+ }+ heatCtx.globalCompositeOperation = "source-over";++ // Heads: a wide soft glow and a white-hot core, matching a signal's stack.+ // Alpha eases in as a route starts and out after it lands, so no head ever+ // appears or disappears in a single frame.+ const brightness = (run) =>+ run.landedAt === undefined+ ? clamp((time - run.startedAt) / REVEAL_FADE_IN, 0, 1)+ : 1 - clamp((time - run.landedAt) / REVEAL_FADE_OUT, 0, 1);+ if (config.revealSpark) {+ for (const pass of [+ { width: 7 * config.scale, alpha: config.revealBloom, colour: null },+ { width: 2.4 * config.scale, alpha: 0.85, colour: config.revealTip, share: 0.45 },+ ]) {+ tipCtx.lineWidth = pass.width;+ if (pass.colour) tipCtx.strokeStyle = pass.colour;+ for (const run of [...plan.live, ...plan.fading]) {+ const alpha = pass.alpha * brightness(run);+ if (alpha <= 0.01) continue;+ tipCtx.globalAlpha = alpha;+ if (!pass.colour) tipCtx.strokeStyle = run.hot;+ strokePolyline(tipCtx, headPiece(run, run.drawn, pass.share || 1));+ }+ }+ tipCtx.globalAlpha = 1;+ }++ // A pad grows into place and rings out — the same arrival blip the live+ // signals use — and is only stamped into the settled layer once it has+ // finished, so it never pops.+ const viaRadius = config.viaOuterRadius * config.scale;+ const holeRadius = config.viaInnerRadius * config.scale;+ for (const via of plan.popping) {+ const progress = clamp((time - via.at) / config.revealBlip, 0, 1);+ const pop = clamp((time - via.at) / (config.revealBlip * 0.42), 0, 1);+ const eased = easeOut(pop);+ tipCtx.globalAlpha = eased;+ tipCtx.fillStyle = via.hot;+ tipCtx.beginPath();+ tipCtx.arc(via.x, via.y, viaRadius * (0.25 + 0.75 * eased), 0, Math.PI * 2);+ tipCtx.fill();+ // The pad is annular from the first frame: drilling the hole only when+ // the pop finished made every via change shape as it landed.+ tipCtx.globalCompositeOperation = "destination-out";+ tipCtx.beginPath();+ tipCtx.arc(via.x, via.y, holeRadius * (0.25 + 0.75 * eased), 0, Math.PI * 2);+ tipCtx.fill();+ tipCtx.globalCompositeOperation = "source-over";+ // The ring: from the pad out to ~8 units, fading, ease-out over revealBlip.+ const ring = easeOut(progress);+ tipCtx.globalAlpha = 0.6 * (1 - progress) * Math.min(1, progress * 6);+ tipCtx.lineWidth = 1.5 * config.scale;+ tipCtx.strokeStyle = via.hot;+ tipCtx.beginPath();+ tipCtx.arc(via.x, via.y, (config.viaOuterRadius + 5 * ring) * config.scale, 0, Math.PI * 2);+ tipCtx.stroke();+ if (progress >= 1) {+ settledCtx.fillStyle = via.settled;+ settledCtx.beginPath();+ settledCtx.arc(via.x, via.y, viaRadius, 0, Math.PI * 2);+ settledCtx.fill();+ settledCtx.fillStyle = plan.hole;+ settledCtx.beginPath();+ settledCtx.arc(via.x, via.y, holeRadius, 0, Math.PI * 2);+ settledCtx.fill();+ plan.popping.delete(via);+ }+ }+ tipCtx.globalAlpha = 1;++ // The board fades out under the growth at the start. At the end the REAL+ // board comes up to full opacity the instant growth finishes — invisibly,+ // under a canvas that is still opaque and holds the same copper in the same+ // colour — and only then does the canvas leave. Cross-fading the two+ // against each other instead dips the copper to ~75% mid-fade (alpha+ // compositing is not additive), which is what read as a hard swap.+ const opening = clamp(time / REVEAL_CLEAR, 0, 1);+ const settleOut = clamp((tail - plan.handoff) / REVEAL_HANDOFF, 0, 1);+ const canvasAlpha = 1 - smoothstep(settleOut);+ revealCtx.clearRect(0, 0, viewWidth, viewHeight);+ // Bottom to top: landed copper, the retiring glow generation on its way out,+ // the current one, then the heads and pads. The heat buffers are not+ // decoration — a route's copper lives ONLY there until it lands, so leaving+ // them out of this composite makes every route invisible while it grows and+ // then appear whole the instant it is stamped into the settled layer.+ revealCtx.globalAlpha = canvasAlpha;+ revealCtx.drawImage(settledCanvas, 0, 0, viewWidth, viewHeight);+ revealCtx.globalAlpha = canvasAlpha * (1 - smoothstep(phase));+ revealCtx.drawImage(plan.heatCanvas[1 - plan.heatIndex], 0, 0, viewWidth, viewHeight);+ revealCtx.globalAlpha = canvasAlpha;+ revealCtx.drawImage(plan.heatCanvas[plan.heatIndex], 0, 0, viewWidth, viewHeight);+ revealCtx.drawImage(tipCanvas, 0, 0, viewWidth, viewHeight);+ revealCtx.globalAlpha = 1;+ if (svg) svg.style.opacity = tail > 0 ? "1" : `${1 - opening}`;++ if (settleOut >= 1) {+ finishReveal();+ return;+ }+ revealFrame = window.requestAnimationFrame(tickReveal);+ }++ // Hide the finished board and grow it back in.+ function runReveal() {+ finishReveal();+ if (config.reveal === "off" || reducedMotion || !tile.traces.length) return;+ ensureRevealCanvas();+ sizeRevealCanvas();+ revealCanvas.style.display = "block";+ for (const ctx of [settledCtx, ...heatContexts, tipCtx]) {+ ctx.clearRect(0, 0, viewWidth, viewHeight);+ }++ const revealRandom = mulberry32(hashSeed(`${config.seed}:reveal:${config.reveal}`));+ const geometry = buildRevealGeometry();+ const depths =+ config.reveal === "flood"+ ? floodDepths(+ tile,+ tile.traces.map((trace) => trace.points[0] || trace.vias[0] || [0, 0]),+ revealSeed(),+ )+ : null;+ const [focusX, focusY] = revealFocus();+ const tileWidth = tile.width * config.scale;+ const tileHeight = tile.height * config.scale;+ const hop = tile.pitch * config.scale * 3; // how far one flood hop reaches++ const ramp = config.revealPalette.map(parseHex);+ const board = parseHex(config.traceColor);+ const zoneAt = makeZoneField(viewWidth, viewHeight, config.revealZone, revealRandom);++ // One run per (route x screen tile): the whole visible background, each+ // piece scheduled and coloured by where it actually sits on screen.+ const runs = [];+ for (let row = -1; row <= tilesDown; row += 1) {+ for (let column = -1; column <= tilesAcross; column += 1) {+ const x = column * tileWidth;+ const y = row * tileHeight + topOffset * config.scale;+ if (x > viewWidth || y > viewHeight) continue;+ if (x + tileWidth < 0 || y + tileHeight < 0) continue;+ geometry.forEach((entry, index) => {+ // Clamped to the visible area: the ring of tiles that only exists to+ // paint wrap-around copper sits off screen, and scheduling it by its+ // true position spends the first beat of the reveal out of frame.+ const anchorX = clamp(x + entry.anchor[0], 0, viewWidth);+ const anchorY = clamp(y + entry.anchor[1], 0, viewHeight);+ let metric;+ if (config.reveal === "sweep") {+ metric = anchorX * 0.94 + anchorY * 0.34;+ } else if (config.reveal === "scatter") {+ metric = revealRandom() * 1e6;+ } else if (config.reveal === "etch") {+ // The router's own passes, replayed everywhere at once.+ metric = index * 1e3 + Math.hypot(anchorX - focusX, anchorY - focusY) * 0.05;+ } else if (config.reveal === "flood") {+ // Outward through the copper: distance from the seed, nudged by how+ // many hops of routing separate this trace from its tile's seed.+ metric = Math.hypot(anchorX - focusX, anchorY - focusY) + depths[index] * hop;+ } else {+ metric = Math.hypot(anchorX - focusX, anchorY - focusY);+ }+ const zone = rampAt(ramp, zoneAt(anchorX, anchorY));+ runs.push({+ geometry: entry,+ x,+ y,+ metric,+ jitter: revealRandom(),+ nudge: revealRandom(),+ hot: rgbCss(zone),+ settled: rgbCss(mixRgb(zone, board, config.revealSettle)),+ });+ });+ }+ }+ runs.sort((a, b) => a.metric - b.metric || a.jitter - b.jitter);++ // Every tip travels at the same speed, so a route's duration is simply its+ // length. The longest route sets how much of the window is left for+ // staggering starts, which keeps revealDuration honest end to end.+ const speed = (config.revealSpeed * config.scale) / 1000; // px per ms+ let longest = 0;+ for (const run of runs) longest = Math.max(longest, run.geometry.length / speed);++ // Spread start times by INK rather than by count: a third of the records+ // are pad-only formations, and pacing by count spends a third of the reveal+ // sprinkling vias with nothing drawing.+ const lengths = geometry.map((entry) => entry.length).sort((a, b) => a - b);+ const median = Math.max(1, lengths[Math.floor(lengths.length / 2)] || 1);+ const padWeight = median * 0.15;+ let total = 0;+ for (const run of runs) total += run.geometry.length + padWeight;+ const window_ = Math.max(0, config.revealDuration - longest);++ let cursor = 0;+ for (const run of runs) {+ run.duration = run.geometry.length / speed;+ run.delay = Math.max(0, (cursor / total) * window_ + (run.nudge - 0.5) * REVEAL_JITTER);+ run.reverse = run.jitter < 0.5;+ run.drawn = 0;+ run.landedAt = undefined;+ cursor += run.geometry.length + padWeight;+ }++ // Stretch the schedule so the last route lands exactly on revealDuration.+ // Reserving the longest route's travel time up front only guarantees the+ // board finishes no LATER than promised — and since the longest route+ // usually starts early, the board was landing well before the knob's time,+ // making the same setting mean different things for different seeds.+ let stretch = Infinity;+ for (const run of runs) {+ if (run.delay > 0) {+ stretch = Math.min(stretch, (config.revealDuration - run.duration) / run.delay);+ }+ }+ if (Number.isFinite(stretch) && stretch > 0) {+ for (const run of runs) run.delay *= stretch;+ }++ const vias = [];+ let last = 0;+ for (const run of runs) {+ last = Math.max(last, run.delay + run.duration);+ const drawable = run.geometry.drawable;+ const pads = drawable ? [] : null;+ run.geometry.viaAt.forEach((at, viaIndex) => {+ const along = run.geometry.length ? clamp(at / run.geometry.length, 0, 1) : 0;+ const offset = run.duration * (run.reverse ? 1 - along : along);+ if (drawable) {+ pads.push({ x: run.geometry.vias[viaIndex][0], y: run.geometry.vias[viaIndex][1], offset });+ } else {+ vias.push({+ x: run.x + run.geometry.vias[viaIndex][0],+ y: run.y + run.geometry.vias[viaIndex][1],+ at: run.delay + offset,+ hot: run.hot,+ settled: run.settled,+ });+ }+ });+ if (drawable) {+ pads.sort((a, b) => a.offset - b.offset);+ // the geometry object is shared by every screen tile, so the schedule+ // lives on the run's own copy+ run.geometry = { ...run.geometry, pads };+ }+ }+ vias.sort((a, b) => a.at - b.at);++ revealPlan = {+ start: performance.now(),+ frameAt: performance.now(),+ // Sorted by DELAY, not by metric. The release loop walks this queue with a+ // single cursor, so an unsorted queue head-of-line blocks: jitter is ~80x+ // wider than the gap between neighbouring start times, which left 84% of+ // the queue out of order and held routes back up to 71ms behind the head,+ // then let them out in one burst — the opposite of what the jitter is for.+ instances: runs.filter((run) => run.geometry.drawable).sort((a, b) => a.delay - b.delay),+ vias,+ next: 0,+ nextVia: 0,+ live: new Set(),+ fading: new Set(),+ popping: new Set(),+ heat: heatContexts,+ heatCanvas: heatCanvases,+ heatIndex: 0,+ heatSwappedAt: 0,+ speed,+ // Long enough for the remaining glow to finish cooling as glow, never a+ // wait. The floor used to be 260ms, which at a very short heat fade left+ // the finished board sitting there for ~150ms with nothing left to cool.+ handoff: clamp(config.revealCool * 1.6, 120, 1100),+ // the SVG fills via holes with var(--circuit-hole); read the same value+ // rather than assuming the default+ hole:+ getComputedStyle(mount).getPropertyValue("--circuit-hole").trim() ||+ config.holeColor ||+ "#0d1117",+ // The last pad still has to ring out before the board settles.+ last: last + config.revealBlip,+ };+ revealEndsAt = revealPlan.start + revealPlan.last + revealPlan.handoff + REVEAL_HANDOFF;+ revealFrame = window.requestAnimationFrame(tickReveal);+ }++ function layout() {+ // The observer also fires when the box did not actually change; only a real+ // resize should interrupt the growth (the copper already laid would no+ // longer line up), and it settles rather than restarting.+ if (+ revealPlan &&+ (Math.abs(mount.clientWidth - viewWidth) > 2 || Math.abs(mount.clientHeight - viewHeight) > 2)+ ) {+ finishReveal();+ }+ const width = Math.max(1, mount.clientWidth);+ const height = Math.max(1, mount.clientHeight);+ const tilePixelWidth = tile.width * config.scale;+ const tilePixelHeight = tile.height * config.scale;+ tilesAcross = Math.max(1, Math.ceil(width / tilePixelWidth));+ tilesDown = Math.max(2, Math.ceil(height / tilePixelHeight) + 1);+ topOffset = -tile.height / 2;+ const viewWidth = tilesAcross * tile.width;+ const viewHeight = tilesDown * tile.height;++ svg.setAttribute("width", `${viewWidth * config.scale}`);+ svg.setAttribute("height", `${viewHeight * config.scale}`);+ svg.setAttribute("viewBox", `0 ${-topOffset} ${viewWidth} ${viewHeight}`);+ usesGroup.replaceChildren();+ // The extra ring of tiles paints the traces that wrap in from neighbors.+ for (let row = -1; row <= tilesDown; row += 1) {+ for (let column = -1; column <= tilesAcross; column += 1) {+ usesGroup.appendChild(+ svgEl("use", {+ href: `#${id}-tile`,+ transform: `translate(${column * tile.width}, ${row * tile.height})`,+ }),+ );+ }+ }+ }++ // Pointer-biased launch pad: candidates are scored by the distance from+ // the ACTUAL launch point (a trace end, not the trace middle) to the+ // cursor, plus spawnRadius worth of jitter — so spawns cluster within+ // roughly spawnRadius of the pointer without a hard cutoff.+ function pickStart() {+ const { dense } = ensureSignalIndex(tile);+ const nearPointer = pointer && performance.now() - pointer.at < 4000;+ let choice = null;+ let bestScore = Infinity;+ const tries = nearPointer ? 40 : 4;+ for (let attempt = 0; attempt < tries; attempt += 1) {+ const trace = Math.floor(random() * dense.length);+ const tileX = Math.floor(random() * tilesAcross);+ const tileY = Math.floor(random() * tilesDown);+ if (dense[trace].length < 6) continue;+ const fromStart = random() < 0.5;+ const candidate = {+ trace,+ tileX,+ tileY,+ point: fromStart ? 0 : dense[trace].length - 1,+ direction: fromStart ? 1 : -1,+ };+ if (!nearPointer) return candidate;+ const [padX, padY] = dense[trace][candidate.point];+ const score =+ Math.hypot(padX + tileX * tile.width - pointer.x, padY + tileY * tile.height - pointer.y) ++ config.spawnRadius * random();+ if (score < bestScore) {+ bestScore = score;+ choice = candidate;+ }+ }+ return choice;+ }++ // Launch pads (trace-end vias) near an ended signal, closest first, so the+ // replacement reads as the signal hopping vias onto a neighboring trace.+ function nearbyEndpointStarts(absX, absY, excludeTrace) {+ const { endpoints } = ensureSignalIndex(tile);+ const baseTileX = Math.floor(absX / tile.width);+ const baseTileY = Math.floor(absY / tile.height);+ const candidates = [];+ for (let tileY = baseTileY - 1; tileY <= baseTileY + 1; tileY += 1) {+ for (let tileX = baseTileX - 1; tileX <= baseTileX + 1; tileX += 1) {+ const localX = absX - tileX * tile.width;+ const localY = absY - tileY * tile.height;+ for (const endpoint of endpoints) {+ if (endpoint.trace === excludeTrace) continue;+ const distance = Math.hypot(endpoint.x - localX, endpoint.y - localY);+ if (distance > 2 && distance < config.hopRadius) {+ candidates.push({ endpoint, tileX, tileY, distance: distance + random() * 20 });+ }+ }+ }+ }+ candidates.sort((a, b) => a.distance - b.distance);+ return candidates.slice(0, 6).map((pick) => ({+ trace: pick.endpoint.trace,+ tileX: pick.tileX,+ tileY: pick.tileY,+ point: pick.endpoint.point,+ direction: pick.endpoint.direction,+ }));+ }++ // phase (0..1) fast-forwards the animation so boot signals are already+ // mid-journey. A chain keeps its speedFactor, color AND survival rate across+ // hops — the signal that entered blue exits blue, and a click-born chain+ // keeps decaying at burstSurvival while ambient chains use hopSurvival.+ // Occasionally (colorDrift) a leg crossfades to a new color over its whole+ // run, so palettes shift gradually, never pop.+ function launchSignal(path, phase = 0, speedFactor, chainColor, survival) {+ const factor = speedFactor ?? 0.85 + random() * 0.3;+ const surviveChance = survival ?? config.hopSurvival;+ const colorFrom = chainColor ?? weightedChoice(random, config.signalColors);+ const colorTo =+ random() < config.colorDrift ? weightedChoice(random, config.signalColors) : colorFrom;+ const d = pathData(path.points);+ const speed = config.signalSpeed * factor;+ const head = config.signalLength;+ const tail = head * 2.2;+ const length = path.length;+ const total = length + tail;+ const duration = (total / speed) * 1000;+ const group = svgEl("g");+ // Faint persistent wake along the whole route.+ const wake = svgEl("path", { d, stroke: colorFrom, "stroke-width": 2, opacity: 0 });+ // Soft glow under the head — a wide translucent stroke is far cheaper+ // than a drop-shadow filter re-rasterizing every frame.+ const glow = svgEl("path", {+ d,+ stroke: colorFrom,+ "stroke-width": 7,+ "stroke-linecap": "round",+ "stroke-opacity": 0.1,+ "stroke-dasharray": `${head} ${total}`,+ "stroke-dashoffset": head,+ });+ // Long dim comet tail behind the head.+ const comet = svgEl("path", {+ d,+ stroke: colorFrom,+ "stroke-width": 2,+ "stroke-linecap": "round",+ "stroke-opacity": 0.16,+ "stroke-dasharray": `${tail} ${total}`,+ "stroke-dashoffset": tail,+ });+ // Bright head.+ const pulse = svgEl("path", {+ d,+ stroke: colorFrom,+ "stroke-width": 2.4,+ "stroke-linecap": "round",+ "stroke-dasharray": `${head} ${total}`,+ "stroke-dashoffset": head,+ "stroke-opacity": 0.72,+ });+ group.append(wake, glow, comet, pulse);+ signalGroup.appendChild(group);+ activeSignals += 1;++ // All layers share the same leading edge; each runs from its own dash+ // length down to -(total - itsDash) so they exit together. Color rides+ // along in the same keyframes when this leg is a crossfade.+ const timing = { duration, easing: "linear", fill: "forwards" };+ const animations = [+ pulse.animate(+ [+ { strokeDashoffset: head, stroke: colorFrom },+ { strokeDashoffset: head - total, stroke: colorTo },+ ],+ timing,+ ),+ glow.animate(+ [+ { strokeDashoffset: head, stroke: colorFrom },+ { strokeDashoffset: head - total, stroke: colorTo },+ ],+ timing,+ ),+ comet.animate(+ [+ { strokeDashoffset: tail, stroke: colorFrom },+ { strokeDashoffset: tail - total, stroke: colorTo },+ ],+ timing,+ ),+ wake.animate(+ [+ { opacity: 0, stroke: colorFrom },+ { opacity: 0.06 },+ { opacity: 0.06 },+ { opacity: 0, stroke: colorTo },+ ],+ { duration, fill: "forwards" },+ ),+ ];+ const headArrival = (duration * length) / total;+ const skip = Math.min(phase, 0.95) * headArrival;+ if (skip > 0) for (const animation of animations) animation.currentTime = skip;++ // The signal is logically done when its head reaches the final via (the+ // tail after that is just residue): blip, release its population slot,+ // and — in the same beat — launch its successor from a nearby via. The+ // handoff is synchronous so motion never pauses.+ const [endX, endY] = path.points[path.points.length - 1];+ const myEpoch = epoch;+ window.setTimeout(() => {+ if (myEpoch !== epoch) return;+ activeSignals -= 1;+ const blip = svgEl("circle", {+ cx: endX,+ cy: endY,+ r: 2,+ fill: "none",+ stroke: colorTo,+ "stroke-width": 1.5,+ "stroke-opacity": 0.6,+ });+ group.appendChild(blip);+ blip.animate(+ [+ { r: 2, strokeOpacity: 0.6 },+ { r: 8, strokeOpacity: 0 },+ ],+ { duration: 500, easing: "ease-out", fill: "forwards" },+ );+ // The successor inherits the color the chain ARRIVED with.+ continueChain(endX, endY, path.startTrace, factor, colorTo, surviveChance);+ }, headArrival - skip);++ window.setTimeout(() => {+ group.remove();+ }, duration + 620 - skip);+ }++ // Every signal is mortal: on each via hop it rolls against its chain's+ // survival rate (hopSurvival for ambient chains, burstSurvival for+ // click-born ones — passed in so a chain keeps its own decay for life).+ // Survivors continue synchronously from a nearby via, inheriting speed and+ // color (arrive blue → depart blue); the rest just die with their arrival+ // blip. Replenishment is NOT done here — the ambient spawn timer refills+ // the population near the cursor, so a death simply lowers the census and+ // the next tick fountains a fresh signal in. Low survival => most signals+ // die after one leg => the fountain stays busy near the pointer.+ function continueChain(endX, endY, excludeTrace, speedFactor, chainColor, survival) {+ if (!config.signals || reducedMotion || document.hidden) return;+ if (random() >= (survival ?? config.hopSurvival)) return;+ if (activeSignals >= config.maxBurstSignals) return;+ spawnSignal(nearbyEndpointStarts(endX, endY, excludeTrace), 0, speedFactor, chainColor, survival);+ }++ // preferred: array of nearby launch pads tried in order (short legs are+ // fine for chain continuations); falls back to random picks elsewhere.+ function spawnSignal(preferred, phase = 0, speedFactor, chainColor, survival) {+ if (!config.signals || reducedMotion) return false;+ if (activeSignals >= config.maxBurstSignals) return false;+ const preferredCount = preferred ? preferred.length : 0;+ const candidates = preferred ? [...preferred] : [];+ for (let attempt = 0; attempt < 8; attempt += 1) {+ const start = pickStart();+ if (start) candidates.push(start);+ }+ for (let index = 0; index < candidates.length; index += 1) {+ const minLength = index < preferredCount ? 60 : 140;+ const path = buildSignalPath(tile, candidates[index], 450 + random() * 900, minLength);+ if (path) {+ path.startTrace = candidates[index].trace;+ launchSignal(path, phase, speedFactor, chainColor, survival);+ return true;+ }+ }+ return false;+ }++ // Fill the population up to maxSignals with fast-forwarded signals, so a+ // fresh board (or a tab returning to view after its chains drained) is+ // already mid-journey instead of visibly cold-starting.+ function prewarm() {+ if (!config.signals || reducedMotion || document.hidden) return;+ let guard = 0;+ while (activeSignals < config.maxSignals && guard < config.maxSignals + 2) {+ guard += 1;+ if (!spawnSignal(null, random() * 0.85)) break;+ }+ }++ // The passive fountain, like the reference site: a steady cadence of new+ // signals near the cursor (pickStart biases toward the pointer when it moved+ // recently, spreads across the board when idle), refilling toward+ // maxSignals. Because signals are mortal, the census keeps dipping below the+ // target and the timer keeps topping it up — so fresh signals keep appearing+ // at the pointer. The balance the user wants is fast spawn + short life:+ // a small signalInterval with a low hopSurvival gives a lively cursor+ // fountain; long life lets the population sit at the cap and spawn rarely.+ // warm: fast-forward a full population in (right for a cold page). After a+ // reveal it is passed false, so the fountain fills from empty at its own+ // cadence instead of a dozen signals appearing mid-flight the instant the+ // board settles.+ function startSignals(warm = true) {+ window.clearInterval(signalTimer);+ window.clearTimeout(signalStartTimer);+ if (!config.signals || reducedMotion) return;+ // Signals wait for the board they ride to finish growing in — a pulse+ // running down a trace that is not there yet reads as a glitch.+ const pending = revealEndsAt - performance.now();+ if (pending > 0) {+ const myEpoch = epoch;+ signalStartTimer = window.setTimeout(() => {+ if (myEpoch === epoch) startSignals(false);+ }, pending + 80);+ return;+ }+ if (warm) prewarm();+ signalTimer = window.setInterval(() => {+ if (!document.hidden && activeSignals < config.maxSignals) spawnSignal(null);+ }, config.signalInterval);+ }++ function burstAt(x, y) {+ const { dense } = ensureSignalIndex(tile);+ const candidates = [];+ const baseTileX = Math.floor(x / tile.width);+ const baseTileY = Math.floor(y / tile.height);+ for (let tileY = baseTileY - 1; tileY <= baseTileY + 1; tileY += 1) {+ for (let tileX = baseTileX - 1; tileX <= baseTileX + 1; tileX += 1) {+ if (tileX < -1 || tileX > tilesAcross || tileY < -1 || tileY > tilesDown) continue;+ const localX = x - tileX * tile.width;+ const localY = y - tileY * tile.height;+ for (let trace = 0; trace < dense.length; trace += 1) {+ let bestPoint = -1;+ let bestDistance = 40;+ for (let point = 0; point < dense[trace].length; point += 1) {+ const distance = Math.hypot(dense[trace][point][0] - localX, dense[trace][point][1] - localY);+ if (distance < bestDistance) {+ bestDistance = distance;+ bestPoint = point;+ }+ }+ if (bestPoint >= 0) candidates.push({ trace, tileX, tileY, point: bestPoint, distance: bestDistance });+ }+ }+ }+ candidates.sort((a, b) => a.distance - b.distance);+ let spawned = 0;+ for (const candidate of candidates.slice(0, Math.ceil(config.burstBoost / 2) + 1)) {+ for (const direction of [1, -1]) {+ if (activeSignals >= config.maxBurstSignals || spawned >= config.burstBoost) return;+ const path = buildSignalPath(+ tile,+ { trace: candidate.trace, tileX: candidate.tileX, tileY: candidate.tileY, point: candidate.point, direction },+ 260 + random() * 380,+ 50,+ );+ if (path) {+ path.startTrace = candidate.trace;+ // Clicked chains decay at burstSurvival, independent of the ambient+ // hopSurvival, so a click can ripple long even when passive life is short.+ launchSignal(path, 0, undefined, undefined, config.burstSurvival);+ spawned += 1;+ }+ }+ }+ }++ function onPointerMove(event) {+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / config.scale,+ y: (event.clientY - rect.top) / config.scale - topOffset,+ at: performance.now(),+ };+ }++ function onClick(event) {+ if (!config.interactive || !config.signals || reducedMotion) return;+ const rect = mount.getBoundingClientRect();+ burstAt(+ (event.clientX - rect.left) / config.scale,+ (event.clientY - rect.top) / config.scale - topOffset,+ );+ }++ function onVisibility() {+ if (!document.hidden) prewarm();+ }++ function regenerate(nextOptions = {}) {+ config = { ...config, ...nextOptions };+ buildSvg();+ startSignals();+ return api;+ }++ function exportSvg() {+ finishReveal(); // never export a half-grown board+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("g[fill='none'] > g").forEach((node) => node.remove());+ clone.removeAttribute("style");+ clone.setAttribute("width", String(tilesAcross * tile.width * config.scale));+ clone.setAttribute("height", String(tilesDown * tile.height * config.scale));+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function exportTileSvg(tileOptions = {}) {+ return tileSvg(tile, { ...config, ...tileOptions });+ }++ function destroy() {+ epoch += 1;+ finishReveal();+ revealCanvas?.remove();+ window.clearInterval(signalTimer);+ window.clearTimeout(signalStartTimer);+ document.removeEventListener("visibilitychange", onVisibility);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("click", onClick);+ svg?.remove();+ if (computedPosition === "static") mount.style.position = originalPosition;+ }++ // Replay the reveal on the board that is already up — no re-routing, so+ // the same artwork grows back in (optionally in a different style).+ function replayReveal(style) {+ if (style) config.reveal = style;+ runReveal();+ startSignals();+ return api;+ }++ const api = {+ regenerate,+ replayReveal,+ spawnSignal,+ exportSvg,+ exportTileSvg,+ destroy,+ get tile() {+ return tile;+ },+ };+ buildSvg();+ resizeObserver = new ResizeObserver(layout);+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ // Hidden tabs let the census drain (the timer no-ops); refill on return.+ document.addEventListener("visibilitychange", onVisibility);+ startSignals();+ return api;+}++// Named animation presets. Each is a partial config merged over the current+// settings; only signal/animation knobs are touched so generation geometry is+// left alone. `signals: false` gives a fully static board.+const ANIMATION_PRESETS = Object.freeze({+ "None": { signals: false },+ "Fireflies": {+ // A few long-lived signals drifting/bouncing across the whole screen.+ signals: true,+ signalInterval: 850,+ maxSignals: 5,+ spawnRadius: 200,+ hopSurvival: 0.92,+ burstSurvival: 0.9,+ colorDrift: 0.12,+ },+ "Swarm": {+ // Same persistent drift, but a dense population.+ signals: true,+ signalInterval: 360,+ maxSignals: 18,+ spawnRadius: 200,+ hopSurvival: 0.9,+ burstSurvival: 0.9,+ colorDrift: 0.18,+ },+ "Cursor sparks": {+ // Really short life + very fast spawning tight around the cursor.+ signals: true,+ signalInterval: 90,+ maxSignals: 14,+ spawnRadius: 35,+ hopSurvival: 0.1,+ burstSurvival: 0.6,+ colorDrift: 0.15,+ },+ "Slow streams": {+ // Longer-lived flowing chains at a relaxed cadence.+ signals: true,+ signalInterval: 560,+ maxSignals: 8,+ spawnRadius: 130,+ hopSurvival: 0.72,+ burstSurvival: 0.82,+ colorDrift: 0.2,+ },+});++// Named reveal styles: how the finished board grows in. Only the order and+// the pacing differ — the drawing mechanic (each trace out of an end via,+// spark on the tip, pads popping as it passes) is shared.+const REVEAL_PRESETS = Object.freeze({+ "Instant": { reveal: "off" },+ "Etch": {+ // Build order: pads and formations, then the nets between them, then+ // filler, then the tap combs — the router's own passes, replayed.+ reveal: "etch",+ revealDuration: 3200,+ },+ "Flood": {+ // The front spreads through the routing's own adjacency, so the board+ // wets outward from a seed like current finding copper.+ reveal: "flood",+ revealDuration: 3400,+ },+ "Sweep": {+ // A shallow diagonal scan line crossing the tile.+ reveal: "sweep",+ revealDuration: 3000,+ },+ "Bloom": {+ // Rings expanding from the cursor (or the tile centre when idle).+ reveal: "bloom",+ revealDuration: 3200,+ },+ "Scatter": {+ // No order at all — the whole board stipples in at once.+ reveal: "scatter",+ revealDuration: 2600,+ },+});++export { DEFAULTS, ANIMATION_PRESETS, REVEAL_PRESETS };
src/circuit-background-v6.jsadded+461@@ -0,0 +1,461 @@+import { createConductorAnimation } from "./circuit-animation-conductor.js?v=1";+import { createHandshakeAnimation } from "./circuit-animation-handshake.js?v=2";+import { createTraceGrowthAnimation } from "./circuit-animation-growth.js?v=1";+import {+ createReflectionAnimation,+ REFLECTION_DEFAULTS,+} from "./circuit-animation-reflection.js?v=1";+import {+ createCircuitBackground as createLegacyCircuitBackground,+ DEFAULTS as GEOMETRY_DEFAULTS,+ ANIMATION_PRESETS as LEGACY_ANIMATION_PRESETS,+ generateCircuitField,+ pathData,+} from "./circuit-background-v4.js?geometry=1";++const SVG_NS = "http://www.w3.org/2000/svg";++const DEFAULTS = Object.freeze({+ ...GEOMETRY_DEFAULTS,+ animationSystem: "none",+ motion: false,+ liveliness: 0,+ atmosphereStrength: 0,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ growthDuration: 7600,+ growthGlow: 0.82,+ ...REFLECTION_DEFAULTS,+});++const ANIMATION_PRESETS = Object.freeze({+ none: LEGACY_ANIMATION_PRESETS.none,+ conductor: LEGACY_ANIMATION_PRESETS.conductor,+ routed: LEGACY_ANIMATION_PRESETS.adom,+ handshake: Object.freeze({+ animationSystem: "handshake",+ motion: true,+ liveliness: 0.72,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ atmosphereStrength: 0,+ }),+ growth: Object.freeze({+ animationSystem: "growth",+ motion: true,+ liveliness: 0.72,+ growthDuration: 7600,+ growthGlow: 0.88,+ atmosphereStrength: 0.16,+ }),+ reflection: Object.freeze({+ animationSystem: "reflection",+ motion: true,+ liveliness: 0.68,+ reflectionStrength: 0.62,+ reflectionCycle: 14800,+ reflectionWidth: 0.3,+ reflectionAngle: 18,+ reflectionDrift: 6,+ reflectionRest: 0.12,+ reflectionQuiet: 0.84,+ reflectionPointer: true,+ atmosphereStrength: 0.14,+ }),+});++let instanceCount = 0;++function hashSeed(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function createModernCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-field-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let field;+ let svg;+ let conductor;+ let handshake;+ let growth;+ let reflection;+ let resizeObserver;+ let resizeTimer;+ let pointer = null;+ let lastSize = "";+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalPosition = mount.style.position;+ const originalOverflow = mount.style.overflow;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function life() {+ return Math.max(0, Math.min(1.5, config.liveliness));+ }++ function featureScale() {+ return Math.max(0.25, config.featureScale);+ }++ function addVia(group, point, role) {+ const scale = featureScale();+ const circles = [+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaOuterRadius * scale, fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ ];+ if (!role) {+ group.append(...circles);+ return circles;+ }+ const via = svgElement("g", { "data-trace-via": role });+ via.append(...circles);+ group.append(via);+ return via;+ }++ function destroyAnimationSystems() {+ conductor?.destroy();+ handshake?.destroy();+ growth?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ growth = undefined;+ reflection = undefined;+ }++ function build(force = false) {+ const pixelWidth = Math.max(1, mount.clientWidth);+ const pixelHeight = Math.max(1, mount.clientHeight);+ const worldWidth = pixelWidth / config.scale;+ const worldHeight = pixelHeight / config.scale;+ const pitch = config.pitch * featureScale();+ const size = `${Math.floor(worldWidth / pitch)}x${Math.floor(worldHeight / pitch)}`;+ if (!force && size === lastSize) return false;+ lastSize = size;++ destroyAnimationSystems();+ svg?.remove();+ field = generateCircuitField({ ...config, width: worldWidth, height: worldHeight });+ const motionNamespace = config.animationSystem === "conductor"+ ? "signals"+ : config.animationSystem === "handshake"+ ? "handshakes"+ : config.animationSystem;+ const motionRandom = mulberry32(hashSeed(`${config.seed}:${size}:${motionNamespace}`));++ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${field.width} ${field.height}`,+ preserveAspectRatio: "none",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });++ const traceLayer = svgElement("g", { "data-static-traces": "" });+ const growthMarkup = config.animationSystem === "growth";+ for (const [index, trace] of field.traces.entries()) {+ const tracePath = svgElement("path", {+ ...(growthMarkup ? { "data-trace-path": "" } : {}),+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * config.featureScale,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ if (!growthMarkup) {+ traceLayer.append(tracePath);+ if (trace.viaStart) addVia(traceLayer, trace.points[0]);+ if (trace.viaEnd) addVia(traceLayer, trace.points.at(-1));+ continue;+ }+ const traceGroup = svgElement("g", { "data-circuit-trace": index });+ traceGroup.append(tracePath);+ if (trace.viaStart) addVia(traceGroup, trace.points[0], "start");+ if (trace.viaEnd) addVia(traceGroup, trace.points.at(-1), "end");+ traceLayer.append(traceGroup);+ }+ svg.append(traceLayer);+ mount.prepend(svg);++ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, field, config, motionRandom);+ } else if (+ config.animationSystem === "handshake"+ && config.motion+ && !reducedMotion+ && life() > 0.02+ ) {+ handshake = createHandshakeAnimation(mount, field, config, motionRandom, { readingZone });+ } else if (config.animationSystem === "growth") {+ growth = createTraceGrowthAnimation(svg, field, config, motionRandom, { traceLayer });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, field, config, motionRandom, { readingZone });+ }+ return true;+ }++ function onPointerMove(event) {+ if (!field) return;+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / rect.width * field.width,+ y: (event.clientY - rect.top) / rect.height * field.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ growth?.stop();+ reflection?.stop();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "growth") growth?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ return;+ }+ lastSize = "";+ build(true);+ startMotion();+ }++ function regenerate(nextOptions = {}) {+ stopMotion();+ config = { ...config, ...nextOptions };+ lastSize = "";+ build(true);+ startMotion();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "growth") return growth?.trigger() || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function exportSvg() {+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("[data-animation]").forEach((layer) => layer.remove());+ clone.querySelectorAll("[data-trace-path]").forEach((path) => {+ path.removeAttribute("stroke-dasharray");+ path.removeAttribute("stroke-dashoffset");+ path.style.removeProperty("opacity");+ path.style.removeProperty("will-change");+ });+ clone.querySelectorAll("[data-circuit-trace]").forEach((group, index) => {+ const path = group.querySelector("[data-trace-path]");+ const trace = field.traces[index];+ if (path && trace) path.setAttribute("d", pathData(trace.points));+ });+ clone.querySelectorAll("[data-trace-via]").forEach((via) => {+ via.style.removeProperty("opacity");+ via.style.removeProperty("will-change");+ });+ clone.removeAttribute("style");+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function destroy() {+ stopMotion();+ destroyAnimationSystems();+ window.clearTimeout(resizeTimer);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ svg?.remove();+ mount.style.position = originalPosition;+ mount.style.overflow = originalOverflow;+ }++ const api = {+ regenerate,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ exportSvg,+ destroy,+ get field() { return field; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") {+ return handshake?.stats || {+ system: "adom-handshake",+ animationNodes: 0,+ activeTransactions: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "growth") {+ return growth?.stats || {+ system: "trace-growth",+ animationNodes: 0,+ activeTraces: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "reflection") {+ return reflection?.stats || {+ system: "adom-reflection",+ animationNodes: 0,+ activeReflections: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ };++ build(true);+ resizeObserver = new ResizeObserver(() => {+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (build()) {+ stopMotion();+ startMotion();+ }+ }, 220);+ });+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ startMotion();+ return api;+}++export function createCircuitBackground(mount, options = {}) {+ let config = { ...DEFAULTS, ...options };+ let destroyed = false;+ const usesRoutedField = (value) => value.animationSystem === "adom";+ const createEngine = () => usesRoutedField(config)+ ? createLegacyCircuitBackground(mount, config)+ : createModernCircuitBackground(mount, config);+ let engine = createEngine();++ const api = {+ regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ const wasRouted = usesRoutedField(config);+ config = { ...config, ...nextOptions };+ if (wasRouted !== usesRoutedField(config)) {+ engine.destroy();+ engine = createEngine();+ } else {+ engine.regenerate(nextOptions);+ }+ return api;+ },+ triggerAnimation(origin = null) {+ return engine.triggerAnimation?.(origin) || false;+ },+ triggerBloom(origin = null) {+ return engine.triggerBloom?.(origin) || engine.triggerAnimation?.(origin) || false;+ },+ exportSvg() {+ return engine.exportSvg();+ },+ destroy() {+ if (destroyed) return;+ destroyed = true;+ engine.destroy();+ },+ get field() { return engine.field; },+ get animationStats() { return engine.animationStats; },+ };++ return api;+}++export { DEFAULTS, ANIMATION_PRESETS, generateCircuitField, pathData };
src/circuit-background-v7.jsadded+1428@@ -0,0 +1,1428 @@+import { createConductorAnimation } from "./circuit-animation-conductor.js?v=1";+import { createHandshakeAnimation } from "./circuit-animation-handshake.js?v=2";+import { createTraceFlowReveal } from "./circuit-reveal-flow.js?v=1";+import {+ createScrollTraceReveal,+ SCROLL_REVEAL_DEFAULTS,+ TRACE_SPAWN_PRESETS,+} from "./circuit-reveal-scroll.js?v=1";+import { createStreamingCircuitField } from "./circuit-field-stream.js?v=1";+import { createStreamingCircuitFieldWorker } from "./circuit-field-stream-client.js?v=1";+import {+ createStreamingTraceReveal,+ STREAM_REVEAL_DEFAULTS,+} from "./circuit-reveal-stream.js?v=1";+import {+ createReflectionAnimation,+ REFLECTION_DEFAULTS,+} from "./circuit-animation-reflection.js?v=1";+import {+ createCircuitBackground as createLegacyCircuitBackground,+ DEFAULTS as GEOMETRY_DEFAULTS,+ ANIMATION_PRESETS as LEGACY_ANIMATION_PRESETS,+ generateCircuitField,+ pathData,+} from "./circuit-background-v4.js?geometry=1";++const SVG_NS = "http://www.w3.org/2000/svg";++const DEFAULTS = Object.freeze({+ ...GEOMETRY_DEFAULTS,+ animationSystem: "none",+ motion: false,+ revealSystem: "instant",+ revealMotion: false,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.82,+ ...SCROLL_REVEAL_DEFAULTS,+ traceDuration: STREAM_REVEAL_DEFAULTS.traceDuration,+ revealLaunchRate: STREAM_REVEAL_DEFAULTS.revealLaunchRate,+ scrollSpeedResponse: 0.6,+ maxActiveTraces: STREAM_REVEAL_DEFAULTS.maxActiveTraces,+ unlockLead: 0.025,+ continuousGeneration: false,+ generationAheadScreens: 2,+ generationChunkScreens: 0.42,+ generationExtendScreens: 2,+ liveliness: 0,+ atmosphereStrength: 0,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ ...REFLECTION_DEFAULTS,+});++const ANIMATION_PRESETS = Object.freeze({+ none: LEGACY_ANIMATION_PRESETS.none,+ conductor: LEGACY_ANIMATION_PRESETS.conductor,+ routed: LEGACY_ANIMATION_PRESETS.adom,+ handshake: Object.freeze({+ animationSystem: "handshake",+ motion: true,+ liveliness: 0.72,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ atmosphereStrength: 0,+ }),+ reflection: Object.freeze({+ animationSystem: "reflection",+ motion: true,+ liveliness: 0.68,+ reflectionStrength: 0.62,+ reflectionCycle: 14800,+ reflectionWidth: 0.3,+ reflectionAngle: 18,+ reflectionDrift: 6,+ reflectionRest: 0.12,+ reflectionQuiet: 0.84,+ reflectionPointer: true,+ atmosphereStrength: 0.14,+ }),+});++const REVEAL_PRESETS = Object.freeze({+ instant: Object.freeze({+ revealSystem: "instant",+ revealMotion: false,+ }),+ flow: Object.freeze({+ revealSystem: "flow",+ revealMotion: true,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.88,+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ revealMaxActiveTraces: 48,+ }),+ scroll: Object.freeze({+ revealSystem: "scroll",+ revealMotion: true,+ revealPower: 0.78,+ ...TRACE_SPAWN_PRESETS.downstream,+ traceWindow: 0.095,+ revealScrollLead: 0.74,+ revealGlow: 0.82,+ traceDuration: 950,+ revealLaunchRate: 24,+ maxActiveTraces: 72,+ scrollSpeedResponse: 0.6,+ unlockLead: 0.025,+ continuousGeneration: true,+ generationAheadScreens: 2,+ }),+});++let instanceCount = 0;++function hashSeed(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function createModernCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-field-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let field;+ let svg;+ let conductor;+ let handshake;+ let reflection;+ let flowReveal;+ let scrollReveal;+ let resizeObserver;+ let resizeTimer;+ let pointer = null;+ let lastSize = "";+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalPosition = mount.style.position;+ const originalOverflow = mount.style.overflow;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function life() {+ return Math.max(0, Math.min(1.5, config.liveliness));+ }++ function featureScale() {+ return Math.max(0.25, config.featureScale);+ }++ function addVia(group, point, role) {+ const scale = featureScale();+ const circles = [+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaOuterRadius * scale, fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ ];+ if (!role) {+ group.append(...circles);+ return circles;+ }+ const via = svgElement("g", { "data-trace-via": role });+ via.append(...circles);+ group.append(via);+ return via;+ }++ function syncAmbientRevealClip(progress = null) {+ const bottom = progress === null ? null : Math.max(0, 100 - progress * 100);+ for (const layer of mount.querySelectorAll("[data-animation]")) {+ if (layer.getAttribute("data-animation") === "scroll-trace-reveal") continue;+ if (bottom === null) layer.style.removeProperty("clip-path");+ else layer.style.clipPath = "inset(0 0 " + bottom + "% 0)";+ }+ }++ function destroyAnimationSystems() {+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ }++ function destroyRevealSystems() {+ syncAmbientRevealClip(null);+ flowReveal?.destroy();+ scrollReveal?.destroy();+ flowReveal = undefined;+ scrollReveal = undefined;+ }++ function createAnimationSystems() {+ const animationNamespace = config.animationSystem === "conductor"+ ? "signals"+ : config.animationSystem === "handshake"+ ? "handshakes"+ : config.animationSystem;+ const animationRandom = mulberry32(hashSeed([config.seed, lastSize, animationNamespace].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, field, config, animationRandom);+ } else if (+ config.animationSystem === "handshake"+ && config.motion+ && !reducedMotion+ && life() > 0.02+ ) {+ handshake = createHandshakeAnimation(mount, field, config, animationRandom, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, field, config, animationRandom, { readingZone });+ }+ }++ function build(force = false) {+ const pixelWidth = Math.max(1, mount.clientWidth);+ const pixelHeight = Math.max(1, mount.clientHeight);+ const worldWidth = pixelWidth / config.scale;+ const worldHeight = pixelHeight / config.scale;+ const pitch = config.pitch * featureScale();+ const size = `${Math.floor(worldWidth / pitch)}x${Math.floor(worldHeight / pitch)}`;+ if (!force && size === lastSize) return false;+ lastSize = size;++ destroyAnimationSystems();+ destroyRevealSystems();+ svg?.remove();+ field = generateCircuitField({ ...config, width: worldWidth, height: worldHeight });+ const revealRandom = mulberry32(hashSeed(`${config.seed}:${size}:reveal:${config.revealSystem}`));++ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${field.width} ${field.height}`,+ preserveAspectRatio: "none",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });++ const traceLayer = svgElement("g", { "data-static-traces": "" });+ const flowMarkup = config.revealSystem === "flow";+ for (const [index, trace] of field.traces.entries()) {+ const tracePath = svgElement("path", {+ ...(flowMarkup ? { "data-trace-path": "" } : {}),+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * config.featureScale,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ if (!flowMarkup) {+ traceLayer.append(tracePath);+ if (trace.viaStart) addVia(traceLayer, trace.points[0]);+ if (trace.viaEnd) addVia(traceLayer, trace.points.at(-1));+ continue;+ }+ const traceGroup = svgElement("g", { "data-circuit-trace": index });+ traceGroup.append(tracePath);+ if (trace.viaStart) addVia(traceGroup, trace.points[0], "start");+ if (trace.viaEnd) addVia(traceGroup, trace.points.at(-1), "end");+ traceLayer.append(traceGroup);+ }+ svg.append(traceLayer);+ mount.prepend(svg);++ createAnimationSystems();++ if (config.revealSystem === "flow") {+ flowReveal = createTraceFlowReveal(svg, field, config, revealRandom, {+ traceLayer,+ onComplete: () => startMotion(),+ });+ } else if (config.revealSystem === "scroll") {+ const revealLead = Math.max(0.25, Math.min(0.95, Number(config.revealScrollLead) || 0.74));+ scrollReveal = createScrollTraceReveal(svg, field, config, {+ traceLayer,+ rangeElement: mount,+ scrollRoot: window,+ progressSource: config.progressSource || "scroll",+ spawnMode: config.spawnMode,+ spawnAngle: config.spawnAngle,+ spawnSwirl: config.spawnSwirl,+ spawnOriginX: config.spawnOriginX,+ spawnOriginY: config.spawnOriginY,+ traceWindow: config.traceWindow,+ unlockLead: config.unlockLead,+ maxActiveTraces: config.maxActiveTraces,+ traceDuration: config.traceDuration,+ revealLaunchRate: config.revealLaunchRate,+ scrollSpeedResponse: config.scrollSpeedResponse,+ revealGlow: config.revealGlow,+ startOffset: Number.isFinite(Number(config.revealStartOffset))+ ? Number(config.revealStartOffset)+ : -window.innerHeight * revealLead,+ endOffset: config.endOffset,+ once: config.once !== false,+ autoStart: false,+ onProgress: (progress) => syncAmbientRevealClip(progress),+ });+ }+ return true;+ }++ function onPointerMove(event) {+ if (!field) return;+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / rect.width * field.width,+ y: (event.clientY - rect.top) / rect.height * field.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (flowReveal?.stats?.running) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function stopReveal() {+ syncAmbientRevealClip(null);+ flowReveal?.stop();+ scrollReveal?.stop();+ }++ function startReveal() {+ if (reducedMotion || config.revealSystem === "instant" || !config.revealMotion) {+ flowReveal?.stop();+ scrollReveal?.complete();+ return;+ }+ if (config.revealSystem === "flow") {+ flowReveal?.start();+ } else if (config.revealSystem === "scroll") {+ scrollReveal?.start();+ syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ }+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ stopReveal();+ scrollReveal?.complete();+ return;+ }+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ }++ function regenerate(nextOptions = {}) {+ stopMotion();+ stopReveal();+ config = { ...config, ...nextOptions };+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ return api;+ }++ function setReveal(nextOptions = {}) {+ return regenerate(nextOptions);+ }++ function setAnimation(nextOptions = {}) {+ stopMotion();+ destroyAnimationSystems();+ config = { ...config, ...nextOptions };+ createAnimationSystems();+ if (config.revealSystem === "scroll") syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ startMotion();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (config.revealSystem === "flow") {+ stopMotion();+ startReveal();+ return true;+ }+ if (config.revealSystem === "scroll") return false;+ return false;+ }++ function setRevealProgress(progress, options) {+ scrollReveal?.setProgress(progress, options);+ return api;+ }++ function exportSvg() {+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("[data-animation]").forEach((layer) => layer.remove());+ clone.querySelector("[data-static-traces]")?.style.removeProperty("visibility");+ clone.querySelector("[data-static-traces]")?.style.removeProperty("display");+ clone.querySelectorAll("[data-trace-path]").forEach((path) => {+ path.removeAttribute("stroke-dasharray");+ path.removeAttribute("stroke-dashoffset");+ path.style.removeProperty("opacity");+ path.style.removeProperty("will-change");+ });+ clone.querySelectorAll("[data-circuit-trace]").forEach((group, index) => {+ const path = group.querySelector("[data-trace-path]");+ const trace = field.traces[index];+ if (path && trace) path.setAttribute("d", pathData(trace.points));+ });+ clone.querySelectorAll("[data-trace-via]").forEach((via) => {+ via.style.removeProperty("opacity");+ via.style.removeProperty("will-change");+ });+ clone.removeAttribute("style");+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function destroy() {+ stopMotion();+ stopReveal();+ destroyAnimationSystems();+ destroyRevealSystems();+ window.clearTimeout(resizeTimer);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ svg?.remove();+ mount.style.position = originalPosition;+ mount.style.overflow = originalOverflow;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return field; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") {+ return handshake?.stats || {+ system: "adom-handshake",+ animationNodes: 0,+ activeTransactions: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "reflection") {+ return reflection?.stats || {+ system: "adom-reflection",+ animationNodes: 0,+ activeReflections: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ if (config.revealSystem === "instant") {+ return { system: "instant", traceCount: field?.traces.length || 0, completed: true, reducedMotion };+ }+ if (config.revealSystem === "flow") {+ return flowReveal?.stats || {+ system: "trace-flow-sweep",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ reducedMotion,+ };+ }+ if (config.revealSystem === "scroll") {+ return scrollReveal?.stats || {+ system: "scroll-trace-reveal",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ completedTraces: 0,+ progress: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", traceCount: 0, reducedMotion };+ },+ };++ build(true);+ resizeObserver = new ResizeObserver(() => {+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (build()) {+ startReveal();+ startMotion();+ }+ }, 220);+ });+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ startReveal();+ startMotion();+ return api;+}+++function createStreamingCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-stream-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let stream;+ let reveal;+ let svg;+ let unsubscribe;+ let fallbackUnsubscribe;+ let conductor;+ let handshake;+ let reflection;+ let resizeObserver;+ let resizeTimer;+ let ambientRefreshTimer;+ let coordinatorFrame = 0;+ let clipFrame = 0;+ let lastAmbientClipBottom = null;+ let ambientClipLayers = null;+ let generationRequest = 0;+ let generationRequestType = "";+ let generationPromise = null;+ let streamUsesWorker = false;+ let buildEpoch = 0;+ let generationTargetWorldY = 0;+ let destroyed = false;+ let pointer = null;+ let lastPixelWidth = Math.max(1, mount.clientWidth);+ let logicalPixelHeight = Math.max(1, mount.clientHeight);+ let previousViewportTop = 0;+ let previousViewportTime = performance.now();+ let latestViewport = null;+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalMountPosition = mount.style.position;+ const originalMountOverflow = mount.style.overflow;+ const originalTargetMinHeight = interactionTarget.style.minHeight;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+ }++ function worldScale() {+ return Math.max(0.01, Number(config.scale) || 1);+ }++ function featureScale() {+ return Math.max(0.25, Number(config.featureScale) || 1);+ }++ function life() {+ return clamp(Number(config.liveliness) || 0, 0, 1.5);+ }++ function logicalWorldHeight() {+ return logicalPixelHeight / worldScale();+ }++ function viewportPixelHeight() {+ return Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);+ }++ function viewportWorldHeight() {+ return viewportPixelHeight() / worldScale();+ }++ function generationChunkRows() {+ const pitch = Math.max(1, (Number(config.pitch) || 7.895) * featureScale());+ const screens = clamp(Number(config.generationChunkScreens) || 0.42, 0.25, 1.5);+ const rowsForScreens = viewportWorldHeight() / pitch * screens;+ const estimatedColumns = Math.max(8, Math.floor(lastPixelWidth / worldScale() / pitch));+ const rowsForWorkBudget = Math.floor(6500 / estimatedColumns);+ return Math.round(clamp(Math.min(rowsForScreens, rowsForWorkBudget), 24, 96));+ }++ function currentViewport() {+ const rect = interactionTarget.getBoundingClientRect();+ const heightPixels = viewportPixelHeight();+ const topPixels = clamp(-rect.top, 0, Math.max(0, logicalPixelHeight - heightPixels));+ const now = performance.now();+ const elapsed = Math.max(1, now - previousViewportTime);+ const forwardPixels = Math.max(0, topPixels - previousViewportTop);+ const velocity = forwardPixels / worldScale() / elapsed;+ previousViewportTop = topPixels;+ previousViewportTime = now;+ latestViewport = {+ topPixels,+ bottomPixels: Math.min(logicalPixelHeight, topPixels + heightPixels),+ heightPixels,+ topWorldY: topPixels / worldScale(),+ bottomWorldY: Math.min(logicalPixelHeight, topPixels + heightPixels) / worldScale(),+ heightWorld: heightPixels / worldScale(),+ velocity,+ };+ return latestViewport;+ }++ const fieldFacade = {+ get width() { return stream?.width || lastPixelWidth / worldScale(); },+ get height() { return logicalWorldHeight(); },+ get traces() { return stream?.traces || []; },+ };++ function updateSvgExtent() {+ if (!svg || !stream) return;+ svg.setAttribute("viewBox", `0 0 ${stream.width} ${logicalWorldHeight()}`);+ }++ function syncAmbientRevealClip() {+ if (!reveal || !svg || config.animationSystem === "none") return;+ const stats = reveal.stats;+ const through = Number(stats.revealedThroughWorldY);+ const progress = Number.isFinite(through)+ ? clamp(through / Math.max(1, logicalWorldHeight()))+ : 0;+ const bottom = Math.max(0, 100 - progress * 100);+ if (bottom === lastAmbientClipBottom) return;+ lastAmbientClipBottom = bottom;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ ambientClipLayers = layers;+ const clipPath = "inset(0 0 " + bottom + "% 0)";+ for (const layer of layers) layer.style.clipPath = clipPath;+ }++ function scheduleAmbientClip() {+ if (+ clipFrame+ || destroyed+ || config.animationSystem === "none"+ || (!conductor && !handshake && !reflection)+ ) return;+ const tick = () => {+ clipFrame = 0;+ syncAmbientRevealClip();+ const stats = reveal?.stats;+ if (+ config.animationSystem !== "none"+ && (conductor || handshake || reflection)+ && stats+ && (stats.active > 0 || stats.queued > 0)+ ) {+ clipFrame = window.requestAnimationFrame(tick);+ }+ };+ clipFrame = window.requestAnimationFrame(tick);+ }++ function clearAmbientClip() {+ window.cancelAnimationFrame(clipFrame);+ clipFrame = 0;+ lastAmbientClipBottom = null;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"));+ for (const layer of layers) {+ if (layer.getAttribute("data-animation") !== "stream-trace-reveal") {+ layer.style.removeProperty("clip-path");+ }+ }+ ambientClipLayers = null;+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function destroyAnimationSystems() {+ window.clearTimeout(ambientRefreshTimer);+ ambientRefreshTimer = 0;+ stopMotion();+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ ambientClipLayers = null;+ lastAmbientClipBottom = null;+ }++ function createAnimationSystems() {+ if (!svg || !stream || config.animationSystem === "none") return;+ const namespace = config.animationSystem === "conductor"+ ? "stream-signals"+ : `stream-${config.animationSystem}`;+ const random = mulberry32(hashSeed([+ config.seed,+ Math.round(stream.width),+ Math.round(logicalWorldHeight()),+ namespace,+ ].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, fieldFacade, config, random);+ } else if (config.animationSystem === "handshake") {+ handshake = createHandshakeAnimation(mount, fieldFacade, config, random, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, fieldFacade, config, random, { readingZone });+ }+ ambientClipLayers = Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ syncAmbientRevealClip();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function refreshGrowingCanvasAnimation() {+ if (!reflection && !handshake) return;+ window.clearTimeout(ambientRefreshTimer);+ const epoch = buildEpoch;+ const candidate = stream;+ ambientRefreshTimer = window.setTimeout(() => {+ ambientRefreshTimer = 0;+ if (destroyed || epoch !== buildEpoch || candidate !== stream) return;+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ }, 180);+ }++ function stopReveal() {+ reveal?.stop();+ }++ function startReveal() {+ if (!reveal) return;+ if (reducedMotion || !config.revealMotion) reveal.complete();+ else reveal.start();+ scheduleAmbientClip();+ }++ function cancelGenerationRequest() {+ if (!generationRequest) return;+ if (generationRequestType === "idle" && window.cancelIdleCallback) {+ window.cancelIdleCallback(generationRequest);+ } else {+ window.clearTimeout(generationRequest);+ }+ generationRequest = 0;+ generationRequestType = "";+ }++ function extendPageWhenReady(viewport = currentViewport()) {+ if (!stream) return false;+ const triggerScreens = 1.45;+ const distancePixels = logicalPixelHeight - viewport.bottomPixels;+ if (distancePixels > viewport.heightPixels * triggerScreens) return false;+ const extendScreens = clamp(Number(config.generationExtendScreens) || 2, 0.75, 4);+ const extensionPixels = viewport.heightPixels * extendScreens;+ const nextPixelHeight = logicalPixelHeight + extensionPixels;+ const nextWorldHeight = nextPixelHeight / worldScale();+ if (stream.generatedThrough + stream.stats.pitch * 0.25 < nextWorldHeight) return false;+ logicalPixelHeight = nextPixelHeight;+ interactionTarget.style.minHeight = `${Math.ceil(logicalPixelHeight)}px`;+ updateSvgExtent();+ refreshGrowingCanvasAnimation();+ return true;+ }++ function pumpGeneration() {+ generationRequest = 0;+ generationRequestType = "";+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const stats = stream.stats;+ const chunkHeight = Math.max(stats.pitch, stats.pitch * stats.chunkRows);+ const through = Math.min(generationTargetWorldY, stream.generatedThrough + chunkHeight);+ stream.ensureThrough(through);+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ }++ function scheduleWorkerGeneration() {+ if (generationPromise || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const candidate = stream;+ const epoch = buildEpoch;+ const target = generationTargetWorldY;+ generationPromise = candidate.ensureThrough(target)+ .then(() => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ })+ .catch((error) => {+ if (+ !destroyed+ && candidate === stream+ && epoch === buildEpoch+ && error?.name !== "AbortError"+ ) {+ fallbackToSynchronousStream(candidate);+ }+ })+ .finally(() => {+ if (candidate !== stream || epoch !== buildEpoch) return;+ generationPromise = null;+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ });+ }++ function scheduleGeneration() {+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ if (streamUsesWorker) {+ scheduleWorkerGeneration();+ return;+ }+ if (generationRequest) return;+ if (typeof window.requestIdleCallback === "function") {+ generationRequestType = "idle";+ generationRequest = window.requestIdleCallback(pumpGeneration, { timeout: 120 });+ } else {+ generationRequestType = "timer";+ generationRequest = window.setTimeout(pumpGeneration, 16);+ }+ }++ function coordinate(measured = null) {+ if (destroyed || !stream || !reveal) return;+ logicalPixelHeight = Math.max(logicalPixelHeight, mount.clientHeight);+ const viewport = measured || currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: viewport.velocity,+ });+ const aheadScreens = clamp(Number(config.generationAheadScreens) || 2, 0.5, 6);+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ viewport.bottomWorldY + viewport.heightWorld * aheadScreens,+ );+ const distancePixels = logicalPixelHeight - viewport.bottomPixels;+ if (distancePixels <= viewport.heightPixels * 1.45) {+ const extendScreens = clamp(Number(config.generationExtendScreens) || 2, 0.75, 4);+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ logicalWorldHeight() + viewport.heightWorld * extendScreens,+ );+ }+ extendPageWhenReady(viewport);+ scheduleGeneration();+ scheduleAmbientClip();+ }++ function scheduleCoordinate() {+ if (coordinatorFrame || destroyed) return;+ coordinatorFrame = window.requestAnimationFrame(() => {+ coordinatorFrame = 0;+ coordinate();+ });+ }++ function createSvg() {+ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${stream.width} ${logicalWorldHeight()}`,+ preserveAspectRatio: "none",+ "data-continuous-circuit": "v7",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });+ mount.prepend(svg);+ }++ function fallbackToSynchronousStream(candidate) {+ if (destroyed || candidate !== stream) return;+ build(false);+ }++ async function initializeStream(candidate, streamOptions, epoch, useWorker) {+ try {+ if (useWorker) await candidate.ready;+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;++ createSvg();+ reveal = createStreamingTraceReveal(svg, config, {+ ...config,+ width: candidate.width,+ autoStart: false,+ });+ const viewport = currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: 0,+ });+ unsubscribe = candidate.onAppend((traces) => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || !reveal) return;+ reveal.appendTraces(traces);+ if (reducedMotion || !config.revealMotion) reveal.complete();+ refreshGrowingCanvasAnimation();+ scheduleAmbientClip();+ });+ const initialAhead = Math.min(+ clamp(Number(config.generationAheadScreens) || 2, 0.5, 6),+ 0.35,+ );+ const initialThrough = Math.min(+ logicalWorldHeight(),+ viewport.bottomWorldY + viewport.heightWorld * initialAhead,+ );+ await Promise.resolve(candidate.ensureThrough(initialThrough));+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;++ generationTargetWorldY = Math.max(+ logicalWorldHeight(),+ viewport.bottomWorldY + viewport.heightWorld * (Number(config.generationAheadScreens) || 2),+ );+ createAnimationSystems();+ startReveal();+ startMotion();+ coordinate(viewport);+ scheduleGeneration();+ } catch (error) {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || error?.name === "AbortError") return;+ if (useWorker) fallbackToSynchronousStream(candidate);+ else console.error("Circuit field generation failed", error, streamOptions);+ }+ }++ function build(useWorker = true) {+ buildEpoch += 1;+ const epoch = buildEpoch;+ cancelGenerationRequest();+ generationPromise = null;+ window.cancelAnimationFrame(coordinatorFrame);+ coordinatorFrame = 0;+ clearAmbientClip();+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ unsubscribe = undefined;+ fallbackUnsubscribe = undefined;+ reveal?.destroy();+ reveal = undefined;+ stream?.destroy();+ stream = undefined;+ svg?.remove();+ svg = undefined;+ lastPixelWidth = Math.max(1, mount.clientWidth);+ logicalPixelHeight = Math.max(logicalPixelHeight, mount.clientHeight, viewportPixelHeight() * 3);+ interactionTarget.style.minHeight = Math.ceil(logicalPixelHeight) + "px";+ const streamOptions = {+ ...config,+ width: lastPixelWidth / worldScale(),+ chunkRows: generationChunkRows(),+ };+ streamUsesWorker = useWorker;+ stream = useWorker+ ? createStreamingCircuitFieldWorker(streamOptions)+ : createStreamingCircuitField(streamOptions);+ const candidate = stream;+ if (useWorker) {+ fallbackUnsubscribe = candidate.onFallback(() => {+ fallbackToSynchronousStream(candidate);+ });+ }+ initializeStream(candidate, streamOptions, epoch, useWorker);+ }++ function onPointerMove(event) {+ if (!stream) return;+ const rect = mount.getBoundingClientRect();+ if (rect.width <= 0 || rect.height <= 0) return;+ pointer = {+ x: (event.clientX - rect.left) / rect.width * fieldFacade.width,+ y: (event.clientY - rect.top) / rect.height * fieldFacade.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ reveal?.complete();+ } else {+ reveal?.start();+ startMotion();+ }+ scheduleAmbientClip();+ }++ function regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ config = { ...config, ...nextOptions };+ build();+ coordinate();+ return api;+ }++ function setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ reveal?.updateOptions(config);+ if (reducedMotion || !config.revealMotion) reveal?.complete();+ else reveal?.start();+ coordinate();+ return api;+ }++ function setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ scheduleAmbientClip();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (!reveal || reducedMotion || !config.revealMotion) return false;+ reveal.reset();+ reveal.start();+ coordinate();+ return true;+ }++ function setRevealProgress(progress, progressOptions = {}) {+ if (!reveal) return api;+ const amount = clamp(Number(progress) || 0);+ const height = viewportWorldHeight();+ const topWorldY = Math.max(0, (logicalWorldHeight() - height) * amount);+ reveal.setViewport({+ topWorldY,+ bottomWorldY: topWorldY + height,+ height,+ velocity: Math.max(0, Number(progressOptions.velocity) || 0),+ });+ scheduleAmbientClip();+ return api;+ }++ function addExportVia(group, point) {+ const scale = featureScale();+ group.append(+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaOuterRadius * scale,+ fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ );+ }++ function exportSvg() {+ const exportHeight = Math.max(logicalWorldHeight(), stream?.generatedThrough || 0);+ const exported = svgElement("svg", {+ xmlns: SVG_NS,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${fieldFacade.width} ${exportHeight}`,+ preserveAspectRatio: "none",+ });+ const paths = svgElement("g", { "data-static-traces": "" });+ const vias = svgElement("g", { "data-static-vias": "" });+ for (const trace of fieldFacade.traces) {+ paths.append(svgElement("path", {+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * featureScale(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ }));+ addExportVia(vias, trace.points[0]);+ addExportVia(vias, trace.points.at(-1));+ }+ exported.append(paths, vias);+ return `<?xml version="1.0" encoding="UTF-8"?>\n${exported.outerHTML}`;+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ buildEpoch += 1;+ generationPromise = null;+ cancelGenerationRequest();+ window.cancelAnimationFrame(coordinatorFrame);+ window.cancelAnimationFrame(clipFrame);+ window.clearTimeout(resizeTimer);+ window.clearTimeout(ambientRefreshTimer);+ resizeObserver?.disconnect();+ window.removeEventListener("scroll", scheduleCoordinate);+ window.removeEventListener("resize", scheduleCoordinate);+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ reveal?.destroy();+ stream?.destroy();+ svg?.remove();+ mount.style.position = originalMountPosition;+ mount.style.overflow = originalMountOverflow;+ interactionTarget.style.minHeight = originalTargetMinHeight;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return fieldFacade; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") return handshake?.stats;+ if (config.animationSystem === "reflection") return reflection?.stats;+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ const stats = reveal?.stats || {};+ return {+ system: "scroll-trace-reveal",+ continuous: true,+ traceCount: fieldFacade.traces.length,+ activeTraces: stats.active || 0,+ queuedTraces: stats.queued || 0,+ completedTraces: stats.completed || 0,+ unlockedTraces: stats.unlocked || 0,+ generatedThrough: stream?.generatedThrough || 0,+ pageWorldHeight: logicalWorldHeight(),+ reducedMotion,+ };+ },+ };++ build();+ resizeObserver = new ResizeObserver(() => {+ const nextWidth = Math.max(1, mount.clientWidth);+ if (Math.abs(nextWidth - lastPixelWidth) < 1) return;+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (!destroyed) regenerate();+ }, 180);+ });+ resizeObserver.observe(mount);+ window.addEventListener("scroll", scheduleCoordinate, { passive: true });+ window.addEventListener("resize", scheduleCoordinate, { passive: true });+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ coordinate();+ return api;+}++function normalizeOptions(options = {}) {+ const normalized = { ...options };+ if (normalized.animationSystem === "growth") {+ normalized.animationSystem = "none";+ if (!normalized.revealSystem) normalized.revealSystem = "flow";+ if (normalized.revealMotion === undefined) normalized.revealMotion = true;+ }+ if (normalized.spawnSystem && !normalized.revealSystem) {+ normalized.revealSystem = normalized.spawnSystem === "front"+ ? "flow"+ : normalized.spawnSystem;+ }+ return normalized;+}++export function createCircuitBackground(mount, options = {}) {+ let config = { ...DEFAULTS, ...normalizeOptions(options) };+ let destroyed = false;+ const engineKind = (value) => {+ if (value.animationSystem === "adom") return "routed";+ if (value.revealSystem === "scroll" && value.continuousGeneration) return "streaming";+ return "finite";+ };+ const createEngine = () => {+ const kind = engineKind(config);+ if (kind === "routed") {+ return createLegacyCircuitBackground(mount, { ...config, revealSystem: "instant" });+ }+ if (kind === "streaming") return createStreamingCircuitBackground(mount, config);+ return createModernCircuitBackground(mount, config);+ };+ let engine = createEngine();++ function recreateEngine() {+ engine.destroy();+ engine = createEngine();+ }++ const api = {+ regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else engine.regenerate(normalized);+ return api;+ },+ setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) !== "routed") engine.setReveal?.(normalized);+ return api;+ },+ setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) === "routed") engine.regenerate(normalized);+ else engine.setAnimation(normalized);+ return api;+ },+ triggerAnimation(origin = null) {+ return engine.triggerAnimation?.(origin) || false;+ },+ triggerBloom(origin = null) {+ return engine.triggerBloom?.(origin) || engine.triggerAnimation?.(origin) || false;+ },+ triggerReveal() {+ if (engineKind(config) === "routed") return false;+ return engine.triggerReveal?.() || false;+ },+ setRevealProgress(progress, progressOptions) {+ if (engineKind(config) !== "routed") {+ engine.setRevealProgress?.(progress, progressOptions);+ }+ return api;+ },+ exportSvg() {+ return engine.exportSvg();+ },+ destroy() {+ if (destroyed) return;+ destroyed = true;+ engine.destroy();+ },+ get field() { return engine.field; },+ get animationStats() { return engine.animationStats; },+ get revealStats() {+ if (engineKind(config) === "routed") {+ return { system: "unavailable-routed", traceCount: engine.field?.traces.length || 0 };+ }+ return engine.revealStats;+ },+ };++ return api;+}++export {+ DEFAULTS,+ ANIMATION_PRESETS,+ REVEAL_PRESETS,+ TRACE_SPAWN_PRESETS,+ generateCircuitField,+ pathData,+};
src/circuit-background-v8.jsadded+1506@@ -0,0 +1,1506 @@+import { createConductorAnimation } from "./circuit-animation-conductor.js?v=1";+import { createHandshakeAnimation } from "./circuit-animation-handshake.js?v=2";+import { createTraceFlowReveal } from "./circuit-reveal-flow.js?v=1";+import {+ createScrollTraceReveal,+ SCROLL_REVEAL_DEFAULTS,+ TRACE_SPAWN_PRESETS,+} from "./circuit-reveal-scroll.js?v=1";+import { createHybridCircuitField } from "./circuit-field-hybrid-v8.js?v=1";+import { createStreamingCircuitFieldWorker } from "./circuit-field-hybrid-client-v8.js?v=1";+import {+ createStreamingTraceReveal,+ STREAM_REVEAL_DEFAULTS,+} from "./circuit-reveal-stream-v8.js?v=1";+import { createPageTraceStager } from "./circuit-trace-stager-v8.js?v=1";+import {+ createReflectionAnimation,+ REFLECTION_DEFAULTS,+} from "./circuit-animation-reflection.js?v=1";+import {+ createCircuitBackground as createLegacyCircuitBackground,+ DEFAULTS as GEOMETRY_DEFAULTS,+ ANIMATION_PRESETS as LEGACY_ANIMATION_PRESETS,+ generateCircuitField,+ pathData,+} from "./circuit-background-v4.js?geometry=1";++const SVG_NS = "http://www.w3.org/2000/svg";++const DEFAULTS = Object.freeze({+ ...GEOMETRY_DEFAULTS,+ animationSystem: "none",+ motion: false,+ revealSystem: "instant",+ revealMotion: false,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.82,+ ...SCROLL_REVEAL_DEFAULTS,+ traceDuration: STREAM_REVEAL_DEFAULTS.traceDuration,+ revealLaunchRate: STREAM_REVEAL_DEFAULTS.revealLaunchRate,+ scrollSpeedResponse: 0.6,+ maxActiveTraces: STREAM_REVEAL_DEFAULTS.maxActiveTraces,+ unlockLead: 0.025,+ continuousGeneration: false,+ generationAheadScreens: 2,+ generationChunkScreens: 1,+ generationExtendScreens: 1,+ liveliness: 0,+ atmosphereStrength: 0,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ ...REFLECTION_DEFAULTS,+});++const ANIMATION_PRESETS = Object.freeze({+ none: LEGACY_ANIMATION_PRESETS.none,+ conductor: LEGACY_ANIMATION_PRESETS.conductor,+ routed: LEGACY_ANIMATION_PRESETS.adom,+ handshake: Object.freeze({+ animationSystem: "handshake",+ motion: true,+ liveliness: 0.72,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ atmosphereStrength: 0,+ }),+ reflection: Object.freeze({+ animationSystem: "reflection",+ motion: true,+ liveliness: 0.68,+ reflectionStrength: 0.62,+ reflectionCycle: 14800,+ reflectionWidth: 0.3,+ reflectionAngle: 18,+ reflectionDrift: 6,+ reflectionRest: 0.12,+ reflectionQuiet: 0.84,+ reflectionPointer: true,+ atmosphereStrength: 0.14,+ }),+});++const REVEAL_PRESETS = Object.freeze({+ instant: Object.freeze({+ revealSystem: "instant",+ revealMotion: false,+ }),+ flow: Object.freeze({+ revealSystem: "flow",+ revealMotion: true,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.88,+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ revealMaxActiveTraces: 48,+ }),+ scroll: Object.freeze({+ revealSystem: "scroll",+ revealMotion: true,+ revealPower: 0.78,+ ...TRACE_SPAWN_PRESETS.downstream,+ traceWindow: 0.095,+ revealScrollLead: 0.74,+ revealGlow: 0.82,+ traceDuration: 950,+ revealLaunchRate: 24,+ maxActiveTraces: 72,+ scrollSpeedResponse: 0.6,+ unlockLead: 0.025,+ continuousGeneration: true,+ generationAheadScreens: 2,+ }),+});++let instanceCount = 0;++function hashSeed(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function createModernCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-field-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let field;+ let svg;+ let conductor;+ let handshake;+ let reflection;+ let flowReveal;+ let scrollReveal;+ let resizeObserver;+ let resizeTimer;+ let pointer = null;+ let lastSize = "";+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalPosition = mount.style.position;+ const originalOverflow = mount.style.overflow;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function life() {+ return Math.max(0, Math.min(1.5, config.liveliness));+ }++ function featureScale() {+ return Math.max(0.25, config.featureScale);+ }++ function addVia(group, point, role) {+ const scale = featureScale();+ const circles = [+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaOuterRadius * scale, fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ ];+ if (!role) {+ group.append(...circles);+ return circles;+ }+ const via = svgElement("g", { "data-trace-via": role });+ via.append(...circles);+ group.append(via);+ return via;+ }++ function syncAmbientRevealClip(progress = null) {+ const bottom = progress === null ? null : Math.max(0, 100 - progress * 100);+ for (const layer of mount.querySelectorAll("[data-animation]")) {+ if (layer.getAttribute("data-animation") === "scroll-trace-reveal") continue;+ if (bottom === null) layer.style.removeProperty("clip-path");+ else layer.style.clipPath = "inset(0 0 " + bottom + "% 0)";+ }+ }++ function destroyAnimationSystems() {+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ }++ function destroyRevealSystems() {+ syncAmbientRevealClip(null);+ flowReveal?.destroy();+ scrollReveal?.destroy();+ flowReveal = undefined;+ scrollReveal = undefined;+ }++ function createAnimationSystems() {+ const animationNamespace = config.animationSystem === "conductor"+ ? "signals"+ : config.animationSystem === "handshake"+ ? "handshakes"+ : config.animationSystem;+ const animationRandom = mulberry32(hashSeed([config.seed, lastSize, animationNamespace].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, field, config, animationRandom);+ } else if (+ config.animationSystem === "handshake"+ && config.motion+ && !reducedMotion+ && life() > 0.02+ ) {+ handshake = createHandshakeAnimation(mount, field, config, animationRandom, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, field, config, animationRandom, { readingZone });+ }+ }++ function build(force = false) {+ const pixelWidth = Math.max(1, mount.clientWidth);+ const pixelHeight = Math.max(1, mount.clientHeight);+ const worldWidth = pixelWidth / config.scale;+ const worldHeight = pixelHeight / config.scale;+ const pitch = config.pitch * featureScale();+ const size = `${Math.floor(worldWidth / pitch)}x${Math.floor(worldHeight / pitch)}`;+ if (!force && size === lastSize) return false;+ lastSize = size;++ destroyAnimationSystems();+ destroyRevealSystems();+ svg?.remove();+ field = generateCircuitField({ ...config, width: worldWidth, height: worldHeight });+ const revealRandom = mulberry32(hashSeed(`${config.seed}:${size}:reveal:${config.revealSystem}`));++ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${field.width} ${field.height}`,+ preserveAspectRatio: "none",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });++ const traceLayer = svgElement("g", { "data-static-traces": "" });+ const flowMarkup = config.revealSystem === "flow";+ for (const [index, trace] of field.traces.entries()) {+ const tracePath = svgElement("path", {+ ...(flowMarkup ? { "data-trace-path": "" } : {}),+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * config.featureScale,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ if (!flowMarkup) {+ traceLayer.append(tracePath);+ if (trace.viaStart) addVia(traceLayer, trace.points[0]);+ if (trace.viaEnd) addVia(traceLayer, trace.points.at(-1));+ continue;+ }+ const traceGroup = svgElement("g", { "data-circuit-trace": index });+ traceGroup.append(tracePath);+ if (trace.viaStart) addVia(traceGroup, trace.points[0], "start");+ if (trace.viaEnd) addVia(traceGroup, trace.points.at(-1), "end");+ traceLayer.append(traceGroup);+ }+ svg.append(traceLayer);+ mount.prepend(svg);++ createAnimationSystems();++ if (config.revealSystem === "flow") {+ flowReveal = createTraceFlowReveal(svg, field, config, revealRandom, {+ traceLayer,+ onComplete: () => startMotion(),+ });+ } else if (config.revealSystem === "scroll") {+ const revealLead = Math.max(0.25, Math.min(0.95, Number(config.revealScrollLead) || 0.74));+ scrollReveal = createScrollTraceReveal(svg, field, config, {+ traceLayer,+ rangeElement: mount,+ scrollRoot: window,+ progressSource: config.progressSource || "scroll",+ spawnMode: config.spawnMode,+ spawnAngle: config.spawnAngle,+ spawnSwirl: config.spawnSwirl,+ spawnOriginX: config.spawnOriginX,+ spawnOriginY: config.spawnOriginY,+ traceWindow: config.traceWindow,+ unlockLead: config.unlockLead,+ maxActiveTraces: config.maxActiveTraces,+ traceDuration: config.traceDuration,+ revealLaunchRate: config.revealLaunchRate,+ scrollSpeedResponse: config.scrollSpeedResponse,+ revealGlow: config.revealGlow,+ startOffset: Number.isFinite(Number(config.revealStartOffset))+ ? Number(config.revealStartOffset)+ : -window.innerHeight * revealLead,+ endOffset: config.endOffset,+ once: config.once !== false,+ autoStart: false,+ onProgress: (progress) => syncAmbientRevealClip(progress),+ });+ }+ return true;+ }++ function onPointerMove(event) {+ if (!field) return;+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / rect.width * field.width,+ y: (event.clientY - rect.top) / rect.height * field.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (flowReveal?.stats?.running) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function stopReveal() {+ syncAmbientRevealClip(null);+ flowReveal?.stop();+ scrollReveal?.stop();+ }++ function startReveal() {+ if (reducedMotion || config.revealSystem === "instant" || !config.revealMotion) {+ flowReveal?.stop();+ scrollReveal?.complete();+ return;+ }+ if (config.revealSystem === "flow") {+ flowReveal?.start();+ } else if (config.revealSystem === "scroll") {+ scrollReveal?.start();+ syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ }+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ stopReveal();+ scrollReveal?.complete();+ return;+ }+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ }++ function regenerate(nextOptions = {}) {+ stopMotion();+ stopReveal();+ config = { ...config, ...nextOptions };+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ return api;+ }++ function setReveal(nextOptions = {}) {+ return regenerate(nextOptions);+ }++ function setAnimation(nextOptions = {}) {+ stopMotion();+ destroyAnimationSystems();+ config = { ...config, ...nextOptions };+ createAnimationSystems();+ if (config.revealSystem === "scroll") syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ startMotion();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (config.revealSystem === "flow") {+ stopMotion();+ startReveal();+ return true;+ }+ if (config.revealSystem === "scroll") return false;+ return false;+ }++ function setRevealProgress(progress, options) {+ scrollReveal?.setProgress(progress, options);+ return api;+ }++ function exportSvg() {+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("[data-animation]").forEach((layer) => layer.remove());+ clone.querySelector("[data-static-traces]")?.style.removeProperty("visibility");+ clone.querySelector("[data-static-traces]")?.style.removeProperty("display");+ clone.querySelectorAll("[data-trace-path]").forEach((path) => {+ path.removeAttribute("stroke-dasharray");+ path.removeAttribute("stroke-dashoffset");+ path.style.removeProperty("opacity");+ path.style.removeProperty("will-change");+ });+ clone.querySelectorAll("[data-circuit-trace]").forEach((group, index) => {+ const path = group.querySelector("[data-trace-path]");+ const trace = field.traces[index];+ if (path && trace) path.setAttribute("d", pathData(trace.points));+ });+ clone.querySelectorAll("[data-trace-via]").forEach((via) => {+ via.style.removeProperty("opacity");+ via.style.removeProperty("will-change");+ });+ clone.removeAttribute("style");+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function destroy() {+ stopMotion();+ stopReveal();+ destroyAnimationSystems();+ destroyRevealSystems();+ window.clearTimeout(resizeTimer);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ svg?.remove();+ mount.style.position = originalPosition;+ mount.style.overflow = originalOverflow;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return field; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") {+ return handshake?.stats || {+ system: "adom-handshake",+ animationNodes: 0,+ activeTransactions: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "reflection") {+ return reflection?.stats || {+ system: "adom-reflection",+ animationNodes: 0,+ activeReflections: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ if (config.revealSystem === "instant") {+ return { system: "instant", traceCount: field?.traces.length || 0, completed: true, reducedMotion };+ }+ if (config.revealSystem === "flow") {+ return flowReveal?.stats || {+ system: "trace-flow-sweep",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ reducedMotion,+ };+ }+ if (config.revealSystem === "scroll") {+ return scrollReveal?.stats || {+ system: "scroll-trace-reveal",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ completedTraces: 0,+ progress: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", traceCount: 0, reducedMotion };+ },+ };++ build(true);+ resizeObserver = new ResizeObserver(() => {+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (build()) {+ startReveal();+ startMotion();+ }+ }, 220);+ });+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ startReveal();+ startMotion();+ return api;+}+++function createStreamingCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-stream-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let stream;+ let reveal;+ let traceStager;+ let svg;+ let unsubscribe;+ let fallbackUnsubscribe;+ let conductor;+ let handshake;+ let reflection;+ let resizeObserver;+ let resizeTimer;+ let ambientRefreshTimer;+ let coordinatorFrame = 0;+ let clipFrame = 0;+ let lastAmbientClipBottom = null;+ let ambientClipLayers = null;+ let generationRequest = 0;+ let generationRequestType = "";+ let generationPromise = null;+ let streamUsesWorker = false;+ let buildEpoch = 0;+ let generationTargetWorldY = 0;+ let destroyed = false;+ let pointer = null;+ let canonicalPageWidth = Math.max(+ 1,+ Number(config.canonicalPageWidth) || mount.clientWidth,+ );+ const canonicalWidthTracksViewport = Math.abs(+ canonicalPageWidth - Math.max(1, window.innerWidth || canonicalPageWidth),+ ) < 2;+ const initialPageCount = config.revealSystem === "scroll" ? 3 : 1;+ const pagePixelHeight = Math.max(+ 1,+ Number(config.canonicalPageHeight) || mount.clientHeight / initialPageCount,+ );+ let lastPixelWidth = canonicalPageWidth;+ let pageWorldHeight = pagePixelHeight / Math.max(0.01, Number(config.scale) || 1);+ let logicalPixelHeight = pagePixelHeight * initialPageCount;+ let previousViewportTop = 0;+ let previousViewportTime = performance.now();+ let latestViewport = null;+ const materializedTraces = [];+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalMountPosition = mount.style.position;+ const originalMountOverflow = mount.style.overflow;+ const originalTargetMinHeight = interactionTarget.style.minHeight;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+ }++ function worldScale() {+ return Math.max(0.01, Number(config.scale) || 1);+ }++ function featureScale() {+ return Math.max(0.25, Number(config.featureScale) || 1);+ }++ function life() {+ return clamp(Number(config.liveliness) || 0, 0, 1.5);+ }++ function worldPerPixel() {+ return pageWorldHeight / pagePixelHeight;+ }++ function logicalWorldHeight() {+ return logicalPixelHeight * worldPerPixel();+ }++ function continuousMode() {+ return config.revealSystem === "scroll" && config.continuousGeneration;+ }++ function viewportPixelHeight() {+ return Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);+ }++ function viewportWorldHeight() {+ return viewportPixelHeight() * worldPerPixel();+ }++ function materializationFrontier(viewport) {+ return viewport.bottomWorldY + pageWorldHeight * 0.35;+ }++ function generationChunkRows() {+ const pitch = Math.max(1, (Number(config.pitch) || 7.895) * featureScale());+ return Math.max(24, Math.round(pageWorldHeight / pitch));+ }++ function currentViewport() {+ const rect = interactionTarget.getBoundingClientRect();+ const heightPixels = viewportPixelHeight();+ const topPixels = clamp(-rect.top, 0, Math.max(0, logicalPixelHeight - heightPixels));+ const now = performance.now();+ const elapsed = Math.max(1, now - previousViewportTime);+ const forwardPixels = Math.max(0, topPixels - previousViewportTop);+ const velocity = forwardPixels * worldPerPixel() / elapsed;+ previousViewportTop = topPixels;+ previousViewportTime = now;+ latestViewport = {+ topPixels,+ bottomPixels: Math.min(logicalPixelHeight, topPixels + heightPixels),+ heightPixels,+ topWorldY: topPixels * worldPerPixel(),+ bottomWorldY: Math.min(logicalPixelHeight, topPixels + heightPixels) * worldPerPixel(),+ heightWorld: heightPixels * worldPerPixel(),+ velocity,+ };+ return latestViewport;+ }++ const fieldFacade = {+ get width() { return stream?.width || lastPixelWidth / worldScale(); },+ get height() { return logicalWorldHeight(); },+ get traces() { return materializedTraces; },+ };++ function updateSvgExtent() {+ if (!svg || !stream) return;+ svg.setAttribute("viewBox", `0 0 ${stream.width} ${logicalWorldHeight()}`);+ }++ function syncAmbientRevealClip() {+ if (!reveal || !svg || config.animationSystem === "none") return;+ const stats = reveal.stats;+ const through = Number(stats.revealedThroughWorldY);+ const progress = Number.isFinite(through)+ ? clamp(through / Math.max(1, logicalWorldHeight()))+ : 0;+ const bottom = Math.max(0, 100 - progress * 100);+ if (bottom === lastAmbientClipBottom) return;+ lastAmbientClipBottom = bottom;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ ambientClipLayers = layers;+ const clipPath = "inset(0 0 " + bottom + "% 0)";+ for (const layer of layers) layer.style.clipPath = clipPath;+ }++ function scheduleAmbientClip() {+ if (+ clipFrame+ || destroyed+ || config.animationSystem === "none"+ || (!conductor && !handshake && !reflection)+ ) return;+ const tick = () => {+ clipFrame = 0;+ syncAmbientRevealClip();+ const stats = reveal?.stats;+ if (+ config.animationSystem !== "none"+ && (conductor || handshake || reflection)+ && stats+ && (stats.active > 0 || stats.queued > 0)+ ) {+ clipFrame = window.requestAnimationFrame(tick);+ }+ };+ clipFrame = window.requestAnimationFrame(tick);+ }++ function clearAmbientClip() {+ window.cancelAnimationFrame(clipFrame);+ clipFrame = 0;+ lastAmbientClipBottom = null;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"));+ for (const layer of layers) {+ if (layer.getAttribute("data-animation") !== "stream-trace-reveal") {+ layer.style.removeProperty("clip-path");+ }+ }+ ambientClipLayers = null;+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function destroyAnimationSystems() {+ window.clearTimeout(ambientRefreshTimer);+ ambientRefreshTimer = 0;+ stopMotion();+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ ambientClipLayers = null;+ lastAmbientClipBottom = null;+ }++ function createAnimationSystems() {+ if (!svg || !stream || config.animationSystem === "none") return;+ const namespace = config.animationSystem === "conductor"+ ? "stream-signals"+ : `stream-${config.animationSystem}`;+ const random = mulberry32(hashSeed([+ config.seed,+ Math.round(stream.width),+ Math.round(logicalWorldHeight()),+ namespace,+ ].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, fieldFacade, config, random);+ } else if (config.animationSystem === "handshake") {+ handshake = createHandshakeAnimation(mount, fieldFacade, config, random, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, fieldFacade, config, random, { readingZone });+ }+ ambientClipLayers = Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ syncAmbientRevealClip();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function refreshGrowingCanvasAnimation() {+ if (!reflection && !handshake) return;+ window.clearTimeout(ambientRefreshTimer);+ const epoch = buildEpoch;+ const candidate = stream;+ ambientRefreshTimer = window.setTimeout(() => {+ ambientRefreshTimer = 0;+ if (destroyed || epoch !== buildEpoch || candidate !== stream) return;+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ }, 180);+ }++ function stopReveal() {+ reveal?.stop();+ }++ function startReveal() {+ if (!reveal) return;+ if (reducedMotion || !config.revealMotion) reveal.complete();+ else reveal.start();+ scheduleAmbientClip();+ }++ function cancelGenerationRequest() {+ if (!generationRequest) return;+ if (generationRequestType === "idle" && window.cancelIdleCallback) {+ window.cancelIdleCallback(generationRequest);+ } else {+ window.clearTimeout(generationRequest);+ }+ generationRequest = 0;+ generationRequestType = "";+ }++ function extendPageWhenReady(viewport = currentViewport()) {+ if (!stream || !continuousMode()) return false;+ const distancePixels = logicalPixelHeight - viewport.bottomPixels;+ if (distancePixels > pagePixelHeight * 1.45) return false;+ const extendPages = Math.max(1, Math.round(Number(config.generationExtendScreens) || 1));+ const nextPixelHeight = logicalPixelHeight + pagePixelHeight * extendPages;+ const nextWorldHeight = logicalWorldHeight() + pageWorldHeight * extendPages;+ if (stream.generatedThrough + stream.stats.pitch * 0.25 < nextWorldHeight) return false;+ logicalPixelHeight = nextPixelHeight;+ interactionTarget.style.minHeight = Math.ceil(logicalPixelHeight) + "px";+ updateSvgExtent();+ refreshGrowingCanvasAnimation();+ return true;+ }++ function pumpGeneration() {+ generationRequest = 0;+ generationRequestType = "";+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const stats = stream.stats;+ const chunkHeight = Math.max(stats.pitch, stats.pitch * stats.chunkRows);+ const through = Math.min(generationTargetWorldY, stream.generatedThrough + chunkHeight);+ stream.ensureThrough(through);+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ }++ function scheduleWorkerGeneration() {+ if (generationPromise || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const candidate = stream;+ const epoch = buildEpoch;+ const target = Math.min(+ generationTargetWorldY,+ stream.generatedThrough + pageWorldHeight,+ );+ generationPromise = candidate.ensureThrough(target)+ .then(() => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ })+ .catch((error) => {+ if (+ !destroyed+ && candidate === stream+ && epoch === buildEpoch+ && error?.name !== "AbortError"+ ) {+ fallbackToSynchronousStream(candidate);+ }+ })+ .finally(() => {+ if (candidate !== stream || epoch !== buildEpoch) return;+ generationPromise = null;+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ });+ }++ function scheduleGeneration() {+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ if (streamUsesWorker) {+ if (generationPromise || generationRequest) return;+ const run = () => {+ generationRequest = 0;+ generationRequestType = "";+ scheduleWorkerGeneration();+ };+ if (typeof window.requestIdleCallback === "function") {+ generationRequestType = "idle";+ generationRequest = window.requestIdleCallback(run, { timeout: 150 });+ } else {+ generationRequestType = "timer";+ generationRequest = window.setTimeout(run, 16);+ }+ return;+ }+ if (generationRequest) return;+ if (typeof window.requestIdleCallback === "function") {+ generationRequestType = "idle";+ generationRequest = window.requestIdleCallback(pumpGeneration, { timeout: 120 });+ } else {+ generationRequestType = "timer";+ generationRequest = window.setTimeout(pumpGeneration, 16);+ }+ }++ function coordinate(measured = null) {+ if (destroyed || !stream || !reveal) return;+ const requiredPages = Math.max(1, Math.ceil((mount.clientHeight - 1) / pagePixelHeight));+ const requiredPixelHeight = requiredPages * pagePixelHeight;+ if (requiredPixelHeight > logicalPixelHeight) {+ logicalPixelHeight = requiredPixelHeight;+ updateSvgExtent();+ }+ const viewport = measured || currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: viewport.velocity,+ });+ traceStager?.materializeThrough(materializationFrontier(viewport));+ if (continuousMode()) {+ const aheadPages = clamp(Number(config.generationAheadScreens) || 2, 1, 6);+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ logicalWorldHeight() + pageWorldHeight * aheadPages,+ );+ if (logicalPixelHeight - viewport.bottomPixels <= pagePixelHeight * 1.45) {+ const extendPages = Math.max(1, Math.round(Number(config.generationExtendScreens) || 1));+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ logicalWorldHeight() + pageWorldHeight * (aheadPages + extendPages),+ );+ }+ } else {+ generationTargetWorldY = Math.max(generationTargetWorldY, logicalWorldHeight());+ }+ extendPageWhenReady(viewport);+ scheduleGeneration();+ scheduleAmbientClip();+ }++ function scheduleCoordinate() {+ if (coordinatorFrame || destroyed) return;+ coordinatorFrame = window.requestAnimationFrame(() => {+ coordinatorFrame = 0;+ coordinate();+ });+ }++ function createSvg() {+ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${stream.width} ${logicalWorldHeight()}`,+ preserveAspectRatio: "none",+ "data-continuous-circuit": "v8",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });+ mount.prepend(svg);+ }++ function fallbackToSynchronousStream(candidate) {+ if (destroyed || candidate !== stream) return;+ build(false);+ }++ async function initializeStream(candidate, streamOptions, epoch, useWorker) {+ try {+ if (useWorker) await candidate.ready;+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;+ const canonicalPageHeight = Number(candidate.stats.initialPageHeight);+ if (Number.isFinite(canonicalPageHeight) && canonicalPageHeight > 0) {+ pageWorldHeight = canonicalPageHeight;+ }++ createSvg();+ reveal = createStreamingTraceReveal(svg, config, {+ ...config,+ width: candidate.width,+ autoStart: false,+ });+ traceStager = createPageTraceStager({+ materialize(traces) {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || !reveal) return;+ reveal.appendTraces(traces);+ materializedTraces.push(...traces);+ if (reducedMotion || !config.revealMotion) reveal.complete();+ refreshGrowingCanvasAnimation();+ scheduleAmbientClip();+ },+ });+ const viewport = currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: 0,+ });+ traceStager.materializeThrough(materializationFrontier(viewport));+ unsubscribe = candidate.onAppend((traces) => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || !traceStager) return;+ traceStager.stage(traces);+ });+ const initialThrough = Math.min(logicalWorldHeight(), pageWorldHeight);+ await Promise.resolve(candidate.ensureThrough(initialThrough));+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;++ const aheadPages = continuousMode()+ ? clamp(Number(config.generationAheadScreens) || 2, 1, 6)+ : 0;+ generationTargetWorldY = logicalWorldHeight() + pageWorldHeight * aheadPages;+ createAnimationSystems();+ startReveal();+ startMotion();+ coordinate(viewport);+ scheduleGeneration();+ } catch (error) {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || error?.name === "AbortError") return;+ if (useWorker) fallbackToSynchronousStream(candidate);+ else console.error("Circuit field generation failed", error, streamOptions);+ }+ }++ function build(useWorker = true) {+ buildEpoch += 1;+ const epoch = buildEpoch;+ cancelGenerationRequest();+ generationPromise = null;+ window.cancelAnimationFrame(coordinatorFrame);+ coordinatorFrame = 0;+ clearAmbientClip();+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ unsubscribe = undefined;+ fallbackUnsubscribe = undefined;+ reveal?.destroy();+ reveal = undefined;+ traceStager?.destroy();+ traceStager = undefined;+ materializedTraces.length = 0;+ stream?.destroy();+ stream = undefined;+ svg?.remove();+ svg = undefined;+ lastPixelWidth = canonicalPageWidth;+ logicalPixelHeight = Math.max(logicalPixelHeight, mount.clientHeight);+ pageWorldHeight = pagePixelHeight / worldScale();+ interactionTarget.style.minHeight = Math.ceil(logicalPixelHeight) + "px";+ const streamOptions = {+ ...config,+ width: lastPixelWidth / worldScale(),+ initialPageHeight: pagePixelHeight / worldScale(),+ chunkRows: generationChunkRows(),+ };+ streamUsesWorker = useWorker;+ stream = useWorker+ ? createStreamingCircuitFieldWorker(streamOptions)+ : createHybridCircuitField(streamOptions);+ const candidate = stream;+ if (useWorker) {+ fallbackUnsubscribe = candidate.onFallback(() => {+ fallbackToSynchronousStream(candidate);+ });+ }+ initializeStream(candidate, streamOptions, epoch, useWorker);+ }++ function onPointerMove(event) {+ if (!stream) return;+ const rect = mount.getBoundingClientRect();+ if (rect.width <= 0 || rect.height <= 0) return;+ pointer = {+ x: (event.clientX - rect.left) / rect.width * fieldFacade.width,+ y: (event.clientY - rect.top) / rect.height * fieldFacade.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ reveal?.complete();+ } else {+ reveal?.start();+ startMotion();+ }+ scheduleAmbientClip();+ }++ function regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ config = { ...config, ...nextOptions };+ build();+ coordinate();+ return api;+ }++ function setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ reveal?.updateOptions(config);+ if (reducedMotion || !config.revealMotion) reveal?.complete();+ else reveal?.start();+ coordinate();+ return api;+ }++ function setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ scheduleAmbientClip();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (!reveal || reducedMotion || !config.revealMotion) return false;+ reveal.reset();+ reveal.start();+ coordinate();+ return true;+ }++ function setRevealProgress(progress, progressOptions = {}) {+ if (!reveal) return api;+ const amount = clamp(Number(progress) || 0);+ const height = viewportWorldHeight();+ const topWorldY = Math.max(0, (logicalWorldHeight() - height) * amount);+ reveal.setViewport({+ topWorldY,+ bottomWorldY: topWorldY + height,+ height,+ velocity: Math.max(0, Number(progressOptions.velocity) || 0),+ });+ traceStager?.materializeThrough(topWorldY + height + pageWorldHeight * 0.35);+ scheduleAmbientClip();+ return api;+ }++ function addExportVia(group, point) {+ const scale = featureScale();+ group.append(+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaOuterRadius * scale,+ fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ );+ }++ function exportSvg() {+ const exportHeight = Math.max(logicalWorldHeight(), stream?.generatedThrough || 0);+ const exported = svgElement("svg", {+ xmlns: SVG_NS,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${fieldFacade.width} ${exportHeight}`,+ preserveAspectRatio: "none",+ });+ const paths = svgElement("g", { "data-static-traces": "" });+ const vias = svgElement("g", { "data-static-vias": "" });+ for (const trace of stream?.traces || []) {+ paths.append(svgElement("path", {+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * featureScale(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ }));+ addExportVia(vias, trace.points[0]);+ addExportVia(vias, trace.points.at(-1));+ }+ exported.append(paths, vias);+ return `<?xml version="1.0" encoding="UTF-8"?>\n${exported.outerHTML}`;+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ buildEpoch += 1;+ generationPromise = null;+ cancelGenerationRequest();+ window.cancelAnimationFrame(coordinatorFrame);+ window.cancelAnimationFrame(clipFrame);+ window.clearTimeout(resizeTimer);+ window.clearTimeout(ambientRefreshTimer);+ resizeObserver?.disconnect();+ window.removeEventListener("scroll", scheduleCoordinate);+ window.removeEventListener("resize", scheduleCoordinate);+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ reveal?.destroy();+ traceStager?.destroy();+ materializedTraces.length = 0;+ stream?.destroy();+ svg?.remove();+ mount.style.position = originalMountPosition;+ mount.style.overflow = originalMountOverflow;+ interactionTarget.style.minHeight = originalTargetMinHeight;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return fieldFacade; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") return handshake?.stats;+ if (config.animationSystem === "reflection") return reflection?.stats;+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ const stats = reveal?.stats || {};+ if (config.revealSystem === "instant") {+ return {+ system: "instant",+ continuous: false,+ traceCount: fieldFacade.traces.length,+ completed: true,+ generatedThrough: stream?.generatedThrough || 0,+ canonicalPageWorldHeight: pageWorldHeight,+ reducedMotion,+ };+ }+ return {+ system: "scroll-trace-reveal",+ continuous: continuousMode(),+ traceCount: fieldFacade.traces.length,+ generatedTraceCount: stream?.traces.length || 0,+ materializedTraceCount: traceStager?.stats.materializedTraces || 0,+ bufferedTraceCount: traceStager?.stats.bufferedTraces || 0,+ activeTraces: stats.active || 0,+ queuedTraces: stats.queued || 0,+ completedTraces: stats.completed || 0,+ unlockedTraces: stats.unlocked || 0,+ generatedThrough: stream?.generatedThrough || 0,+ pageWorldHeight: logicalWorldHeight(),+ canonicalPageWorldHeight: pageWorldHeight,+ reducedMotion,+ };+ },+ };++ build();+ resizeObserver = new ResizeObserver(() => {+ const nextWidth = canonicalWidthTracksViewport+ ? Math.max(1, window.innerWidth || mount.clientWidth)+ : Math.max(1, mount.clientWidth);+ if (Math.abs(nextWidth - lastPixelWidth) < 1) return;+ canonicalPageWidth = nextWidth;+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (!destroyed) regenerate();+ }, 180);+ });+ resizeObserver.observe(mount);+ window.addEventListener("scroll", scheduleCoordinate, { passive: true });+ window.addEventListener("resize", scheduleCoordinate, { passive: true });+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ coordinate();+ return api;+}++function normalizeOptions(options = {}) {+ const normalized = { ...options };+ if (normalized.animationSystem === "growth") {+ normalized.animationSystem = "none";+ if (!normalized.revealSystem) normalized.revealSystem = "flow";+ if (normalized.revealMotion === undefined) normalized.revealMotion = true;+ }+ if (normalized.spawnSystem && !normalized.revealSystem) {+ normalized.revealSystem = normalized.spawnSystem === "front"+ ? "flow"+ : normalized.spawnSystem;+ }+ return normalized;+}++export function createCircuitBackground(mount, options = {}) {+ let config = { ...DEFAULTS, ...normalizeOptions(options) };+ let destroyed = false;+ const engineKind = (value) => {+ if (value.animationSystem === "adom") return "routed";+ if (value.revealSystem === "flow") return "finite";+ if (value.revealSystem === "scroll") return "page-scroll";+ return "finite";+ };+ const createEngine = () => {+ const kind = engineKind(config);+ if (kind === "routed") {+ return createLegacyCircuitBackground(mount, { ...config, revealSystem: "instant" });+ }+ if (kind.startsWith("page-")) return createStreamingCircuitBackground(mount, config);+ return createModernCircuitBackground(mount, config);+ };+ let engine = createEngine();++ function recreateEngine() {+ engine.destroy();+ engine = createEngine();+ }++ const api = {+ regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else engine.regenerate(normalized);+ return api;+ },+ setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) !== "routed") engine.setReveal?.(normalized);+ return api;+ },+ setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) === "routed") engine.regenerate(normalized);+ else engine.setAnimation(normalized);+ return api;+ },+ triggerAnimation(origin = null) {+ return engine.triggerAnimation?.(origin) || false;+ },+ triggerBloom(origin = null) {+ return engine.triggerBloom?.(origin) || engine.triggerAnimation?.(origin) || false;+ },+ triggerReveal() {+ if (engineKind(config) === "routed") return false;+ return engine.triggerReveal?.() || false;+ },+ setRevealProgress(progress, progressOptions) {+ if (engineKind(config) !== "routed") {+ engine.setRevealProgress?.(progress, progressOptions);+ }+ return api;+ },+ exportSvg() {+ return engine.exportSvg();+ },+ destroy() {+ if (destroyed) return;+ destroyed = true;+ engine.destroy();+ },+ get field() { return engine.field; },+ get animationStats() { return engine.animationStats; },+ get revealStats() {+ if (engineKind(config) === "routed") {+ return { system: "unavailable-routed", traceCount: engine.field?.traces.length || 0 };+ }+ return engine.revealStats;+ },+ };++ return api;+}++export {+ DEFAULTS,+ ANIMATION_PRESETS,+ REVEAL_PRESETS,+ TRACE_SPAWN_PRESETS,+ generateCircuitField,+ pathData,+};
src/circuit-background-v9.jsadded+1506@@ -0,0 +1,1506 @@+import { createConductorAnimation } from "./circuit-animation-conductor.js?v=1";+import { createHandshakeAnimation } from "./circuit-animation-handshake.js?v=2";+import { createTraceFlowReveal } from "./circuit-reveal-flow.js?v=1";+import {+ createScrollTraceReveal,+ SCROLL_REVEAL_DEFAULTS,+ TRACE_SPAWN_PRESETS,+} from "./circuit-reveal-scroll.js?v=1";+import { createHybridCircuitField } from "./circuit-field-hybrid-v9.js?v=1";+import { createStreamingCircuitFieldWorker } from "./circuit-field-hybrid-client-v9.js?v=1";+import {+ createStreamingTraceReveal,+ STREAM_REVEAL_DEFAULTS,+} from "./circuit-reveal-stream-v8.js?v=1";+import { createPageTraceStager } from "./circuit-trace-stager-v8.js?v=1";+import {+ createReflectionAnimation,+ REFLECTION_DEFAULTS,+} from "./circuit-animation-reflection.js?v=1";+import {+ createCircuitBackground as createLegacyCircuitBackground,+ DEFAULTS as GEOMETRY_DEFAULTS,+ ANIMATION_PRESETS as LEGACY_ANIMATION_PRESETS,+ generateCircuitField,+ pathData,+} from "./circuit-geometry-v9.js?geometry=1";++const SVG_NS = "http://www.w3.org/2000/svg";++const DEFAULTS = Object.freeze({+ ...GEOMETRY_DEFAULTS,+ animationSystem: "none",+ motion: false,+ revealSystem: "instant",+ revealMotion: false,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.82,+ ...SCROLL_REVEAL_DEFAULTS,+ traceDuration: STREAM_REVEAL_DEFAULTS.traceDuration,+ revealLaunchRate: STREAM_REVEAL_DEFAULTS.revealLaunchRate,+ scrollSpeedResponse: 0.6,+ maxActiveTraces: STREAM_REVEAL_DEFAULTS.maxActiveTraces,+ unlockLead: 0.025,+ continuousGeneration: false,+ generationAheadScreens: 2,+ generationChunkScreens: 1,+ generationExtendScreens: 1,+ liveliness: 0,+ atmosphereStrength: 0,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ ...REFLECTION_DEFAULTS,+});++const ANIMATION_PRESETS = Object.freeze({+ none: LEGACY_ANIMATION_PRESETS.none,+ conductor: LEGACY_ANIMATION_PRESETS.conductor,+ routed: LEGACY_ANIMATION_PRESETS.adom,+ handshake: Object.freeze({+ animationSystem: "handshake",+ motion: true,+ liveliness: 0.72,+ handshakeInterval: 1650,+ handshakeSpeed: 230,+ handshakeLength: 48,+ maxHandshakes: 3,+ atmosphereStrength: 0,+ }),+ reflection: Object.freeze({+ animationSystem: "reflection",+ motion: true,+ liveliness: 0.68,+ reflectionStrength: 0.62,+ reflectionCycle: 14800,+ reflectionWidth: 0.3,+ reflectionAngle: 18,+ reflectionDrift: 6,+ reflectionRest: 0.12,+ reflectionQuiet: 0.84,+ reflectionPointer: true,+ atmosphereStrength: 0.14,+ }),+});++const REVEAL_PRESETS = Object.freeze({+ instant: Object.freeze({+ revealSystem: "instant",+ revealMotion: false,+ }),+ flow: Object.freeze({+ revealSystem: "flow",+ revealMotion: true,+ revealPower: 0.72,+ revealDuration: 7600,+ revealGlow: 0.88,+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ revealMaxActiveTraces: 48,+ }),+ scroll: Object.freeze({+ revealSystem: "scroll",+ revealMotion: true,+ revealPower: 0.78,+ ...TRACE_SPAWN_PRESETS.downstream,+ traceWindow: 0.095,+ revealScrollLead: 0.74,+ revealGlow: 0.82,+ traceDuration: 950,+ revealLaunchRate: 24,+ maxActiveTraces: 72,+ scrollSpeedResponse: 0.6,+ unlockLead: 0.025,+ continuousGeneration: true,+ generationAheadScreens: 2,+ }),+});++let instanceCount = 0;++function hashSeed(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function createModernCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-field-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let field;+ let svg;+ let conductor;+ let handshake;+ let reflection;+ let flowReveal;+ let scrollReveal;+ let resizeObserver;+ let resizeTimer;+ let pointer = null;+ let lastSize = "";+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalPosition = mount.style.position;+ const originalOverflow = mount.style.overflow;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function life() {+ return Math.max(0, Math.min(1.5, config.liveliness));+ }++ function featureScale() {+ return Math.max(0.25, config.featureScale);+ }++ function addVia(group, point, role) {+ const scale = featureScale();+ const circles = [+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaOuterRadius * scale, fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0], cy: point[1], r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ ];+ if (!role) {+ group.append(...circles);+ return circles;+ }+ const via = svgElement("g", { "data-trace-via": role });+ via.append(...circles);+ group.append(via);+ return via;+ }++ function syncAmbientRevealClip(progress = null) {+ const bottom = progress === null ? null : Math.max(0, 100 - progress * 100);+ for (const layer of mount.querySelectorAll("[data-animation]")) {+ if (layer.getAttribute("data-animation") === "scroll-trace-reveal") continue;+ if (bottom === null) layer.style.removeProperty("clip-path");+ else layer.style.clipPath = "inset(0 0 " + bottom + "% 0)";+ }+ }++ function destroyAnimationSystems() {+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ }++ function destroyRevealSystems() {+ syncAmbientRevealClip(null);+ flowReveal?.destroy();+ scrollReveal?.destroy();+ flowReveal = undefined;+ scrollReveal = undefined;+ }++ function createAnimationSystems() {+ const animationNamespace = config.animationSystem === "conductor"+ ? "signals"+ : config.animationSystem === "handshake"+ ? "handshakes"+ : config.animationSystem;+ const animationRandom = mulberry32(hashSeed([config.seed, lastSize, animationNamespace].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, field, config, animationRandom);+ } else if (+ config.animationSystem === "handshake"+ && config.motion+ && !reducedMotion+ && life() > 0.02+ ) {+ handshake = createHandshakeAnimation(mount, field, config, animationRandom, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, field, config, animationRandom, { readingZone });+ }+ }++ function build(force = false) {+ const pixelWidth = Math.max(1, mount.clientWidth);+ const pixelHeight = Math.max(1, mount.clientHeight);+ const worldWidth = pixelWidth / config.scale;+ const worldHeight = pixelHeight / config.scale;+ const pitch = config.pitch * featureScale();+ const size = `${Math.floor(worldWidth / pitch)}x${Math.floor(worldHeight / pitch)}`;+ if (!force && size === lastSize) return false;+ lastSize = size;++ destroyAnimationSystems();+ destroyRevealSystems();+ svg?.remove();+ field = generateCircuitField({ ...config, width: worldWidth, height: worldHeight });+ const revealRandom = mulberry32(hashSeed(`${config.seed}:${size}:reveal:${config.revealSystem}`));++ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${field.width} ${field.height}`,+ preserveAspectRatio: "none",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });++ const traceLayer = svgElement("g", { "data-static-traces": "" });+ const flowMarkup = config.revealSystem === "flow";+ for (const [index, trace] of field.traces.entries()) {+ const tracePath = svgElement("path", {+ ...(flowMarkup ? { "data-trace-path": "" } : {}),+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * config.featureScale,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ if (!flowMarkup) {+ traceLayer.append(tracePath);+ if (trace.viaStart) addVia(traceLayer, trace.points[0]);+ if (trace.viaEnd) addVia(traceLayer, trace.points.at(-1));+ continue;+ }+ const traceGroup = svgElement("g", { "data-circuit-trace": index });+ traceGroup.append(tracePath);+ if (trace.viaStart) addVia(traceGroup, trace.points[0], "start");+ if (trace.viaEnd) addVia(traceGroup, trace.points.at(-1), "end");+ traceLayer.append(traceGroup);+ }+ svg.append(traceLayer);+ mount.prepend(svg);++ createAnimationSystems();++ if (config.revealSystem === "flow") {+ flowReveal = createTraceFlowReveal(svg, field, config, revealRandom, {+ traceLayer,+ onComplete: () => startMotion(),+ });+ } else if (config.revealSystem === "scroll") {+ const revealLead = Math.max(0.25, Math.min(0.95, Number(config.revealScrollLead) || 0.74));+ scrollReveal = createScrollTraceReveal(svg, field, config, {+ traceLayer,+ rangeElement: mount,+ scrollRoot: window,+ progressSource: config.progressSource || "scroll",+ spawnMode: config.spawnMode,+ spawnAngle: config.spawnAngle,+ spawnSwirl: config.spawnSwirl,+ spawnOriginX: config.spawnOriginX,+ spawnOriginY: config.spawnOriginY,+ traceWindow: config.traceWindow,+ unlockLead: config.unlockLead,+ maxActiveTraces: config.maxActiveTraces,+ traceDuration: config.traceDuration,+ revealLaunchRate: config.revealLaunchRate,+ scrollSpeedResponse: config.scrollSpeedResponse,+ revealGlow: config.revealGlow,+ startOffset: Number.isFinite(Number(config.revealStartOffset))+ ? Number(config.revealStartOffset)+ : -window.innerHeight * revealLead,+ endOffset: config.endOffset,+ once: config.once !== false,+ autoStart: false,+ onProgress: (progress) => syncAmbientRevealClip(progress),+ });+ }+ return true;+ }++ function onPointerMove(event) {+ if (!field) return;+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / rect.width * field.width,+ y: (event.clientY - rect.top) / rect.height * field.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (flowReveal?.stats?.running) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function stopReveal() {+ syncAmbientRevealClip(null);+ flowReveal?.stop();+ scrollReveal?.stop();+ }++ function startReveal() {+ if (reducedMotion || config.revealSystem === "instant" || !config.revealMotion) {+ flowReveal?.stop();+ scrollReveal?.complete();+ return;+ }+ if (config.revealSystem === "flow") {+ flowReveal?.start();+ } else if (config.revealSystem === "scroll") {+ scrollReveal?.start();+ syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ }+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ stopReveal();+ scrollReveal?.complete();+ return;+ }+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ }++ function regenerate(nextOptions = {}) {+ stopMotion();+ stopReveal();+ config = { ...config, ...nextOptions };+ lastSize = "";+ build(true);+ startReveal();+ startMotion();+ return api;+ }++ function setReveal(nextOptions = {}) {+ return regenerate(nextOptions);+ }++ function setAnimation(nextOptions = {}) {+ stopMotion();+ destroyAnimationSystems();+ config = { ...config, ...nextOptions };+ createAnimationSystems();+ if (config.revealSystem === "scroll") syncAmbientRevealClip(scrollReveal?.visualProgress || 0);+ startMotion();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (config.revealSystem === "flow") {+ stopMotion();+ startReveal();+ return true;+ }+ if (config.revealSystem === "scroll") return false;+ return false;+ }++ function setRevealProgress(progress, options) {+ scrollReveal?.setProgress(progress, options);+ return api;+ }++ function exportSvg() {+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("[data-animation]").forEach((layer) => layer.remove());+ clone.querySelector("[data-static-traces]")?.style.removeProperty("visibility");+ clone.querySelector("[data-static-traces]")?.style.removeProperty("display");+ clone.querySelectorAll("[data-trace-path]").forEach((path) => {+ path.removeAttribute("stroke-dasharray");+ path.removeAttribute("stroke-dashoffset");+ path.style.removeProperty("opacity");+ path.style.removeProperty("will-change");+ });+ clone.querySelectorAll("[data-circuit-trace]").forEach((group, index) => {+ const path = group.querySelector("[data-trace-path]");+ const trace = field.traces[index];+ if (path && trace) path.setAttribute("d", pathData(trace.points));+ });+ clone.querySelectorAll("[data-trace-via]").forEach((via) => {+ via.style.removeProperty("opacity");+ via.style.removeProperty("will-change");+ });+ clone.removeAttribute("style");+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function destroy() {+ stopMotion();+ stopReveal();+ destroyAnimationSystems();+ destroyRevealSystems();+ window.clearTimeout(resizeTimer);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ svg?.remove();+ mount.style.position = originalPosition;+ mount.style.overflow = originalOverflow;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return field; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") {+ return handshake?.stats || {+ system: "adom-handshake",+ animationNodes: 0,+ activeTransactions: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "reflection") {+ return reflection?.stats || {+ system: "adom-reflection",+ animationNodes: 0,+ activeReflections: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ if (config.revealSystem === "instant") {+ return { system: "instant", traceCount: field?.traces.length || 0, completed: true, reducedMotion };+ }+ if (config.revealSystem === "flow") {+ return flowReveal?.stats || {+ system: "trace-flow-sweep",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ reducedMotion,+ };+ }+ if (config.revealSystem === "scroll") {+ return scrollReveal?.stats || {+ system: "scroll-trace-reveal",+ traceCount: field?.traces.length || 0,+ activeTraces: 0,+ completedTraces: 0,+ progress: 0,+ reducedMotion,+ };+ }+ return { system: "unknown", traceCount: 0, reducedMotion };+ },+ };++ build(true);+ resizeObserver = new ResizeObserver(() => {+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (build()) {+ startReveal();+ startMotion();+ }+ }, 220);+ });+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ startReveal();+ startMotion();+ return api;+}+++function createStreamingCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-stream-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let stream;+ let reveal;+ let traceStager;+ let svg;+ let unsubscribe;+ let fallbackUnsubscribe;+ let conductor;+ let handshake;+ let reflection;+ let resizeObserver;+ let resizeTimer;+ let ambientRefreshTimer;+ let coordinatorFrame = 0;+ let clipFrame = 0;+ let lastAmbientClipBottom = null;+ let ambientClipLayers = null;+ let generationRequest = 0;+ let generationRequestType = "";+ let generationPromise = null;+ let streamUsesWorker = false;+ let buildEpoch = 0;+ let generationTargetWorldY = 0;+ let destroyed = false;+ let pointer = null;+ let canonicalPageWidth = Math.max(+ 1,+ Number(config.canonicalPageWidth) || mount.clientWidth,+ );+ const canonicalWidthTracksViewport = Math.abs(+ canonicalPageWidth - Math.max(1, window.innerWidth || canonicalPageWidth),+ ) < 2;+ const initialPageCount = config.revealSystem === "scroll" ? 3 : 1;+ const pagePixelHeight = Math.max(+ 1,+ Number(config.canonicalPageHeight) || mount.clientHeight / initialPageCount,+ );+ let lastPixelWidth = canonicalPageWidth;+ let pageWorldHeight = pagePixelHeight / Math.max(0.01, Number(config.scale) || 1);+ let logicalPixelHeight = pagePixelHeight * initialPageCount;+ let previousViewportTop = 0;+ let previousViewportTime = performance.now();+ let latestViewport = null;+ const materializedTraces = [];+ const interactionTarget = mount.parentElement || mount;+ const readingZone = interactionTarget.querySelector?.("[data-circuit-reading-zone]") || null;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ let reducedMotion = motionPreference.matches;+ const originalMountPosition = mount.style.position;+ const originalMountOverflow = mount.style.overflow;+ const originalTargetMinHeight = interactionTarget.style.minHeight;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+ }++ function worldScale() {+ return Math.max(0.01, Number(config.scale) || 1);+ }++ function featureScale() {+ return Math.max(0.25, Number(config.featureScale) || 1);+ }++ function life() {+ return clamp(Number(config.liveliness) || 0, 0, 1.5);+ }++ function worldPerPixel() {+ return pageWorldHeight / pagePixelHeight;+ }++ function logicalWorldHeight() {+ return logicalPixelHeight * worldPerPixel();+ }++ function continuousMode() {+ return config.revealSystem === "scroll" && config.continuousGeneration;+ }++ function viewportPixelHeight() {+ return Math.max(1, window.innerHeight || document.documentElement.clientHeight || 1);+ }++ function viewportWorldHeight() {+ return viewportPixelHeight() * worldPerPixel();+ }++ function materializationFrontier(viewport) {+ return viewport.bottomWorldY + pageWorldHeight * 0.35;+ }++ function generationChunkRows() {+ const pitch = Math.max(1, (Number(config.pitch) || 7.895) * featureScale());+ return Math.max(24, Math.round(pageWorldHeight / pitch));+ }++ function currentViewport() {+ const rect = interactionTarget.getBoundingClientRect();+ const heightPixels = viewportPixelHeight();+ const topPixels = clamp(-rect.top, 0, Math.max(0, logicalPixelHeight - heightPixels));+ const now = performance.now();+ const elapsed = Math.max(1, now - previousViewportTime);+ const forwardPixels = Math.max(0, topPixels - previousViewportTop);+ const velocity = forwardPixels * worldPerPixel() / elapsed;+ previousViewportTop = topPixels;+ previousViewportTime = now;+ latestViewport = {+ topPixels,+ bottomPixels: Math.min(logicalPixelHeight, topPixels + heightPixels),+ heightPixels,+ topWorldY: topPixels * worldPerPixel(),+ bottomWorldY: Math.min(logicalPixelHeight, topPixels + heightPixels) * worldPerPixel(),+ heightWorld: heightPixels * worldPerPixel(),+ velocity,+ };+ return latestViewport;+ }++ const fieldFacade = {+ get width() { return stream?.width || lastPixelWidth / worldScale(); },+ get height() { return logicalWorldHeight(); },+ get traces() { return materializedTraces; },+ };++ function updateSvgExtent() {+ if (!svg || !stream) return;+ svg.setAttribute("viewBox", `0 0 ${stream.width} ${logicalWorldHeight()}`);+ }++ function syncAmbientRevealClip() {+ if (!reveal || !svg || config.animationSystem === "none") return;+ const stats = reveal.stats;+ const through = Number(stats.revealedThroughWorldY);+ const progress = Number.isFinite(through)+ ? clamp(through / Math.max(1, logicalWorldHeight()))+ : 0;+ const bottom = Math.max(0, 100 - progress * 100);+ if (bottom === lastAmbientClipBottom) return;+ lastAmbientClipBottom = bottom;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ ambientClipLayers = layers;+ const clipPath = "inset(0 0 " + bottom + "% 0)";+ for (const layer of layers) layer.style.clipPath = clipPath;+ }++ function scheduleAmbientClip() {+ if (+ clipFrame+ || destroyed+ || config.animationSystem === "none"+ || (!conductor && !handshake && !reflection)+ ) return;+ const tick = () => {+ clipFrame = 0;+ syncAmbientRevealClip();+ const stats = reveal?.stats;+ if (+ config.animationSystem !== "none"+ && (conductor || handshake || reflection)+ && stats+ && (stats.active > 0 || stats.queued > 0)+ ) {+ clipFrame = window.requestAnimationFrame(tick);+ }+ };+ clipFrame = window.requestAnimationFrame(tick);+ }++ function clearAmbientClip() {+ window.cancelAnimationFrame(clipFrame);+ clipFrame = 0;+ lastAmbientClipBottom = null;+ const layers = ambientClipLayers || Array.from(mount.querySelectorAll("[data-animation]"));+ for (const layer of layers) {+ if (layer.getAttribute("data-animation") !== "stream-trace-reveal") {+ layer.style.removeProperty("clip-path");+ }+ }+ ambientClipLayers = null;+ }++ function stopMotion() {+ conductor?.stop();+ handshake?.stop();+ reflection?.stop();+ }++ function destroyAnimationSystems() {+ window.clearTimeout(ambientRefreshTimer);+ ambientRefreshTimer = 0;+ stopMotion();+ conductor?.destroy();+ handshake?.destroy();+ reflection?.destroy();+ conductor = undefined;+ handshake = undefined;+ reflection = undefined;+ ambientClipLayers = null;+ lastAmbientClipBottom = null;+ }++ function createAnimationSystems() {+ if (!svg || !stream || config.animationSystem === "none") return;+ const namespace = config.animationSystem === "conductor"+ ? "stream-signals"+ : `stream-${config.animationSystem}`;+ const random = mulberry32(hashSeed([+ config.seed,+ Math.round(stream.width),+ Math.round(logicalWorldHeight()),+ namespace,+ ].join(":")));+ if (config.animationSystem === "conductor") {+ conductor = createConductorAnimation(svg, fieldFacade, config, random);+ } else if (config.animationSystem === "handshake") {+ handshake = createHandshakeAnimation(mount, fieldFacade, config, random, { readingZone });+ } else if (config.animationSystem === "reflection") {+ reflection = createReflectionAnimation(mount, fieldFacade, config, random, { readingZone });+ }+ ambientClipLayers = Array.from(mount.querySelectorAll("[data-animation]"))+ .filter((layer) => layer.getAttribute("data-animation") !== "stream-trace-reveal");+ syncAmbientRevealClip();+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (config.animationSystem === "conductor") conductor?.start();+ else if (config.animationSystem === "handshake") handshake?.start();+ else if (config.animationSystem === "reflection") reflection?.start();+ }++ function refreshGrowingCanvasAnimation() {+ if (!reflection && !handshake) return;+ window.clearTimeout(ambientRefreshTimer);+ const epoch = buildEpoch;+ const candidate = stream;+ ambientRefreshTimer = window.setTimeout(() => {+ ambientRefreshTimer = 0;+ if (destroyed || epoch !== buildEpoch || candidate !== stream) return;+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ }, 180);+ }++ function stopReveal() {+ reveal?.stop();+ }++ function startReveal() {+ if (!reveal) return;+ if (reducedMotion || !config.revealMotion) reveal.complete();+ else reveal.start();+ scheduleAmbientClip();+ }++ function cancelGenerationRequest() {+ if (!generationRequest) return;+ if (generationRequestType === "idle" && window.cancelIdleCallback) {+ window.cancelIdleCallback(generationRequest);+ } else {+ window.clearTimeout(generationRequest);+ }+ generationRequest = 0;+ generationRequestType = "";+ }++ function extendPageWhenReady(viewport = currentViewport()) {+ if (!stream || !continuousMode()) return false;+ const distancePixels = logicalPixelHeight - viewport.bottomPixels;+ if (distancePixels > pagePixelHeight * 1.45) return false;+ const extendPages = Math.max(1, Math.round(Number(config.generationExtendScreens) || 1));+ const nextPixelHeight = logicalPixelHeight + pagePixelHeight * extendPages;+ const nextWorldHeight = logicalWorldHeight() + pageWorldHeight * extendPages;+ if (stream.generatedThrough + stream.stats.pitch * 0.25 < nextWorldHeight) return false;+ logicalPixelHeight = nextPixelHeight;+ interactionTarget.style.minHeight = Math.ceil(logicalPixelHeight) + "px";+ updateSvgExtent();+ refreshGrowingCanvasAnimation();+ return true;+ }++ function pumpGeneration() {+ generationRequest = 0;+ generationRequestType = "";+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const stats = stream.stats;+ const chunkHeight = Math.max(stats.pitch, stats.pitch * stats.chunkRows);+ const through = Math.min(generationTargetWorldY, stream.generatedThrough + chunkHeight);+ stream.ensureThrough(through);+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ }++ function scheduleWorkerGeneration() {+ if (generationPromise || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ const candidate = stream;+ const epoch = buildEpoch;+ const target = Math.min(+ generationTargetWorldY,+ stream.generatedThrough + pageWorldHeight,+ );+ generationPromise = candidate.ensureThrough(target)+ .then(() => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;+ const viewport = latestViewport || currentViewport();+ const extended = extendPageWhenReady(viewport);+ if (extended) coordinate(viewport);+ })+ .catch((error) => {+ if (+ !destroyed+ && candidate === stream+ && epoch === buildEpoch+ && error?.name !== "AbortError"+ ) {+ fallbackToSynchronousStream(candidate);+ }+ })+ .finally(() => {+ if (candidate !== stream || epoch !== buildEpoch) return;+ generationPromise = null;+ if (stream.generatedThrough < generationTargetWorldY) scheduleGeneration();+ });+ }++ function scheduleGeneration() {+ if (destroyed || !stream || stream.generatedThrough >= generationTargetWorldY) return;+ if (streamUsesWorker) {+ if (generationPromise || generationRequest) return;+ const run = () => {+ generationRequest = 0;+ generationRequestType = "";+ scheduleWorkerGeneration();+ };+ if (typeof window.requestIdleCallback === "function") {+ generationRequestType = "idle";+ generationRequest = window.requestIdleCallback(run, { timeout: 150 });+ } else {+ generationRequestType = "timer";+ generationRequest = window.setTimeout(run, 16);+ }+ return;+ }+ if (generationRequest) return;+ if (typeof window.requestIdleCallback === "function") {+ generationRequestType = "idle";+ generationRequest = window.requestIdleCallback(pumpGeneration, { timeout: 120 });+ } else {+ generationRequestType = "timer";+ generationRequest = window.setTimeout(pumpGeneration, 16);+ }+ }++ function coordinate(measured = null) {+ if (destroyed || !stream || !reveal) return;+ const requiredPages = Math.max(1, Math.ceil((mount.clientHeight - 1) / pagePixelHeight));+ const requiredPixelHeight = requiredPages * pagePixelHeight;+ if (requiredPixelHeight > logicalPixelHeight) {+ logicalPixelHeight = requiredPixelHeight;+ updateSvgExtent();+ }+ const viewport = measured || currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: viewport.velocity,+ });+ traceStager?.materializeThrough(materializationFrontier(viewport));+ if (continuousMode()) {+ const aheadPages = clamp(Number(config.generationAheadScreens) || 2, 1, 6);+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ logicalWorldHeight() + pageWorldHeight * aheadPages,+ );+ if (logicalPixelHeight - viewport.bottomPixels <= pagePixelHeight * 1.45) {+ const extendPages = Math.max(1, Math.round(Number(config.generationExtendScreens) || 1));+ generationTargetWorldY = Math.max(+ generationTargetWorldY,+ logicalWorldHeight() + pageWorldHeight * (aheadPages + extendPages),+ );+ }+ } else {+ generationTargetWorldY = Math.max(generationTargetWorldY, logicalWorldHeight());+ }+ extendPageWhenReady(viewport);+ scheduleGeneration();+ scheduleAmbientClip();+ }++ function scheduleCoordinate() {+ if (coordinatorFrame || destroyed) return;+ coordinatorFrame = window.requestAnimationFrame(() => {+ coordinatorFrame = 0;+ coordinate();+ });+ }++ function createSvg() {+ svg = svgElement("svg", {+ id,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${stream.width} ${logicalWorldHeight()}`,+ preserveAspectRatio: "none",+ "data-continuous-circuit": "v8",+ });+ Object.assign(svg.style, {+ position: "absolute",+ inset: "0",+ width: "100%",+ height: "100%",+ display: "block",+ pointerEvents: "none",+ });+ mount.prepend(svg);+ }++ function fallbackToSynchronousStream(candidate) {+ if (destroyed || candidate !== stream) return;+ build(false);+ }++ async function initializeStream(candidate, streamOptions, epoch, useWorker) {+ try {+ if (useWorker) await candidate.ready;+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;+ const canonicalPageHeight = Number(candidate.stats.initialPageHeight);+ if (Number.isFinite(canonicalPageHeight) && canonicalPageHeight > 0) {+ pageWorldHeight = canonicalPageHeight;+ }++ createSvg();+ reveal = createStreamingTraceReveal(svg, config, {+ ...config,+ width: candidate.width,+ autoStart: false,+ });+ traceStager = createPageTraceStager({+ materialize(traces) {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || !reveal) return;+ reveal.appendTraces(traces);+ materializedTraces.push(...traces);+ if (reducedMotion || !config.revealMotion) reveal.complete();+ refreshGrowingCanvasAnimation();+ scheduleAmbientClip();+ },+ });+ const viewport = currentViewport();+ reveal.setViewport({+ topWorldY: viewport.topWorldY,+ bottomWorldY: viewport.bottomWorldY,+ height: viewport.heightWorld,+ velocity: 0,+ });+ traceStager.materializeThrough(materializationFrontier(viewport));+ unsubscribe = candidate.onAppend((traces) => {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || !traceStager) return;+ traceStager.stage(traces);+ });+ const initialThrough = Math.min(logicalWorldHeight(), pageWorldHeight);+ await Promise.resolve(candidate.ensureThrough(initialThrough));+ if (destroyed || candidate !== stream || epoch !== buildEpoch) return;++ const aheadPages = continuousMode()+ ? clamp(Number(config.generationAheadScreens) || 2, 1, 6)+ : 0;+ generationTargetWorldY = logicalWorldHeight() + pageWorldHeight * aheadPages;+ createAnimationSystems();+ startReveal();+ startMotion();+ coordinate(viewport);+ scheduleGeneration();+ } catch (error) {+ if (destroyed || candidate !== stream || epoch !== buildEpoch || error?.name === "AbortError") return;+ if (useWorker) fallbackToSynchronousStream(candidate);+ else console.error("Circuit field generation failed", error, streamOptions);+ }+ }++ function build(useWorker = true) {+ buildEpoch += 1;+ const epoch = buildEpoch;+ cancelGenerationRequest();+ generationPromise = null;+ window.cancelAnimationFrame(coordinatorFrame);+ coordinatorFrame = 0;+ clearAmbientClip();+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ unsubscribe = undefined;+ fallbackUnsubscribe = undefined;+ reveal?.destroy();+ reveal = undefined;+ traceStager?.destroy();+ traceStager = undefined;+ materializedTraces.length = 0;+ stream?.destroy();+ stream = undefined;+ svg?.remove();+ svg = undefined;+ lastPixelWidth = canonicalPageWidth;+ logicalPixelHeight = Math.max(logicalPixelHeight, mount.clientHeight);+ pageWorldHeight = pagePixelHeight / worldScale();+ interactionTarget.style.minHeight = Math.ceil(logicalPixelHeight) + "px";+ const streamOptions = {+ ...config,+ width: lastPixelWidth / worldScale(),+ initialPageHeight: pagePixelHeight / worldScale(),+ chunkRows: generationChunkRows(),+ };+ streamUsesWorker = useWorker;+ stream = useWorker+ ? createStreamingCircuitFieldWorker(streamOptions)+ : createHybridCircuitField(streamOptions);+ const candidate = stream;+ if (useWorker) {+ fallbackUnsubscribe = candidate.onFallback(() => {+ fallbackToSynchronousStream(candidate);+ });+ }+ initializeStream(candidate, streamOptions, epoch, useWorker);+ }++ function onPointerMove(event) {+ if (!stream) return;+ const rect = mount.getBoundingClientRect();+ if (rect.width <= 0 || rect.height <= 0) return;+ pointer = {+ x: (event.clientX - rect.left) / rect.width * fieldFacade.width,+ y: (event.clientY - rect.top) / rect.height * fieldFacade.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ handshake?.pointerMoved(pointer);+ reflection?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 3000;+ handshake?.pointerLeft();+ reflection?.pointerLeft();+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else if (config.animationSystem === "handshake") handshake?.clicked(pointer);+ else if (config.animationSystem === "reflection") reflection?.clicked(pointer);+ }++ function onMotionPreferenceChange(event) {+ reducedMotion = event.matches;+ if (reducedMotion) {+ stopMotion();+ reveal?.complete();+ } else {+ reveal?.start();+ startMotion();+ }+ scheduleAmbientClip();+ }++ function regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ config = { ...config, ...nextOptions };+ build();+ coordinate();+ return api;+ }++ function setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ reveal?.updateOptions(config);+ if (reducedMotion || !config.revealMotion) reveal?.complete();+ else reveal?.start();+ coordinate();+ return api;+ }++ function setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ config = { ...config, ...nextOptions };+ destroyAnimationSystems();+ createAnimationSystems();+ startMotion();+ scheduleAmbientClip();+ return api;+ }++ function triggerAnimation(origin = null) {+ if (config.animationSystem === "conductor") return conductor?.trigger(origin) || false;+ if (config.animationSystem === "handshake") return handshake?.trigger(origin) || false;+ if (config.animationSystem === "reflection") return reflection?.trigger(origin) || false;+ return false;+ }++ function triggerReveal() {+ if (!reveal || reducedMotion || !config.revealMotion) return false;+ reveal.reset();+ reveal.start();+ coordinate();+ return true;+ }++ function setRevealProgress(progress, progressOptions = {}) {+ if (!reveal) return api;+ const amount = clamp(Number(progress) || 0);+ const height = viewportWorldHeight();+ const topWorldY = Math.max(0, (logicalWorldHeight() - height) * amount);+ reveal.setViewport({+ topWorldY,+ bottomWorldY: topWorldY + height,+ height,+ velocity: Math.max(0, Number(progressOptions.velocity) || 0),+ });+ traceStager?.materializeThrough(topWorldY + height + pageWorldHeight * 0.35);+ scheduleAmbientClip();+ return api;+ }++ function addExportVia(group, point) {+ const scale = featureScale();+ group.append(+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaOuterRadius * scale,+ fill: config.traceColor,+ }),+ svgElement("circle", {+ cx: point[0],+ cy: point[1],+ r: config.viaInnerRadius * scale,+ fill: "var(--circuit-hole, #0d1117)",+ }),+ );+ }++ function exportSvg() {+ const exportHeight = Math.max(logicalWorldHeight(), stream?.generatedThrough || 0);+ const exported = svgElement("svg", {+ xmlns: SVG_NS,+ "aria-hidden": true,+ focusable: false,+ viewBox: `0 0 ${fieldFacade.width} ${exportHeight}`,+ preserveAspectRatio: "none",+ });+ const paths = svgElement("g", { "data-static-traces": "" });+ const vias = svgElement("g", { "data-static-vias": "" });+ for (const trace of stream?.traces || []) {+ paths.append(svgElement("path", {+ d: pathData(trace.points),+ fill: "none",+ stroke: config.traceColor,+ "stroke-width": config.traceWidth * featureScale(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ }));+ addExportVia(vias, trace.points[0]);+ addExportVia(vias, trace.points.at(-1));+ }+ exported.append(paths, vias);+ return `<?xml version="1.0" encoding="UTF-8"?>\n${exported.outerHTML}`;+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ buildEpoch += 1;+ generationPromise = null;+ cancelGenerationRequest();+ window.cancelAnimationFrame(coordinatorFrame);+ window.cancelAnimationFrame(clipFrame);+ window.clearTimeout(resizeTimer);+ window.clearTimeout(ambientRefreshTimer);+ resizeObserver?.disconnect();+ window.removeEventListener("scroll", scheduleCoordinate);+ window.removeEventListener("resize", scheduleCoordinate);+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ if (motionPreference.removeEventListener) {+ motionPreference.removeEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.removeListener?.(onMotionPreferenceChange);+ }+ destroyAnimationSystems();+ unsubscribe?.();+ fallbackUnsubscribe?.();+ reveal?.destroy();+ traceStager?.destroy();+ materializedTraces.length = 0;+ stream?.destroy();+ svg?.remove();+ mount.style.position = originalMountPosition;+ mount.style.overflow = originalMountOverflow;+ interactionTarget.style.minHeight = originalTargetMinHeight;+ }++ const api = {+ regenerate,+ setReveal,+ setAnimation,+ triggerAnimation,+ triggerBloom: triggerAnimation,+ triggerReveal,+ setRevealProgress,+ exportSvg,+ destroy,+ get field() { return fieldFacade; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return { system: "none", animationNodes: 0, frameCount: 0, reducedMotion };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ if (config.animationSystem === "handshake") return handshake?.stats;+ if (config.animationSystem === "reflection") return reflection?.stats;+ return { system: "unknown", animationNodes: 0, frameCount: 0, reducedMotion };+ },+ get revealStats() {+ const stats = reveal?.stats || {};+ if (config.revealSystem === "instant") {+ return {+ system: "instant",+ continuous: false,+ traceCount: fieldFacade.traces.length,+ completed: true,+ generatedThrough: stream?.generatedThrough || 0,+ canonicalPageWorldHeight: pageWorldHeight,+ reducedMotion,+ };+ }+ return {+ system: "scroll-trace-reveal",+ continuous: continuousMode(),+ traceCount: fieldFacade.traces.length,+ generatedTraceCount: stream?.traces.length || 0,+ materializedTraceCount: traceStager?.stats.materializedTraces || 0,+ bufferedTraceCount: traceStager?.stats.bufferedTraces || 0,+ activeTraces: stats.active || 0,+ queuedTraces: stats.queued || 0,+ completedTraces: stats.completed || 0,+ unlockedTraces: stats.unlocked || 0,+ generatedThrough: stream?.generatedThrough || 0,+ pageWorldHeight: logicalWorldHeight(),+ canonicalPageWorldHeight: pageWorldHeight,+ reducedMotion,+ };+ },+ };++ build();+ resizeObserver = new ResizeObserver(() => {+ const nextWidth = canonicalWidthTracksViewport+ ? Math.max(1, window.innerWidth || mount.clientWidth)+ : Math.max(1, mount.clientWidth);+ if (Math.abs(nextWidth - lastPixelWidth) < 1) return;+ canonicalPageWidth = nextWidth;+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (!destroyed) regenerate();+ }, 180);+ });+ resizeObserver.observe(mount);+ window.addEventListener("scroll", scheduleCoordinate, { passive: true });+ window.addEventListener("resize", scheduleCoordinate, { passive: true });+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ if (motionPreference.addEventListener) {+ motionPreference.addEventListener("change", onMotionPreferenceChange);+ } else {+ motionPreference.addListener?.(onMotionPreferenceChange);+ }+ coordinate();+ return api;+}++function normalizeOptions(options = {}) {+ const normalized = { ...options };+ if (normalized.animationSystem === "growth") {+ normalized.animationSystem = "none";+ if (!normalized.revealSystem) normalized.revealSystem = "flow";+ if (normalized.revealMotion === undefined) normalized.revealMotion = true;+ }+ if (normalized.spawnSystem && !normalized.revealSystem) {+ normalized.revealSystem = normalized.spawnSystem === "front"+ ? "flow"+ : normalized.spawnSystem;+ }+ return normalized;+}++export function createCircuitBackground(mount, options = {}) {+ let config = { ...DEFAULTS, ...normalizeOptions(options) };+ let destroyed = false;+ const engineKind = (value) => {+ if (value.animationSystem === "adom") return "routed";+ if (value.revealSystem === "flow") return "finite";+ if (value.revealSystem === "scroll") return "page-scroll";+ return "finite";+ };+ const createEngine = () => {+ const kind = engineKind(config);+ if (kind === "routed") {+ return createLegacyCircuitBackground(mount, { ...config, revealSystem: "instant" });+ }+ if (kind.startsWith("page-")) return createStreamingCircuitBackground(mount, config);+ return createModernCircuitBackground(mount, config);+ };+ let engine = createEngine();++ function recreateEngine() {+ engine.destroy();+ engine = createEngine();+ }++ const api = {+ regenerate(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot regenerate a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else engine.regenerate(normalized);+ return api;+ },+ setReveal(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) !== "routed") engine.setReveal?.(normalized);+ return api;+ },+ setAnimation(nextOptions = {}) {+ if (destroyed) throw new Error("Cannot update a destroyed circuit background");+ const previousKind = engineKind(config);+ const normalized = normalizeOptions(nextOptions);+ config = { ...config, ...normalized };+ if (previousKind !== engineKind(config)) recreateEngine();+ else if (engineKind(config) === "routed") engine.regenerate(normalized);+ else engine.setAnimation(normalized);+ return api;+ },+ triggerAnimation(origin = null) {+ return engine.triggerAnimation?.(origin) || false;+ },+ triggerBloom(origin = null) {+ return engine.triggerBloom?.(origin) || engine.triggerAnimation?.(origin) || false;+ },+ triggerReveal() {+ if (engineKind(config) === "routed") return false;+ return engine.triggerReveal?.() || false;+ },+ setRevealProgress(progress, progressOptions) {+ if (engineKind(config) !== "routed") {+ engine.setRevealProgress?.(progress, progressOptions);+ }+ return api;+ },+ exportSvg() {+ return engine.exportSvg();+ },+ destroy() {+ if (destroyed) return;+ destroyed = true;+ engine.destroy();+ },+ get field() { return engine.field; },+ get animationStats() { return engine.animationStats; },+ get revealStats() {+ if (engineKind(config) === "routed") {+ return { system: "unavailable-routed", traceCount: engine.field?.traces.length || 0 };+ }+ return engine.revealStats;+ },+ };++ return api;+}++export {+ DEFAULTS,+ ANIMATION_PRESETS,+ REVEAL_PRESETS,+ TRACE_SPAWN_PRESETS,+ generateCircuitField,+ pathData,+};
src/circuit-field-hybrid-client-v8.jsadded+422@@ -0,0 +1,422 @@+const EMPTY_STATS = Object.freeze({+ chunks: 0,+ columns: 0,+ chunkRows: 0,+ pitch: 0,+ width: 0,+ generatedThrough: 0,+ occupiedCells: 0,+ occupancyFill: 0,+ occupiedCellsRetained: 0,+ occupiedCellsPruned: 0,+ occupancyRowsRetained: 0,+ occupancyRowsPruned: 0,+ flowVorticesRetained: 0,+ flowVorticesPruned: 0,+ generationCacheMinimumRow: 1,+ totalPublished: 0,+ retainedTraces: 0,+ totalPruned: 0,+ rejectedRoutes: 0,+ routeGuardRows: 0,+ occupancyRetainedForSafety: true,+ initialPublished: false,+ initialPageHeight: 0,+ initialPageRows: 0,+ initialPageTraceCount: 0,+});++function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ promise.catch(() => {});+ return {+ promise,+ resolve,+ reject,+ settled: false,+ };+}++function abortError(message) {+ if (typeof DOMException === "function") {+ return new DOMException(message, "AbortError");+ }+ const error = new Error(message);+ error.name = "AbortError";+ return error;+}++function errorFromPayload(payload, fallbackMessage) {+ const error = new Error(payload?.message || fallbackMessage);+ error.name = payload?.name || "Error";+ if (payload?.stack) error.stack = payload.stack;+ return error;+}++function immutableStats(stats) {+ return Object.freeze({ ...EMPTY_STATS, ...(stats || {}) });+}++function immutableTrace(trace) {+ return Object.freeze(trace);+}++function notify(callbacks, value, api) {+ for (const callback of callbacks) {+ try {+ callback(value, api);+ } catch (error) {+ console.error("Circuit field worker callback failed", error);+ }+ }+}++/**+ * Main-thread client for circuit-field-hybrid-worker-v8.js.+ *+ * The returned facade is available immediately. Await `ready` before reading+ * normalized dimensions. `ensureThrough()` resolves after all append callbacks+ * for its requested frontier have run.+ */+export function createStreamingCircuitFieldWorker(options = {}, clientOptions = {}) {+ const appendCallbacks = new Set();+ const fallbackCallbacks = new Set();+ const statusCallbacks = new Set();+ const pendingEnsures = new Map();+ const pendingPrunes = new Map();+ const retained = [];++ let currentOptions = { ...options };+ let worker;+ let workerEpoch = 0;+ let requestSequence = 0;+ let readyState;+ let lastStats = EMPTY_STATS;+ let fallbackReason = null;+ let state = "starting";+ let destroyed = false;++ const workerUrl = clientOptions.workerUrl+ || new URL("./circuit-field-hybrid-worker-v8.js", import.meta.url);+ const workerName = clientOptions.name || "circuit-field-hybrid-v8";++ function setState(nextState) {+ if (state === nextState) return;+ state = nextState;+ queueMicrotask(() => notify(statusCallbacks, nextState, api));+ }++ function rejectPending(error) {+ for (const request of pendingEnsures.values()) request.reject(error);+ for (const request of pendingPrunes.values()) request.reject(error);+ pendingEnsures.clear();+ pendingPrunes.clear();+ }++ function terminateWorker() {+ if (!worker) return;+ const target = worker;+ worker = undefined;+ try {+ target.postMessage({ type: "destroy" });+ } catch {+ // The worker may already have stopped.+ }+ target.terminate();+ }++ function signalFallback(kind, error, phase = "startup") {+ if (destroyed || state === "failed") return;+ const normalizedError = error instanceof Error+ ? error+ : errorFromPayload(error, "Circuit field worker failed");+ fallbackReason = Object.freeze({+ kind,+ phase,+ error: normalizedError,+ options: Object.freeze({ ...currentOptions }),+ synchronousFallbackAvailable: true,+ });+ setState("failed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(normalizedError);+ }+ rejectPending(normalizedError);+ notify(fallbackCallbacks, fallbackReason, api);+ }++ function createWorkerInstance() {+ if (typeof clientOptions.workerFactory === "function") {+ return clientOptions.workerFactory(workerUrl, {+ type: "module",+ name: workerName,+ });+ }+ if (typeof Worker !== "function") {+ throw new Error("Web Workers are unavailable");+ }+ return new Worker(workerUrl, {+ type: "module",+ name: workerName,+ });+ }++ function handleAppend(message) {+ lastStats = immutableStats(message.stats);+ const batch = Object.freeze(+ (message.traces || []).map(immutableTrace),+ );+ retained.push(...batch);+ notify(appendCallbacks, batch, api);+ }++ function handleEnsured(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingEnsures.get(message.requestId);+ if (!request) return;+ pendingEnsures.delete(message.requestId);+ request.resolve(Object.freeze({+ target: message.target,+ generatedThrough: message.generatedThrough,+ stats: lastStats,+ }));+ if (!pendingEnsures.size) setState("ready");+ }++ function handlePruned(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingPrunes.get(message.requestId);+ if (!request) return;+ pendingPrunes.delete(message.requestId);+ const removedIds = Object.freeze((message.removedIds || []).slice());+ if (removedIds.length) {+ const removed = new Set(removedIds);+ let writeIndex = 0;+ for (const trace of retained) {+ if (removed.has(trace.id)) continue;+ retained[writeIndex] = trace;+ writeIndex += 1;+ }+ retained.length = writeIndex;+ }+ request.resolve(removedIds);+ }++ function handleMessage(event, epoch) {+ if (destroyed || epoch !== workerEpoch) return;+ const message = event.data || {};+ if (message.type === "ready") {+ lastStats = immutableStats(message.stats);+ setState("ready");+ if (!readyState.settled) {+ readyState.settled = true;+ readyState.resolve(api);+ }+ } else if (message.type === "append") {+ handleAppend(message);+ } else if (message.type === "ensured") {+ handleEnsured(message);+ } else if (message.type === "pruned") {+ handlePruned(message);+ } else if (message.type === "fatal") {+ signalFallback(+ "worker-runtime-error",+ errorFromPayload(message.error, "Circuit field worker failed"),+ message.phase,+ );+ } else {+ signalFallback(+ "worker-protocol-error",+ new Error(`Unknown worker response: ${String(message.type)}`),+ "message",+ );+ }+ }++ function startWorker() {+ workerEpoch += 1;+ const epoch = workerEpoch;+ readyState = deferred();+ fallbackReason = null;+ setState("starting");++ try {+ worker = createWorkerInstance();+ worker.addEventListener("message", (event) => handleMessage(event, epoch));+ worker.addEventListener("error", (event) => {+ if (epoch !== workerEpoch || destroyed) return;+ event.preventDefault?.();+ signalFallback(+ "worker-runtime-error",+ event.error || new Error(event.message || "Circuit field worker crashed"),+ "runtime",+ );+ });+ worker.addEventListener("messageerror", () => {+ if (epoch !== workerEpoch || destroyed) return;+ signalFallback(+ "worker-message-error",+ new Error("Circuit field worker returned an unreadable message"),+ "message",+ );+ });+ worker.postMessage({+ type: "init",+ options: currentOptions,+ });+ } catch (error) {+ signalFallback("worker-unavailable", error, "startup");+ }+ return readyState.promise;+ }++ async function ensureThrough(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const target = Math.max(0, Number(worldY) || 0);+ if (lastStats.initialPublished && lastStats.generatedThrough >= target) {+ return Object.freeze({+ target,+ generatedThrough: lastStats.generatedThrough,+ stats: lastStats,+ });+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingEnsures.set(requestId, request);+ setState("generating");+ try {+ worker.postMessage({ type: "ensure", requestId, target });+ } catch (error) {+ signalFallback("worker-message-error", error, "ensure");+ }+ return request.promise;+ }++ async function pruneBefore(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingPrunes.set(requestId, request);+ try {+ worker.postMessage({+ type: "prune",+ requestId,+ worldY: Number(worldY) || 0,+ });+ } catch (error) {+ signalFallback("worker-message-error", error, "prune");+ }+ return request.promise;+ }++ function onAppend(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ appendCallbacks.add(callback);+ return () => appendCallbacks.delete(callback);+ }++ function onFallback(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ fallbackCallbacks.add(callback);+ if (fallbackReason) {+ const reason = fallbackReason;+ const epoch = workerEpoch;+ queueMicrotask(() => {+ if (+ destroyed+ || epoch !== workerEpoch+ || fallbackReason !== reason+ || !fallbackCallbacks.has(callback)+ ) return;+ notify([callback], reason, api);+ });+ }+ return () => fallbackCallbacks.delete(callback);+ }++ function onStatus(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ statusCallbacks.add(callback);+ return () => statusCallbacks.delete(callback);+ }++ function reset(nextOptions = {}) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const resetError = abortError("Circuit field worker was reset");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(resetError);+ }+ rejectPending(resetError);+ retained.length = 0;+ lastStats = EMPTY_STATS;+ currentOptions = { ...currentOptions, ...nextOptions };+ return startWorker();+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ const destroyedError = abortError("Circuit field worker was destroyed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(destroyedError);+ }+ rejectPending(destroyedError);+ appendCallbacks.clear();+ fallbackCallbacks.clear();+ statusCallbacks.clear();+ retained.length = 0;+ state = "destroyed";+ }++ const api = {+ ensureThrough,+ onAppend,+ onFallback,+ onStatus,+ pruneBefore,+ reset,+ destroy,+ get ready() { return readyState.promise; },+ get status() { return state; },+ get fallbackReason() { return fallbackReason; },+ get width() { return lastStats.width; },+ get height() { return lastStats.generatedThrough; },+ get generatedThrough() { return lastStats.generatedThrough; },+ get frontier() { return lastStats.generatedThrough; },+ get traces() { return retained; },+ get retainedTraces() { return retained; },+ get stats() { return lastStats; },+ };++ startWorker();+ return api;+}+
src/circuit-field-hybrid-client-v9.jsadded+422@@ -0,0 +1,422 @@+const EMPTY_STATS = Object.freeze({+ chunks: 0,+ columns: 0,+ chunkRows: 0,+ pitch: 0,+ width: 0,+ generatedThrough: 0,+ occupiedCells: 0,+ occupancyFill: 0,+ occupiedCellsRetained: 0,+ occupiedCellsPruned: 0,+ occupancyRowsRetained: 0,+ occupancyRowsPruned: 0,+ flowVorticesRetained: 0,+ flowVorticesPruned: 0,+ generationCacheMinimumRow: 1,+ totalPublished: 0,+ retainedTraces: 0,+ totalPruned: 0,+ rejectedRoutes: 0,+ routeGuardRows: 0,+ occupancyRetainedForSafety: true,+ initialPublished: false,+ initialPageHeight: 0,+ initialPageRows: 0,+ initialPageTraceCount: 0,+});++function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ promise.catch(() => {});+ return {+ promise,+ resolve,+ reject,+ settled: false,+ };+}++function abortError(message) {+ if (typeof DOMException === "function") {+ return new DOMException(message, "AbortError");+ }+ const error = new Error(message);+ error.name = "AbortError";+ return error;+}++function errorFromPayload(payload, fallbackMessage) {+ const error = new Error(payload?.message || fallbackMessage);+ error.name = payload?.name || "Error";+ if (payload?.stack) error.stack = payload.stack;+ return error;+}++function immutableStats(stats) {+ return Object.freeze({ ...EMPTY_STATS, ...(stats || {}) });+}++function immutableTrace(trace) {+ return Object.freeze(trace);+}++function notify(callbacks, value, api) {+ for (const callback of callbacks) {+ try {+ callback(value, api);+ } catch (error) {+ console.error("Circuit field worker callback failed", error);+ }+ }+}++/**+ * Main-thread client for circuit-field-hybrid-worker-v9.js.+ *+ * The returned facade is available immediately. Await `ready` before reading+ * normalized dimensions. `ensureThrough()` resolves after all append callbacks+ * for its requested frontier have run.+ */+export function createStreamingCircuitFieldWorker(options = {}, clientOptions = {}) {+ const appendCallbacks = new Set();+ const fallbackCallbacks = new Set();+ const statusCallbacks = new Set();+ const pendingEnsures = new Map();+ const pendingPrunes = new Map();+ const retained = [];++ let currentOptions = { ...options };+ let worker;+ let workerEpoch = 0;+ let requestSequence = 0;+ let readyState;+ let lastStats = EMPTY_STATS;+ let fallbackReason = null;+ let state = "starting";+ let destroyed = false;++ const workerUrl = clientOptions.workerUrl+ || new URL("./circuit-field-hybrid-worker-v9.js", import.meta.url);+ const workerName = clientOptions.name || "circuit-field-hybrid-v9";++ function setState(nextState) {+ if (state === nextState) return;+ state = nextState;+ queueMicrotask(() => notify(statusCallbacks, nextState, api));+ }++ function rejectPending(error) {+ for (const request of pendingEnsures.values()) request.reject(error);+ for (const request of pendingPrunes.values()) request.reject(error);+ pendingEnsures.clear();+ pendingPrunes.clear();+ }++ function terminateWorker() {+ if (!worker) return;+ const target = worker;+ worker = undefined;+ try {+ target.postMessage({ type: "destroy" });+ } catch {+ // The worker may already have stopped.+ }+ target.terminate();+ }++ function signalFallback(kind, error, phase = "startup") {+ if (destroyed || state === "failed") return;+ const normalizedError = error instanceof Error+ ? error+ : errorFromPayload(error, "Circuit field worker failed");+ fallbackReason = Object.freeze({+ kind,+ phase,+ error: normalizedError,+ options: Object.freeze({ ...currentOptions }),+ synchronousFallbackAvailable: true,+ });+ setState("failed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(normalizedError);+ }+ rejectPending(normalizedError);+ notify(fallbackCallbacks, fallbackReason, api);+ }++ function createWorkerInstance() {+ if (typeof clientOptions.workerFactory === "function") {+ return clientOptions.workerFactory(workerUrl, {+ type: "module",+ name: workerName,+ });+ }+ if (typeof Worker !== "function") {+ throw new Error("Web Workers are unavailable");+ }+ return new Worker(workerUrl, {+ type: "module",+ name: workerName,+ });+ }++ function handleAppend(message) {+ lastStats = immutableStats(message.stats);+ const batch = Object.freeze(+ (message.traces || []).map(immutableTrace),+ );+ retained.push(...batch);+ notify(appendCallbacks, batch, api);+ }++ function handleEnsured(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingEnsures.get(message.requestId);+ if (!request) return;+ pendingEnsures.delete(message.requestId);+ request.resolve(Object.freeze({+ target: message.target,+ generatedThrough: message.generatedThrough,+ stats: lastStats,+ }));+ if (!pendingEnsures.size) setState("ready");+ }++ function handlePruned(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingPrunes.get(message.requestId);+ if (!request) return;+ pendingPrunes.delete(message.requestId);+ const removedIds = Object.freeze((message.removedIds || []).slice());+ if (removedIds.length) {+ const removed = new Set(removedIds);+ let writeIndex = 0;+ for (const trace of retained) {+ if (removed.has(trace.id)) continue;+ retained[writeIndex] = trace;+ writeIndex += 1;+ }+ retained.length = writeIndex;+ }+ request.resolve(removedIds);+ }++ function handleMessage(event, epoch) {+ if (destroyed || epoch !== workerEpoch) return;+ const message = event.data || {};+ if (message.type === "ready") {+ lastStats = immutableStats(message.stats);+ setState("ready");+ if (!readyState.settled) {+ readyState.settled = true;+ readyState.resolve(api);+ }+ } else if (message.type === "append") {+ handleAppend(message);+ } else if (message.type === "ensured") {+ handleEnsured(message);+ } else if (message.type === "pruned") {+ handlePruned(message);+ } else if (message.type === "fatal") {+ signalFallback(+ "worker-runtime-error",+ errorFromPayload(message.error, "Circuit field worker failed"),+ message.phase,+ );+ } else {+ signalFallback(+ "worker-protocol-error",+ new Error(`Unknown worker response: ${String(message.type)}`),+ "message",+ );+ }+ }++ function startWorker() {+ workerEpoch += 1;+ const epoch = workerEpoch;+ readyState = deferred();+ fallbackReason = null;+ setState("starting");++ try {+ worker = createWorkerInstance();+ worker.addEventListener("message", (event) => handleMessage(event, epoch));+ worker.addEventListener("error", (event) => {+ if (epoch !== workerEpoch || destroyed) return;+ event.preventDefault?.();+ signalFallback(+ "worker-runtime-error",+ event.error || new Error(event.message || "Circuit field worker crashed"),+ "runtime",+ );+ });+ worker.addEventListener("messageerror", () => {+ if (epoch !== workerEpoch || destroyed) return;+ signalFallback(+ "worker-message-error",+ new Error("Circuit field worker returned an unreadable message"),+ "message",+ );+ });+ worker.postMessage({+ type: "init",+ options: currentOptions,+ });+ } catch (error) {+ signalFallback("worker-unavailable", error, "startup");+ }+ return readyState.promise;+ }++ async function ensureThrough(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const target = Math.max(0, Number(worldY) || 0);+ if (lastStats.initialPublished && lastStats.generatedThrough >= target) {+ return Object.freeze({+ target,+ generatedThrough: lastStats.generatedThrough,+ stats: lastStats,+ });+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingEnsures.set(requestId, request);+ setState("generating");+ try {+ worker.postMessage({ type: "ensure", requestId, target });+ } catch (error) {+ signalFallback("worker-message-error", error, "ensure");+ }+ return request.promise;+ }++ async function pruneBefore(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingPrunes.set(requestId, request);+ try {+ worker.postMessage({+ type: "prune",+ requestId,+ worldY: Number(worldY) || 0,+ });+ } catch (error) {+ signalFallback("worker-message-error", error, "prune");+ }+ return request.promise;+ }++ function onAppend(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ appendCallbacks.add(callback);+ return () => appendCallbacks.delete(callback);+ }++ function onFallback(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ fallbackCallbacks.add(callback);+ if (fallbackReason) {+ const reason = fallbackReason;+ const epoch = workerEpoch;+ queueMicrotask(() => {+ if (+ destroyed+ || epoch !== workerEpoch+ || fallbackReason !== reason+ || !fallbackCallbacks.has(callback)+ ) return;+ notify([callback], reason, api);+ });+ }+ return () => fallbackCallbacks.delete(callback);+ }++ function onStatus(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ statusCallbacks.add(callback);+ return () => statusCallbacks.delete(callback);+ }++ function reset(nextOptions = {}) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const resetError = abortError("Circuit field worker was reset");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(resetError);+ }+ rejectPending(resetError);+ retained.length = 0;+ lastStats = EMPTY_STATS;+ currentOptions = { ...currentOptions, ...nextOptions };+ return startWorker();+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ const destroyedError = abortError("Circuit field worker was destroyed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(destroyedError);+ }+ rejectPending(destroyedError);+ appendCallbacks.clear();+ fallbackCallbacks.clear();+ statusCallbacks.clear();+ retained.length = 0;+ state = "destroyed";+ }++ const api = {+ ensureThrough,+ onAppend,+ onFallback,+ onStatus,+ pruneBefore,+ reset,+ destroy,+ get ready() { return readyState.promise; },+ get status() { return state; },+ get fallbackReason() { return fallbackReason; },+ get width() { return lastStats.width; },+ get height() { return lastStats.generatedThrough; },+ get generatedThrough() { return lastStats.generatedThrough; },+ get frontier() { return lastStats.generatedThrough; },+ get traces() { return retained; },+ get retainedTraces() { return retained; },+ get stats() { return lastStats; },+ };++ startWorker();+ return api;+}+
src/circuit-field-hybrid-v8.jsadded+232@@ -0,0 +1,232 @@+import { generateCircuitField } from "./circuit-background-v4.js?geometry=1";+import { createStreamingCircuitField } from "./circuit-field-stream.js";++function finiteNumber(value, fallback) {+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+}++function traceBounds(points) {+ let minimum = Number.POSITIVE_INFINITY;+ let maximum = Number.NEGATIVE_INFINITY;+ for (const point of points) {+ minimum = Math.min(minimum, point[1]);+ maximum = Math.max(maximum, point[1]);+ }+ return [minimum, maximum];+}++function initialTraceAdapter(trace, index) {+ const [minY, maxY] = traceBounds(trace.points);+ return Object.freeze({+ ...trace,+ id: `initial:${index}`,+ chunkId: 0,+ ownerChunk: 0,+ minY,+ maxY,+ });+}++function continuationTraceAdapter(trace, translateY) {+ return Object.freeze({+ ...trace,+ id: `continuation:${trace.id}`,+ chunkId: trace.chunkId + 1,+ ownerChunk: trace.ownerChunk + 1,+ points: trace.points.map(([x, y]) => [x, y + translateY]),+ minY: trace.minY + translateY,+ maxY: trace.maxY + translateY,+ });+}++/**+ * Combines the canonical finite generator with one persistent continuation.+ *+ * The first ensure publishes the unchanged finite geometry through adapter+ * copies. Later batches come from one deterministic streaming field whose+ * fixed chunk height equals the finite page's normalized height.+ */+export function createHybridCircuitField(options = {}) {+ let config;+ let initialField;+ let initialBatch;+ let continuation;+ let unsubscribeContinuation;+ let continuationTranslateY;+ let generationTolerance;+ let retained;+ let callbacks;+ let initialPublished;+ let totalPruned;+ let destroyed = false;++ function assertLive() {+ if (destroyed) throw new Error("Hybrid circuit field has been destroyed");+ }++ function notify(batch) {+ for (const callback of callbacks) callback(batch, api);+ }++ function initialize(nextOptions) {+ unsubscribeContinuation?.();+ continuation?.destroy();++ config = { ...nextOptions };+ const requestedWidth = finiteNumber(config.width, 900);+ const requestedInitialPageHeight = finiteNumber(+ config.initialPageHeight,+ finiteNumber(config.height, 450),+ );+ initialField = generateCircuitField({+ ...config,+ width: requestedWidth,+ height: requestedInitialPageHeight,+ });+ const pitch = initialField.height / Math.max(1, initialField.rows - 1);+ const continuationRows = Math.max(1, initialField.rows - 1);+ continuationTranslateY = initialField.height - pitch;+ generationTolerance = Math.max(1e-9, pitch * 1e-7);+ initialBatch = Object.freeze(+ initialField.traces.map(initialTraceAdapter),+ );+ retained = [];+ initialPublished = false;+ totalPruned = 0;++ continuation = createStreamingCircuitField({+ ...config,+ width: requestedWidth,+ seed: `${config.seed ?? "nitrogen"}:continuation`,+ chunkRows: continuationRows,+ });+ unsubscribeContinuation = continuation.onAppend((traces) => {+ const batch = Object.freeze(+ traces.map((trace) => continuationTraceAdapter(trace, continuationTranslateY)),+ );+ retained.push(...batch);+ notify(batch);+ });+ }++ function publishInitial() {+ if (initialPublished) return [];+ initialPublished = true;+ retained.push(...initialBatch);+ notify(initialBatch);+ return initialBatch;+ }++ const api = {+ ensureThrough(worldY) {+ assertLive();+ const target = Math.max(0, finiteNumber(worldY, 0));+ const appended = [...publishInitial()];+ const continuationTarget = Math.max(0, target - initialField.height);+ const tolerantTarget = Math.max(0, continuationTarget - generationTolerance);+ if (tolerantTarget > continuation.generatedThrough) {+ const before = retained.length;+ continuation.ensureThrough(tolerantTarget);+ appended.push(...retained.slice(before));+ }+ return appended;+ },++ onAppend(callback) {+ assertLive();+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ callbacks.add(callback);+ return () => callbacks.delete(callback);+ },++ pruneBefore(worldY) {+ assertLive();+ const numericBoundary = Number(worldY);+ const boundary = Number.isNaN(numericBoundary) ? 0 : numericBoundary;+ const removed = [];+ let writeIndex = 0;+ for (const trace of retained) {+ if (trace.maxY < boundary) {+ removed.push(trace.id);+ continue;+ }+ retained[writeIndex] = trace;+ writeIndex += 1;+ }+ retained.length = writeIndex;+ continuation.pruneBefore(boundary - continuationTranslateY);+ totalPruned += removed.length;+ return removed;+ },++ reset(nextOptions = {}) {+ assertLive();+ initialize({ ...config, ...nextOptions });+ return api;+ },++ destroy() {+ if (destroyed) return;+ destroyed = true;+ unsubscribeContinuation?.();+ continuation?.destroy();+ callbacks.clear();+ retained = [];+ },++ get width() {+ return initialField.width;+ },++ get height() {+ return initialField.height + continuation.generatedThrough;+ },++ get generatedThrough() {+ return initialField.height + continuation.generatedThrough;+ },++ get frontier() {+ return initialField.height + continuation.generatedThrough;+ },++ get traces() {+ return retained;+ },++ get retainedTraces() {+ return retained;+ },++ get initialField() {+ return initialField;+ },++ get stats() {+ const streamStats = continuation.stats;+ const initialTraceCount = initialField.traces.length;+ return Object.freeze({+ ...streamStats,+ chunks: streamStats.chunks + 1,+ columns: initialField.columns,+ chunkRows: initialField.rows - 1,+ pitch: initialField.height / Math.max(1, initialField.rows - 1),+ width: initialField.width,+ generatedThrough: initialField.height + continuation.generatedThrough,+ totalPublished: (initialPublished ? initialTraceCount : 0)+ + streamStats.totalPublished,+ retainedTraces: retained.length,+ totalPruned,+ initialPublished,+ initialPageHeight: initialField.height,+ initialPageRows: initialField.rows,+ initialPageTraceCount: initialTraceCount,+ });+ },+ };++ callbacks = new Set();+ initialize(options);+ return api;+}
src/circuit-field-hybrid-v9.jsadded+232@@ -0,0 +1,232 @@+import { generateCircuitField } from "./circuit-geometry-v9.js?geometry=1";+import { createStreamingCircuitField } from "./circuit-field-stream.js";++function finiteNumber(value, fallback) {+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+}++function traceBounds(points) {+ let minimum = Number.POSITIVE_INFINITY;+ let maximum = Number.NEGATIVE_INFINITY;+ for (const point of points) {+ minimum = Math.min(minimum, point[1]);+ maximum = Math.max(maximum, point[1]);+ }+ return [minimum, maximum];+}++function initialTraceAdapter(trace, index) {+ const [minY, maxY] = traceBounds(trace.points);+ return Object.freeze({+ ...trace,+ id: `initial:${index}`,+ chunkId: 0,+ ownerChunk: 0,+ minY,+ maxY,+ });+}++function continuationTraceAdapter(trace, translateY) {+ return Object.freeze({+ ...trace,+ id: `continuation:${trace.id}`,+ chunkId: trace.chunkId + 1,+ ownerChunk: trace.ownerChunk + 1,+ points: trace.points.map(([x, y]) => [x, y + translateY]),+ minY: trace.minY + translateY,+ maxY: trace.maxY + translateY,+ });+}++/**+ * Combines the canonical finite generator with one persistent continuation.+ *+ * The first ensure publishes the unchanged finite geometry through adapter+ * copies. Later batches come from one deterministic streaming field whose+ * fixed chunk height equals the finite page's normalized height.+ */+export function createHybridCircuitField(options = {}) {+ let config;+ let initialField;+ let initialBatch;+ let continuation;+ let unsubscribeContinuation;+ let continuationTranslateY;+ let generationTolerance;+ let retained;+ let callbacks;+ let initialPublished;+ let totalPruned;+ let destroyed = false;++ function assertLive() {+ if (destroyed) throw new Error("Hybrid circuit field has been destroyed");+ }++ function notify(batch) {+ for (const callback of callbacks) callback(batch, api);+ }++ function initialize(nextOptions) {+ unsubscribeContinuation?.();+ continuation?.destroy();++ config = { ...nextOptions };+ const requestedWidth = finiteNumber(config.width, 900);+ const requestedInitialPageHeight = finiteNumber(+ config.initialPageHeight,+ finiteNumber(config.height, 450),+ );+ initialField = generateCircuitField({+ ...config,+ width: requestedWidth,+ height: requestedInitialPageHeight,+ });+ const pitch = initialField.height / Math.max(1, initialField.rows - 1);+ const continuationRows = Math.max(1, initialField.rows - 1);+ continuationTranslateY = initialField.height - pitch;+ generationTolerance = Math.max(1e-9, pitch * 1e-7);+ initialBatch = Object.freeze(+ initialField.traces.map(initialTraceAdapter),+ );+ retained = [];+ initialPublished = false;+ totalPruned = 0;++ continuation = createStreamingCircuitField({+ ...config,+ width: requestedWidth,+ seed: `${config.seed ?? "nitrogen"}:continuation`,+ chunkRows: continuationRows,+ });+ unsubscribeContinuation = continuation.onAppend((traces) => {+ const batch = Object.freeze(+ traces.map((trace) => continuationTraceAdapter(trace, continuationTranslateY)),+ );+ retained.push(...batch);+ notify(batch);+ });+ }++ function publishInitial() {+ if (initialPublished) return [];+ initialPublished = true;+ retained.push(...initialBatch);+ notify(initialBatch);+ return initialBatch;+ }++ const api = {+ ensureThrough(worldY) {+ assertLive();+ const target = Math.max(0, finiteNumber(worldY, 0));+ const appended = [...publishInitial()];+ const continuationTarget = Math.max(0, target - initialField.height);+ const tolerantTarget = Math.max(0, continuationTarget - generationTolerance);+ if (tolerantTarget > continuation.generatedThrough) {+ const before = retained.length;+ continuation.ensureThrough(tolerantTarget);+ appended.push(...retained.slice(before));+ }+ return appended;+ },++ onAppend(callback) {+ assertLive();+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ callbacks.add(callback);+ return () => callbacks.delete(callback);+ },++ pruneBefore(worldY) {+ assertLive();+ const numericBoundary = Number(worldY);+ const boundary = Number.isNaN(numericBoundary) ? 0 : numericBoundary;+ const removed = [];+ let writeIndex = 0;+ for (const trace of retained) {+ if (trace.maxY < boundary) {+ removed.push(trace.id);+ continue;+ }+ retained[writeIndex] = trace;+ writeIndex += 1;+ }+ retained.length = writeIndex;+ continuation.pruneBefore(boundary - continuationTranslateY);+ totalPruned += removed.length;+ return removed;+ },++ reset(nextOptions = {}) {+ assertLive();+ initialize({ ...config, ...nextOptions });+ return api;+ },++ destroy() {+ if (destroyed) return;+ destroyed = true;+ unsubscribeContinuation?.();+ continuation?.destroy();+ callbacks.clear();+ retained = [];+ },++ get width() {+ return initialField.width;+ },++ get height() {+ return initialField.height + continuation.generatedThrough;+ },++ get generatedThrough() {+ return initialField.height + continuation.generatedThrough;+ },++ get frontier() {+ return initialField.height + continuation.generatedThrough;+ },++ get traces() {+ return retained;+ },++ get retainedTraces() {+ return retained;+ },++ get initialField() {+ return initialField;+ },++ get stats() {+ const streamStats = continuation.stats;+ const initialTraceCount = initialField.traces.length;+ return Object.freeze({+ ...streamStats,+ chunks: streamStats.chunks + 1,+ columns: initialField.columns,+ chunkRows: initialField.rows - 1,+ pitch: initialField.height / Math.max(1, initialField.rows - 1),+ width: initialField.width,+ generatedThrough: initialField.height + continuation.generatedThrough,+ totalPublished: (initialPublished ? initialTraceCount : 0)+ + streamStats.totalPublished,+ retainedTraces: retained.length,+ totalPruned,+ initialPublished,+ initialPageHeight: initialField.height,+ initialPageRows: initialField.rows,+ initialPageTraceCount: initialTraceCount,+ });+ },+ };++ callbacks = new Set();+ initialize(options);+ return api;+}
src/circuit-field-hybrid-worker-v8.jsadded+191@@ -0,0 +1,191 @@+import { createHybridCircuitField } from "./circuit-field-hybrid-v8.js";++const scope = globalThis;+const pendingEnsures = [];+const pumpChannel = new MessageChannel();+const retainedTraceMeta = new Map();+const APPEND_SLICE_SIZE = 256;++let field;+let unsubscribe;+let initialized = false;+let pumpScheduled = false;+let highestTarget = 0;+let publiclyPruned = 0;+let fatal = false;++function serializeError(error) {+ return {+ name: error?.name || "Error",+ message: error?.message || String(error),+ stack: error?.stack || "",+ };+}++function post(type, payload = {}) {+ scope.postMessage({ type, ...payload });+}++function publicStats() {+ return {+ ...field.stats,+ retainedTraces: retainedTraceMeta.size,+ totalPruned: publiclyPruned,+ };+}++function postFatal(error, phase) {+ if (fatal) return;+ fatal = true;+ pumpScheduled = false;+ post("fatal", {+ phase,+ error: serializeError(error),+ });+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+}++function settleEnsures() {+ if (!field) return;+ const frontier = field.generatedThrough;+ let writeIndex = 0;+ highestTarget = 0;++ for (let index = 0; index < pendingEnsures.length; index += 1) {+ const request = pendingEnsures[index];+ if (request.target <= frontier) {+ post("ensured", {+ requestId: request.requestId,+ target: request.target,+ generatedThrough: frontier,+ stats: publicStats(),+ });+ continue;+ }+ pendingEnsures[writeIndex] = request;+ writeIndex += 1;+ highestTarget = Math.max(highestTarget, request.target);+ }+ pendingEnsures.length = writeIndex;+}++function schedulePump() {+ if (+ pumpScheduled+ || fatal+ || !field+ || field.generatedThrough >= highestTarget+ ) return;+ pumpScheduled = true;+ pumpChannel.port2.postMessage(0);+}++function pumpOneChunk() {+ pumpScheduled = false;+ if (fatal || !field) return;++ try {+ settleEnsures();+ if (field.generatedThrough >= highestTarget) return;++ const stats = field.stats;+ const nextChunkBoundary = (+ field.generatedThrough+ + stats.chunkRows * stats.pitch+ );+ field.ensureThrough(nextChunkBoundary);+ settleEnsures();+ schedulePump();+ } catch (error) {+ postFatal(error, "generation");+ }+}++pumpChannel.port1.onmessage = pumpOneChunk;++function initialize(message) {+ if (initialized) throw new Error("Worker has already been initialized");+ initialized = true;+ field = createHybridCircuitField(message.options || {});+ unsubscribe = field.onAppend((traces) => {+ for (let offset = 0; offset < traces.length; offset += APPEND_SLICE_SIZE) {+ const slice = traces.slice(offset, offset + APPEND_SLICE_SIZE);+ for (const trace of slice) retainedTraceMeta.set(trace.id, trace.maxY);+ post("append", {+ traces: slice,+ generatedThrough: field.generatedThrough,+ stats: publicStats(),+ });+ }+ // postMessage has already cloned the batch. Keep only the routing+ // occupancy and lightweight pruning metadata in this thread.+ field.pruneBefore(Number.POSITIVE_INFINITY);+ });+ post("ready", {+ stats: publicStats(),+ width: field.width,+ generatedThrough: field.generatedThrough,+ });+}++function ensureThrough(message) {+ if (!field) throw new Error("Worker is not initialized");+ const target = Math.max(0, Number(message.target) || 0);+ if (!field.stats.initialPublished) {+ field.ensureThrough(Math.min(target, field.generatedThrough));+ }+ pendingEnsures.push({+ requestId: message.requestId,+ target,+ });+ highestTarget = Math.max(highestTarget, target);+ settleEnsures();+ schedulePump();+}++function pruneBefore(message) {+ if (!field) throw new Error("Worker is not initialized");+ const boundary = Number(message.worldY) || 0;+ const removedIds = [];+ for (const [id, maxY] of retainedTraceMeta) {+ if (maxY >= boundary) continue;+ removedIds.push(id);+ retainedTraceMeta.delete(id);+ }+ publiclyPruned += removedIds.length;+ post("pruned", {+ requestId: message.requestId,+ removedIds,+ stats: publicStats(),+ });+}++function destroy() {+ fatal = true;+ pumpScheduled = false;+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+ pumpChannel.port1.close();+ pumpChannel.port2.close();+ scope.close?.();+}++scope.onmessage = (event) => {+ if (fatal) return;+ const message = event.data || {};+ try {+ if (message.type === "init") initialize(message);+ else if (message.type === "ensure") ensureThrough(message);+ else if (message.type === "prune") pruneBefore(message);+ else if (message.type === "destroy") destroy();+ else throw new Error(`Unknown worker message: ${String(message.type)}`);+ } catch (error) {+ postFatal(error, message.type || "message");+ }+};+
src/circuit-field-hybrid-worker-v9.jsadded+191@@ -0,0 +1,191 @@+import { createHybridCircuitField } from "./circuit-field-hybrid-v9.js";++const scope = globalThis;+const pendingEnsures = [];+const pumpChannel = new MessageChannel();+const retainedTraceMeta = new Map();+const APPEND_SLICE_SIZE = 256;++let field;+let unsubscribe;+let initialized = false;+let pumpScheduled = false;+let highestTarget = 0;+let publiclyPruned = 0;+let fatal = false;++function serializeError(error) {+ return {+ name: error?.name || "Error",+ message: error?.message || String(error),+ stack: error?.stack || "",+ };+}++function post(type, payload = {}) {+ scope.postMessage({ type, ...payload });+}++function publicStats() {+ return {+ ...field.stats,+ retainedTraces: retainedTraceMeta.size,+ totalPruned: publiclyPruned,+ };+}++function postFatal(error, phase) {+ if (fatal) return;+ fatal = true;+ pumpScheduled = false;+ post("fatal", {+ phase,+ error: serializeError(error),+ });+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+}++function settleEnsures() {+ if (!field) return;+ const frontier = field.generatedThrough;+ let writeIndex = 0;+ highestTarget = 0;++ for (let index = 0; index < pendingEnsures.length; index += 1) {+ const request = pendingEnsures[index];+ if (request.target <= frontier) {+ post("ensured", {+ requestId: request.requestId,+ target: request.target,+ generatedThrough: frontier,+ stats: publicStats(),+ });+ continue;+ }+ pendingEnsures[writeIndex] = request;+ writeIndex += 1;+ highestTarget = Math.max(highestTarget, request.target);+ }+ pendingEnsures.length = writeIndex;+}++function schedulePump() {+ if (+ pumpScheduled+ || fatal+ || !field+ || field.generatedThrough >= highestTarget+ ) return;+ pumpScheduled = true;+ pumpChannel.port2.postMessage(0);+}++function pumpOneChunk() {+ pumpScheduled = false;+ if (fatal || !field) return;++ try {+ settleEnsures();+ if (field.generatedThrough >= highestTarget) return;++ const stats = field.stats;+ const nextChunkBoundary = (+ field.generatedThrough+ + stats.chunkRows * stats.pitch+ );+ field.ensureThrough(nextChunkBoundary);+ settleEnsures();+ schedulePump();+ } catch (error) {+ postFatal(error, "generation");+ }+}++pumpChannel.port1.onmessage = pumpOneChunk;++function initialize(message) {+ if (initialized) throw new Error("Worker has already been initialized");+ initialized = true;+ field = createHybridCircuitField(message.options || {});+ unsubscribe = field.onAppend((traces) => {+ for (let offset = 0; offset < traces.length; offset += APPEND_SLICE_SIZE) {+ const slice = traces.slice(offset, offset + APPEND_SLICE_SIZE);+ for (const trace of slice) retainedTraceMeta.set(trace.id, trace.maxY);+ post("append", {+ traces: slice,+ generatedThrough: field.generatedThrough,+ stats: publicStats(),+ });+ }+ // postMessage has already cloned the batch. Keep only the routing+ // occupancy and lightweight pruning metadata in this thread.+ field.pruneBefore(Number.POSITIVE_INFINITY);+ });+ post("ready", {+ stats: publicStats(),+ width: field.width,+ generatedThrough: field.generatedThrough,+ });+}++function ensureThrough(message) {+ if (!field) throw new Error("Worker is not initialized");+ const target = Math.max(0, Number(message.target) || 0);+ if (!field.stats.initialPublished) {+ field.ensureThrough(Math.min(target, field.generatedThrough));+ }+ pendingEnsures.push({+ requestId: message.requestId,+ target,+ });+ highestTarget = Math.max(highestTarget, target);+ settleEnsures();+ schedulePump();+}++function pruneBefore(message) {+ if (!field) throw new Error("Worker is not initialized");+ const boundary = Number(message.worldY) || 0;+ const removedIds = [];+ for (const [id, maxY] of retainedTraceMeta) {+ if (maxY >= boundary) continue;+ removedIds.push(id);+ retainedTraceMeta.delete(id);+ }+ publiclyPruned += removedIds.length;+ post("pruned", {+ requestId: message.requestId,+ removedIds,+ stats: publicStats(),+ });+}++function destroy() {+ fatal = true;+ pumpScheduled = false;+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+ pumpChannel.port1.close();+ pumpChannel.port2.close();+ scope.close?.();+}++scope.onmessage = (event) => {+ if (fatal) return;+ const message = event.data || {};+ try {+ if (message.type === "init") initialize(message);+ else if (message.type === "ensure") ensureThrough(message);+ else if (message.type === "prune") pruneBefore(message);+ else if (message.type === "destroy") destroy();+ else throw new Error(`Unknown worker message: ${String(message.type)}`);+ } catch (error) {+ postFatal(error, message.type || "message");+ }+};+
src/circuit-field-stream-client.jsadded+418@@ -0,0 +1,418 @@+const EMPTY_STATS = Object.freeze({+ chunks: 0,+ columns: 0,+ chunkRows: 0,+ pitch: 0,+ width: 0,+ generatedThrough: 0,+ occupiedCells: 0,+ occupancyFill: 0,+ occupiedCellsRetained: 0,+ occupiedCellsPruned: 0,+ occupancyRowsRetained: 0,+ occupancyRowsPruned: 0,+ flowVorticesRetained: 0,+ flowVorticesPruned: 0,+ generationCacheMinimumRow: 1,+ totalPublished: 0,+ retainedTraces: 0,+ totalPruned: 0,+ rejectedRoutes: 0,+ routeGuardRows: 0,+ occupancyRetainedForSafety: true,+});++function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });+ promise.catch(() => {});+ return {+ promise,+ resolve,+ reject,+ settled: false,+ };+}++function abortError(message) {+ if (typeof DOMException === "function") {+ return new DOMException(message, "AbortError");+ }+ const error = new Error(message);+ error.name = "AbortError";+ return error;+}++function errorFromPayload(payload, fallbackMessage) {+ const error = new Error(payload?.message || fallbackMessage);+ error.name = payload?.name || "Error";+ if (payload?.stack) error.stack = payload.stack;+ return error;+}++function immutableStats(stats) {+ return Object.freeze({ ...EMPTY_STATS, ...(stats || {}) });+}++function immutableTrace(trace) {+ return Object.freeze(trace);+}++function notify(callbacks, value, api) {+ for (const callback of callbacks) {+ try {+ callback(value, api);+ } catch (error) {+ console.error("Circuit field worker callback failed", error);+ }+ }+}++/**+ * Main-thread client for circuit-field-stream-worker.js.+ *+ * The returned facade is available immediately. Await `ready` before reading+ * normalized dimensions. `ensureThrough()` resolves after all append callbacks+ * for its requested frontier have run.+ */+export function createStreamingCircuitFieldWorker(options = {}, clientOptions = {}) {+ const appendCallbacks = new Set();+ const fallbackCallbacks = new Set();+ const statusCallbacks = new Set();+ const pendingEnsures = new Map();+ const pendingPrunes = new Map();+ const retained = [];++ let currentOptions = { ...options };+ let worker;+ let workerEpoch = 0;+ let requestSequence = 0;+ let readyState;+ let lastStats = EMPTY_STATS;+ let fallbackReason = null;+ let state = "starting";+ let destroyed = false;++ const workerUrl = clientOptions.workerUrl+ || new URL("./circuit-field-stream-worker.js", import.meta.url);+ const workerName = clientOptions.name || "circuit-field-stream";++ function setState(nextState) {+ if (state === nextState) return;+ state = nextState;+ queueMicrotask(() => notify(statusCallbacks, nextState, api));+ }++ function rejectPending(error) {+ for (const request of pendingEnsures.values()) request.reject(error);+ for (const request of pendingPrunes.values()) request.reject(error);+ pendingEnsures.clear();+ pendingPrunes.clear();+ }++ function terminateWorker() {+ if (!worker) return;+ const target = worker;+ worker = undefined;+ try {+ target.postMessage({ type: "destroy" });+ } catch {+ // The worker may already have stopped.+ }+ target.terminate();+ }++ function signalFallback(kind, error, phase = "startup") {+ if (destroyed || state === "failed") return;+ const normalizedError = error instanceof Error+ ? error+ : errorFromPayload(error, "Circuit field worker failed");+ fallbackReason = Object.freeze({+ kind,+ phase,+ error: normalizedError,+ options: Object.freeze({ ...currentOptions }),+ synchronousFallbackAvailable: true,+ });+ setState("failed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(normalizedError);+ }+ rejectPending(normalizedError);+ notify(fallbackCallbacks, fallbackReason, api);+ }++ function createWorkerInstance() {+ if (typeof clientOptions.workerFactory === "function") {+ return clientOptions.workerFactory(workerUrl, {+ type: "module",+ name: workerName,+ });+ }+ if (typeof Worker !== "function") {+ throw new Error("Web Workers are unavailable");+ }+ return new Worker(workerUrl, {+ type: "module",+ name: workerName,+ });+ }++ function handleAppend(message) {+ lastStats = immutableStats(message.stats);+ const batch = Object.freeze(+ (message.traces || []).map(immutableTrace),+ );+ retained.push(...batch);+ notify(appendCallbacks, batch, api);+ }++ function handleEnsured(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingEnsures.get(message.requestId);+ if (!request) return;+ pendingEnsures.delete(message.requestId);+ request.resolve(Object.freeze({+ target: message.target,+ generatedThrough: message.generatedThrough,+ stats: lastStats,+ }));+ if (!pendingEnsures.size) setState("ready");+ }++ function handlePruned(message) {+ lastStats = immutableStats(message.stats);+ const request = pendingPrunes.get(message.requestId);+ if (!request) return;+ pendingPrunes.delete(message.requestId);+ const removedIds = Object.freeze((message.removedIds || []).slice());+ if (removedIds.length) {+ const removed = new Set(removedIds);+ let writeIndex = 0;+ for (const trace of retained) {+ if (removed.has(trace.id)) continue;+ retained[writeIndex] = trace;+ writeIndex += 1;+ }+ retained.length = writeIndex;+ }+ request.resolve(removedIds);+ }++ function handleMessage(event, epoch) {+ if (destroyed || epoch !== workerEpoch) return;+ const message = event.data || {};+ if (message.type === "ready") {+ lastStats = immutableStats(message.stats);+ setState("ready");+ if (!readyState.settled) {+ readyState.settled = true;+ readyState.resolve(api);+ }+ } else if (message.type === "append") {+ handleAppend(message);+ } else if (message.type === "ensured") {+ handleEnsured(message);+ } else if (message.type === "pruned") {+ handlePruned(message);+ } else if (message.type === "fatal") {+ signalFallback(+ "worker-runtime-error",+ errorFromPayload(message.error, "Circuit field worker failed"),+ message.phase,+ );+ } else {+ signalFallback(+ "worker-protocol-error",+ new Error(`Unknown worker response: ${String(message.type)}`),+ "message",+ );+ }+ }++ function startWorker() {+ workerEpoch += 1;+ const epoch = workerEpoch;+ readyState = deferred();+ fallbackReason = null;+ setState("starting");++ try {+ worker = createWorkerInstance();+ worker.addEventListener("message", (event) => handleMessage(event, epoch));+ worker.addEventListener("error", (event) => {+ if (epoch !== workerEpoch || destroyed) return;+ event.preventDefault?.();+ signalFallback(+ "worker-runtime-error",+ event.error || new Error(event.message || "Circuit field worker crashed"),+ "runtime",+ );+ });+ worker.addEventListener("messageerror", () => {+ if (epoch !== workerEpoch || destroyed) return;+ signalFallback(+ "worker-message-error",+ new Error("Circuit field worker returned an unreadable message"),+ "message",+ );+ });+ worker.postMessage({+ type: "init",+ options: currentOptions,+ });+ } catch (error) {+ signalFallback("worker-unavailable", error, "startup");+ }+ return readyState.promise;+ }++ async function ensureThrough(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const target = Math.max(0, Number(worldY) || 0);+ if (lastStats.generatedThrough >= target) {+ return Object.freeze({+ target,+ generatedThrough: lastStats.generatedThrough,+ stats: lastStats,+ });+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingEnsures.set(requestId, request);+ setState("generating");+ try {+ worker.postMessage({ type: "ensure", requestId, target });+ } catch (error) {+ signalFallback("worker-message-error", error, "ensure");+ }+ return request.promise;+ }++ async function pruneBefore(worldY) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const epoch = workerEpoch;+ await readyState.promise;+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ if (epoch !== workerEpoch) throw abortError("Circuit field worker was reset");+ if (state === "failed" || !worker) {+ throw fallbackReason?.error || new Error("Circuit field worker is unavailable");+ }++ const requestId = ++requestSequence;+ const request = deferred();+ pendingPrunes.set(requestId, request);+ try {+ worker.postMessage({+ type: "prune",+ requestId,+ worldY: Number(worldY) || 0,+ });+ } catch (error) {+ signalFallback("worker-message-error", error, "prune");+ }+ return request.promise;+ }++ function onAppend(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ appendCallbacks.add(callback);+ return () => appendCallbacks.delete(callback);+ }++ function onFallback(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ fallbackCallbacks.add(callback);+ if (fallbackReason) {+ const reason = fallbackReason;+ const epoch = workerEpoch;+ queueMicrotask(() => {+ if (+ destroyed+ || epoch !== workerEpoch+ || fallbackReason !== reason+ || !fallbackCallbacks.has(callback)+ ) return;+ notify([callback], reason, api);+ });+ }+ return () => fallbackCallbacks.delete(callback);+ }++ function onStatus(callback) {+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ statusCallbacks.add(callback);+ return () => statusCallbacks.delete(callback);+ }++ function reset(nextOptions = {}) {+ if (destroyed) throw new Error("Streaming circuit field worker has been destroyed");+ const resetError = abortError("Circuit field worker was reset");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(resetError);+ }+ rejectPending(resetError);+ retained.length = 0;+ lastStats = EMPTY_STATS;+ currentOptions = { ...currentOptions, ...nextOptions };+ return startWorker();+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ const destroyedError = abortError("Circuit field worker was destroyed");+ terminateWorker();+ if (readyState && !readyState.settled) {+ readyState.settled = true;+ readyState.reject(destroyedError);+ }+ rejectPending(destroyedError);+ appendCallbacks.clear();+ fallbackCallbacks.clear();+ statusCallbacks.clear();+ retained.length = 0;+ state = "destroyed";+ }++ const api = {+ ensureThrough,+ onAppend,+ onFallback,+ onStatus,+ pruneBefore,+ reset,+ destroy,+ get ready() { return readyState.promise; },+ get status() { return state; },+ get fallbackReason() { return fallbackReason; },+ get width() { return lastStats.width; },+ get height() { return lastStats.generatedThrough; },+ get generatedThrough() { return lastStats.generatedThrough; },+ get frontier() { return lastStats.generatedThrough; },+ get traces() { return retained; },+ get retainedTraces() { return retained; },+ get stats() { return lastStats; },+ };++ startWorker();+ return api;+}+
src/circuit-field-stream-worker.jsadded+185@@ -0,0 +1,185 @@+import { createStreamingCircuitField } from "./circuit-field-stream.js";++const scope = globalThis;+const pendingEnsures = [];+const pumpChannel = new MessageChannel();+const retainedTraceMeta = new Map();++let field;+let unsubscribe;+let initialized = false;+let pumpScheduled = false;+let highestTarget = 0;+let publiclyPruned = 0;+let fatal = false;++function serializeError(error) {+ return {+ name: error?.name || "Error",+ message: error?.message || String(error),+ stack: error?.stack || "",+ };+}++function post(type, payload = {}) {+ scope.postMessage({ type, ...payload });+}++function publicStats() {+ return {+ ...field.stats,+ retainedTraces: retainedTraceMeta.size,+ totalPruned: publiclyPruned,+ };+}++function postFatal(error, phase) {+ if (fatal) return;+ fatal = true;+ pumpScheduled = false;+ post("fatal", {+ phase,+ error: serializeError(error),+ });+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+}++function settleEnsures() {+ if (!field) return;+ const frontier = field.generatedThrough;+ let writeIndex = 0;+ highestTarget = 0;++ for (let index = 0; index < pendingEnsures.length; index += 1) {+ const request = pendingEnsures[index];+ if (request.target <= frontier) {+ post("ensured", {+ requestId: request.requestId,+ target: request.target,+ generatedThrough: frontier,+ stats: publicStats(),+ });+ continue;+ }+ pendingEnsures[writeIndex] = request;+ writeIndex += 1;+ highestTarget = Math.max(highestTarget, request.target);+ }+ pendingEnsures.length = writeIndex;+}++function schedulePump() {+ if (+ pumpScheduled+ || fatal+ || !field+ || field.generatedThrough >= highestTarget+ ) return;+ pumpScheduled = true;+ pumpChannel.port2.postMessage(0);+}++function pumpOneChunk() {+ pumpScheduled = false;+ if (fatal || !field) return;++ try {+ settleEnsures();+ if (field.generatedThrough >= highestTarget) return;++ const stats = field.stats;+ const nextChunkBoundary = (+ (stats.chunks + 1)+ * stats.chunkRows+ * stats.pitch+ );+ field.ensureThrough(nextChunkBoundary);+ settleEnsures();+ schedulePump();+ } catch (error) {+ postFatal(error, "generation");+ }+}++pumpChannel.port1.onmessage = pumpOneChunk;++function initialize(message) {+ if (initialized) throw new Error("Worker has already been initialized");+ initialized = true;+ field = createStreamingCircuitField(message.options || {});+ unsubscribe = field.onAppend((traces) => {+ for (const trace of traces) retainedTraceMeta.set(trace.id, trace.maxY);+ post("append", {+ traces,+ generatedThrough: field.generatedThrough,+ stats: publicStats(),+ });+ // postMessage has already cloned the batch. Keep only the routing+ // occupancy and lightweight pruning metadata in this thread.+ field.pruneBefore(Number.POSITIVE_INFINITY);+ });+ post("ready", {+ stats: publicStats(),+ width: field.width,+ generatedThrough: field.generatedThrough,+ });+}++function ensureThrough(message) {+ if (!field) throw new Error("Worker is not initialized");+ const target = Math.max(0, Number(message.target) || 0);+ pendingEnsures.push({+ requestId: message.requestId,+ target,+ });+ highestTarget = Math.max(highestTarget, target);+ settleEnsures();+ schedulePump();+}++function pruneBefore(message) {+ if (!field) throw new Error("Worker is not initialized");+ const boundary = Number(message.worldY) || 0;+ const removedIds = [];+ for (const [id, maxY] of retainedTraceMeta) {+ if (maxY >= boundary) continue;+ removedIds.push(id);+ retainedTraceMeta.delete(id);+ }+ publiclyPruned += removedIds.length;+ post("pruned", {+ requestId: message.requestId,+ removedIds,+ stats: publicStats(),+ });+}++function destroy() {+ fatal = true;+ pumpScheduled = false;+ unsubscribe?.();+ field?.destroy();+ pendingEnsures.length = 0;+ retainedTraceMeta.clear();+ pumpChannel.port1.close();+ pumpChannel.port2.close();+ scope.close?.();+}++scope.onmessage = (event) => {+ if (fatal) return;+ const message = event.data || {};+ try {+ if (message.type === "init") initialize(message);+ else if (message.type === "ensure") ensureThrough(message);+ else if (message.type === "prune") pruneBefore(message);+ else if (message.type === "destroy") destroy();+ else throw new Error(`Unknown worker message: ${String(message.type)}`);+ } catch (error) {+ postFatal(error, message.type || "message");+ }+};+
src/circuit-field-stream.jsadded+775@@ -0,0 +1,775 @@+const DEFAULTS = Object.freeze({+ seed: "nitrogen",+ width: 900,+ pitch: 7.895,+ featureScale: 1,+ chunkRows: 96,+ density: 1,+ fill: 0.668,+ routeLength: 0.78,+ horizontalFlow: 0.82,+ flowAngle: 0,+ swirl: 0.28,+ swirlScale: 0.8,+ diagonalFlow: 0.58,+ jogLength: 0.72,+ channelAttraction: 0.78,+ longFlow: 0.18,+ edgeDensity: 0.22,+ maxRouteBudget: 86,+ routeGuardRows: 0,+});++const DIRECTIONS = Object.freeze([[1, 0], [0, 1], [-1, 0], [0, -1]]);++function clamp(value, minimum, maximum) {+ return Math.max(minimum, Math.min(maximum, value));+}++function hashSeed(value) {+ let hash = 2166136261;+ for (const character of String(value)) {+ hash ^= character.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mix32(value) {+ value = Math.imul(value ^ (value >>> 16), 0x7feb352d);+ value = Math.imul(value ^ (value >>> 15), 0x846ca68b);+ return (value ^ (value >>> 16)) >>> 0;+}++function coordinateHash(seed, x, y, salt = 0) {+ let value = seed ^ Math.imul(x | 0, 0x9e3779b1);+ value ^= Math.imul(y | 0, 0x85ebca77);+ value ^= Math.imul(salt | 0, 0xc2b2ae3d);+ return mix32(value);+}++function unitHash(seed, x, y, salt = 0) {+ return coordinateHash(seed, x, y, salt) / 4294967296;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function integer(random, minimum, maximum) {+ if (maximum <= minimum) return minimum;+ return Math.floor(random() * (maximum - minimum + 1)) + minimum;+}++function weighted(random, entries) {+ let total = 0;+ for (const [, weight] of entries) total += weight;+ let roll = random() * total;+ for (const [value, weight] of entries) {+ roll -= weight;+ if (roll <= 0) return value;+ }+ return entries.at(-1)?.[0];+}++function shuffle(random, values) {+ for (let index = values.length - 1; index > 0; index -= 1) {+ const swapIndex = integer(random, 0, index);+ [values[index], values[swapIndex]] = [values[swapIndex], values[index]];+ }+ return values;+}++function diagonalness(vector) {+ return 1 - Math.abs(Math.abs(vector[0]) - Math.abs(vector[1]));+}++function closestDirection(vector) {+ let result = 0;+ let bestScore = -Infinity;+ for (let index = 0; index < DIRECTIONS.length; index += 1) {+ const score = DIRECTIONS[index][0] * vector[0] + DIRECTIONS[index][1] * vector[1];+ if (score > bestScore) {+ bestScore = score;+ result = index;+ }+ }+ return result;+}++function simplify(path) {+ if (path.length < 3) return path.slice();+ const result = [path[0]];+ for (let index = 1; index < path.length - 1; index += 1) {+ const previous = result.at(-1);+ const current = path[index];+ const next = path[index + 1];+ const ax = Math.sign(current[0] - previous[0]);+ const ay = Math.sign(current[1] - previous[1]);+ const bx = Math.sign(next[0] - current[0]);+ const by = Math.sign(next[1] - current[1]);+ if (ax !== bx || ay !== by) result.push(current);+ }+ result.push(path.at(-1));+ return result;+}++function chamfer(path) {+ if (path.length < 3) return path.slice();+ const result = [path[0]];+ for (let index = 1; index < path.length - 1; index += 1) {+ const previous = path[index - 1];+ const current = path[index];+ const next = path[index + 1];+ const ax = current[0] - previous[0];+ const ay = current[1] - previous[1];+ const bx = next[0] - current[0];+ const by = next[1] - current[1];+ const incomingLength = Math.hypot(ax, ay);+ const outgoingLength = Math.hypot(bx, by);+ if (ax * bx + ay * by !== 0 || (ax === bx && ay === by)) {+ result.push(current);+ continue;+ }+ const inset = Math.min(0.38, incomingLength * 0.38, outgoingLength * 0.38);+ result.push(+ [current[0] - ax / incomingLength * inset, current[1] - ay / incomingLength * inset],+ [current[0] + bx / outgoingLength * inset, current[1] + by / outgoingLength * inset],+ );+ }+ result.push(path.at(-1));+ return result;+}++function pathLength(points) {+ let length = 0;+ for (let index = 1; index < points.length; index += 1) {+ length += Math.hypot(+ points[index][0] - points[index - 1][0],+ points[index][1] - points[index - 1][1],+ );+ }+ return length;+}++function normalizeOptions(options) {+ const config = { ...DEFAULTS, ...options };+ const featureScale = Math.max(0.25, Number(config.featureScale) || 1);+ const pitch = Math.max(1, Number(config.pitch) * featureScale || DEFAULTS.pitch);+ const requestedWidth = Math.max(240, Number(config.width) || DEFAULTS.width);+ const columns = Math.max(30, Math.floor(requestedWidth / pitch));+ const chunkRows = Math.max(24, Math.round(Number(config.chunkRows) || DEFAULTS.chunkRows));+ const maxRouteBudget = Math.max(+ 12,+ Math.round((Number(config.maxRouteBudget) || DEFAULTS.maxRouteBudget)+ * clamp(Number(config.routeLength) || DEFAULTS.routeLength, 0.2, 2)),+ );+ const routeGuardRows = Math.max(+ maxRouteBudget + 8,+ Math.round(Number(config.routeGuardRows) || 0),+ );+ return {+ ...config,+ width: (columns - 1) * pitch,+ pitch,+ columns,+ chunkRows,+ maxRouteBudget,+ routeGuardRows,+ fill: clamp(Number(config.fill) || DEFAULTS.fill, 0.05, 0.9),+ density: clamp(Number(config.density) || DEFAULTS.density, 0.05, 1.5),+ horizontalFlow: clamp(Number(config.horizontalFlow) || 0, 0, 1),+ swirl: clamp(Number(config.swirl) || 0, 0, 1.5),+ swirlScale: clamp(Number(config.swirlScale) || DEFAULTS.swirlScale, 0.2, 3),+ diagonalFlow: clamp(Number(config.diagonalFlow) || 0, 0, 1),+ jogLength: clamp(Number(config.jogLength) || 0, 0.15, 1.5),+ channelAttraction: clamp(Number(config.channelAttraction) || 0, 0, 2),+ longFlow: clamp(Number(config.longFlow) || 0, 0, 1),+ edgeDensity: clamp(Number(config.edgeDensity) || 0, 0, 1),+ flowAngle: Number(config.flowAngle) || 0,+ };+}++/**+ * Creates a deterministic, append-only field of non-crossing circuit traces.+ * Geometry uses absolute world coordinates. ensureThrough() is synchronous and+ * always processes the same fixed-height chunks, regardless of call cadence.+ */+export function createStreamingCircuitField(options = {}) {+ let config;+ let seedHash;+ let occupied;+ let rowOccupancy;+ let flowVortexCache;+ let retained;+ let callbacks;+ let nextChunkId;+ let nextTraceSequence;+ let generatedThroughRow;+ let totalPublished;+ let totalPruned;+ let totalOccupiedCells;+ let prunedOccupiedCells;+ let prunedOccupancyRows;+ let prunedFlowVortices;+ let generationCacheMinimumRow;+ let rejectedRoutes;+ let destroyed = false;++ function initialize(nextOptions) {+ config = normalizeOptions(nextOptions);+ seedHash = hashSeed(config.seed);+ occupied = new Set();+ rowOccupancy = new Map();+ flowVortexCache = new Map();+ retained = [];+ callbacks = callbacks || new Set();+ nextChunkId = 0;+ nextTraceSequence = 0;+ generatedThroughRow = 0;+ totalPublished = 0;+ totalPruned = 0;+ totalOccupiedCells = 0;+ prunedOccupiedCells = 0;+ prunedOccupancyRows = 0;+ prunedFlowVortices = 0;+ generationCacheMinimumRow = 1;+ rejectedRoutes = 0;+ }++ function assertLive() {+ if (destroyed) throw new Error("Streaming circuit field has been destroyed");+ }++ function cellKey(x, y) {+ return y * config.columns + x;+ }++ function isBlocked(x, y) {+ return occupied.has(cellKey(x, y));+ }++ function flowVortex(latticeX, latticeY, spacing) {+ const key = latticeX + "," + latticeY;+ let vortex = flowVortexCache.get(key);+ if (vortex) return vortex;+ vortex = {+ x: (latticeX + 0.15 + unitHash(seedHash, latticeX, latticeY, 1) * 0.7) * spacing,+ y: (latticeY + 0.15 + unitHash(seedHash, latticeX, latticeY, 2) * 0.7) * spacing,+ radius: spacing * (0.7 + unitHash(seedHash, latticeX, latticeY, 3) * 0.55),+ spin: unitHash(seedHash, latticeX, latticeY, 4) < 0.5 ? -1 : 1,+ strength: 0.72 + unitHash(seedHash, latticeX, latticeY, 5) * 0.56,+ };+ flowVortexCache.set(key, vortex);+ return vortex;+ }++ function flowVector(x, y, angleDegrees) {+ const radians = angleDegrees * Math.PI / 180;+ let vx = Math.cos(radians);+ let vy = Math.sin(radians);+ const spacing = Math.max(24, Math.round(72 * config.swirlScale));+ const gridX = Math.floor(x / spacing);+ const gridY = Math.floor(y / spacing);++ // A hashed lattice gives the infinite field stable vortices without using+ // viewport dimensions or the current generated height.+ for (let offsetY = -1; offsetY <= 1; offsetY += 1) {+ for (let offsetX = -1; offsetX <= 1; offsetX += 1) {+ const latticeX = gridX + offsetX;+ const latticeY = gridY + offsetY;+ const vortex = flowVortex(latticeX, latticeY, spacing);+ const dx = x - vortex.x;+ const dy = y - vortex.y;+ const distance = Math.hypot(dx, dy);+ if (distance < 0.0001) continue;+ const falloff = Math.exp(+ -(distance * distance) / (2 * vortex.radius * vortex.radius),+ );+ const influence = config.swirl * vortex.strength * falloff * 0.34;+ vx += (-dy / distance) * vortex.spin * influence;+ vy += (dx / distance) * vortex.spin * influence;+ }+ }++ const magnitude = Math.hypot(vx, vy) || 1;+ return [vx / magnitude, vy / magnitude];+ }++ function runLength(random, perpendicular, vector) {+ let result;+ if (perpendicular) {+ result = random() < 0.22 ? integer(random, 4, 7) : integer(random, 1, 4);+ const scale = config.jogLength + (1 - config.jogLength) * diagonalness(vector);+ return Math.max(1, Math.round(result * scale));+ }+ const roll = random();+ if (roll < 0.14) result = integer(random, 16, 28);+ else if (roll < 0.52) result = integer(random, 9, 16);+ else result = integer(random, 4, 10);+ const scale = 1 - diagonalness(vector) * config.diagonalFlow * 0.9;+ return Math.max(1, Math.round(result * scale));+ }++ function traceBudget(random) {+ const ceiling = config.maxRouteBudget;+ const roll = random();+ let result;+ if (roll < 0.2) result = integer(random, Math.min(42, ceiling), ceiling);+ else if (roll < 0.65) result = integer(random, Math.min(24, ceiling), Math.min(50, ceiling));+ else result = integer(random, Math.min(12, ceiling), Math.min(28, ceiling));+ return Math.max(6, result);+ }++ function lookAhead(x, y, direction, local, minimumRow, maximumRow) {+ const [dx, dy] = DIRECTIONS[direction];+ let open = 0;+ for (let step = 1; step <= 5; step += 1) {+ const nextX = x + dx * step;+ const nextY = y + dy * step;+ if (+ nextX < 1+ || nextX >= config.columns - 1+ || nextY < minimumRow+ || nextY > maximumRow+ ) break;+ const key = cellKey(nextX, nextY);+ if (occupied.has(key) || local.has(key)) break;+ open += 1;+ }+ return open;+ }++ function growOne(+ start,+ initialDirection,+ limit,+ local,+ random,+ angleDegrees,+ travelSign,+ minimumRow,+ maximumRow,+ ) {+ const points = [start];+ let [x, y] = start;+ let direction = initialDirection;+ const firstVector = flowVector(x, y, angleDegrees);+ let targetVector = [firstVector[0] * travelSign, firstVector[1] * travelSign];+ let remaining = runLength(random, false, targetVector);++ while (points.length <= limit) {+ const candidates = [];+ const primaryDirection = closestDirection(targetVector);+ for (const candidate of [direction, (direction + 1) % 4, (direction + 3) % 4]) {+ const [dx, dy] = DIRECTIONS[candidate];+ const nextX = x + dx;+ const nextY = y + dy;+ if (+ nextX < 1+ || nextX >= config.columns - 1+ || nextY < minimumRow+ || nextY > maximumRow+ ) continue;+ const key = cellKey(nextX, nextY);+ if (occupied.has(key) || local.has(key)) continue;+ const open = lookAhead(x, y, candidate, local, minimumRow, maximumRow);+ if (!open) continue;+ const straight = candidate === direction;+ let weight = straight ? (remaining > 0 ? 15 : 1.6) : (remaining > 0 ? 0.12 : 4.2);+ const alignment = dx * targetVector[0] + dy * targetVector[1];+ if (alignment < -0.16) continue;+ weight *= 0.45 + open * 0.34;+ let neighbors = 0;+ if (candidate % 2 === 0) {+ weight *= 0.45 + Math.max(0, alignment) * 2.2;+ if (nextY > minimumRow && isBlocked(nextX, nextY - 1)) neighbors += 1;+ if (nextY < maximumRow && isBlocked(nextX, nextY + 1)) neighbors += 1;+ } else {+ if (nextX > 1 && isBlocked(nextX - 1, nextY)) neighbors += 1;+ if (nextX < config.columns - 2 && isBlocked(nextX + 1, nextY)) neighbors += 1;+ }+ weight *= 1 + neighbors * config.channelAttraction;+ candidates.push([candidate, weight]);+ }+ if (!candidates.length) break;+ const nextDirection = weighted(random, candidates);+ if (nextDirection !== direction) {+ direction = nextDirection;+ remaining = runLength(+ random,+ direction % 2 !== primaryDirection % 2,+ targetVector,+ );+ } else {+ remaining -= 1;+ }+ x += DIRECTIONS[direction][0];+ y += DIRECTIONS[direction][1];+ const key = cellKey(x, y);+ local.add(key);+ points.push([x, y]);+ const sampled = flowVector(x, y, angleDegrees);+ targetVector = [sampled[0] * travelSign, sampled[1] * travelSign];+ }+ return points;+ }++ function commitTrace(cells, ownerChunk, destination) {+ if (cells.length < 6) {+ rejectedRoutes += 1;+ return false;+ }+ for (const [x, y] of cells) {+ const key = cellKey(x, y);+ if (occupied.has(key)) {+ rejectedRoutes += 1;+ return false;+ }+ }+ for (const [x, y] of cells) {+ occupied.add(cellKey(x, y));+ rowOccupancy.set(y, (rowOccupancy.get(y) || 0) + 1);+ }+ totalOccupiedCells += cells.length;+ // Simplify first, then cut only a short diagonal across each reserved+ // corner. This keeps the visible path inside its occupied grid corridor.+ const shaped = chamfer(simplify(cells));+ const points = shaped.map(([x, y]) => [x * config.pitch, y * config.pitch]);+ const yValues = points.map((point) => point[1]);+ const trace = Object.freeze({+ id: `${seedHash.toString(36)}-${nextTraceSequence.toString(36)}`,+ chunkId: ownerChunk,+ ownerChunk,+ points,+ length: pathLength(points),+ minY: Math.min(...yValues),+ maxY: Math.max(...yValues),+ viaStart: true,+ viaEnd: true,+ });+ nextTraceSequence += 1;+ destination.push(trace);+ retained.push(trace);+ totalPublished += 1;+ return true;+ }++ function makeInteriorTrace(start, ownerChunk, destination, random, minimumRow, maximumRow) {+ const startKey = cellKey(start[0], start[1]);+ if (occupied.has(startKey)) return false;+ const followsPrimary = random() < config.horizontalFlow;+ const angleDegrees = config.flowAngle + (followsPrimary ? 0 : 90);+ const startVector = flowVector(start[0], start[1], angleDegrees);+ const direction = closestDirection(startVector);+ const budget = traceBudget(random);+ const forwardBudget = Math.max(3, Math.floor(budget * (0.42 + random() * 0.16)));+ const local = new Set([startKey]);+ const forward = growOne(+ start,+ direction,+ forwardBudget,+ local,+ random,+ angleDegrees,+ 1,+ minimumRow,+ maximumRow,+ );+ const backward = growOne(+ start,+ (direction + 2) % 4,+ budget - forwardBudget,+ local,+ random,+ angleDegrees,+ -1,+ minimumRow,+ maximumRow,+ );+ return commitTrace(backward.slice(1).reverse().concat(forward), ownerChunk, destination);+ }++ function makeEdgeTrace(+ start,+ direction,+ ownerChunk,+ destination,+ random,+ minimumRow,+ maximumRow,+ routeOptions = {},+ ) {+ const startKey = cellKey(start[0], start[1]);+ if (occupied.has(startKey)) return false;+ const local = new Set([startKey]);+ const budget = routeOptions.budget ?? traceBudget(random);+ const angleDegrees = routeOptions.angleDegrees+ ?? config.flowAngle + (random() < config.horizontalFlow ? 0 : 90);+ const sampled = flowVector(start[0], start[1], angleDegrees);+ const inward = DIRECTIONS[direction][0] * sampled[0] + DIRECTIONS[direction][1] * sampled[1];+ const cells = growOne(+ start,+ direction,+ budget,+ local,+ random,+ angleDegrees,+ inward >= 0 ? 1 : -1,+ minimumRow,+ maximumRow,+ );+ if (cells.length < (routeOptions.minimumLength ?? 6)) {+ rejectedRoutes += 1;+ return false;+ }+ return commitTrace(cells, ownerChunk, destination);+ }++ function occupiedInRange(startRow, endRow) {+ let result = 0;+ for (let row = startRow; row <= endRow; row += 1) {+ result += rowOccupancy.get(row) || 0;+ }+ return result;+ }++ // Future route probes reject every row below this monotonically increasing+ // guard, so neither occupancy structure can observe discarded rows again.+ function pruneGenerationCaches(minimumRouteRow) {+ generationCacheMinimumRow = minimumRouteRow;++ for (const key of occupied) {+ const row = Math.floor(key / config.columns);+ if (row < minimumRouteRow) {+ occupied.delete(key);+ prunedOccupiedCells += 1;+ }+ }++ for (const row of rowOccupancy.keys()) {+ if (row < minimumRouteRow) {+ rowOccupancy.delete(row);+ prunedOccupancyRows += 1;+ }+ }++ // flowVector samples gridY - 1 through gridY + 1, making lower lattice+ // rows unreachable once the route guard advances past them.+ const spacing = Math.max(24, Math.round(72 * config.swirlScale));+ const minimumLatticeRow = Math.floor(minimumRouteRow / spacing) - 1;+ for (const key of flowVortexCache.keys()) {+ const latticeRow = Number(key.slice(key.indexOf(",") + 1));+ if (latticeRow < minimumLatticeRow) {+ flowVortexCache.delete(key);+ prunedFlowVortices += 1;+ }+ }+ }++ function generateChunk(chunkId) {+ const chunkStart = chunkId * config.chunkRows + 1;+ const chunkEnd = chunkStart + config.chunkRows - 1;+ const minimumRouteRow = Math.max(1, chunkStart - config.routeGuardRows);+ const maximumRouteRow = chunkEnd + config.routeGuardRows;+ const random = mulberry32(hashSeed(+ `${config.seed}:${config.columns}:chunk:${chunkId}`,+ ));+ const appended = [];+ const angleRadians = config.flowAngle * Math.PI / 180;+ const absoluteX = Math.abs(Math.cos(angleRadians));+ const absoluteY = Math.abs(Math.sin(angleRadians));+ const primaryHorizontal = absoluteX / (absoluteX + absoluteY || 1);+ const horizontalWeight = config.horizontalFlow * primaryHorizontal+ + (1 - config.horizontalFlow) * (1 - primaryHorizontal);++ // Carriers are admitted only from the true left and right boundaries.+ // Chunk top and bottom are never treated as edges, which avoids seams.+ const carriers = [];+ for (let row = chunkStart; row <= chunkEnd; row += 1) {+ carriers.push([[1, row], 0], [[config.columns - 2, row], 2]);+ }+ shuffle(random, carriers);+ const carrierTarget = Math.round(config.chunkRows * config.longFlow * horizontalWeight);+ let carrierCount = 0;+ for (const [start, direction] of carriers) {+ if (carrierCount >= carrierTarget) break;+ const minimumBudget = Math.max(12, Math.round(config.columns * 0.58));+ const maximumBudget = Math.min(+ config.maxRouteBudget,+ Math.max(minimumBudget, Math.round(config.columns * 1.02)),+ );+ const budget = integer(random, Math.min(minimumBudget, maximumBudget), maximumBudget);+ if (makeEdgeTrace(+ start,+ direction,+ chunkId,+ appended,+ random,+ minimumRouteRow,+ maximumRouteRow,+ {+ budget,+ angleDegrees: config.flowAngle,+ minimumLength: Math.max(6, Math.round(config.columns * 0.3)),+ },+ )) carrierCount += 1;+ }++ const edgeSeeds = shuffle(random, carriers.slice());+ const edgeTarget = Math.round(config.chunkRows * 2 * config.edgeDensity);+ let edgeCount = 0;+ for (const [start, direction] of edgeSeeds) {+ if (edgeCount >= edgeTarget) break;+ if (makeEdgeTrace(+ start,+ direction,+ chunkId,+ appended,+ random,+ minimumRouteRow,+ maximumRouteRow,+ )) edgeCount += 1;+ }++ const seeds = [];+ for (let row = chunkStart; row <= chunkEnd; row += 1) {+ for (let column = 1; column < config.columns - 1; column += 1) {+ seeds.push([column, row]);+ }+ }+ shuffle(random, seeds);+ const targetFill = Math.min(0.82, Math.max(0.12, config.fill * config.density));+ const targetOccupied = Math.round(+ targetFill * config.chunkRows * (config.columns - 2),+ );+ let chunkOccupied = occupiedInRange(chunkStart, chunkEnd);+ for (const seed of seeds) {+ if (chunkOccupied >= targetOccupied) break;+ if (isBlocked(seed[0], seed[1])) continue;+ if (makeInteriorTrace(+ seed,+ chunkId,+ appended,+ random,+ minimumRouteRow,+ maximumRouteRow,+ )) {+ chunkOccupied = occupiedInRange(chunkStart, chunkEnd);+ }+ }++ generatedThroughRow = chunkEnd;+ nextChunkId = chunkId + 1;+ const nextMinimumRouteRow = Math.max(+ 1,+ nextChunkId * config.chunkRows + 1 - config.routeGuardRows,+ );+ pruneGenerationCaches(nextMinimumRouteRow);+ if (appended.length) {+ const immutableBatch = Object.freeze(appended.slice());+ for (const callback of callbacks) callback(immutableBatch, api);+ }+ return appended;+ }++ const api = {+ ensureThrough(worldY) {+ assertLive();+ const target = Math.max(0, Number(worldY) || 0);+ const appended = [];+ while (generatedThroughRow * config.pitch < target) {+ appended.push(...generateChunk(nextChunkId));+ }+ return appended;+ },++ onAppend(callback) {+ assertLive();+ if (typeof callback !== "function") throw new TypeError("callback must be a function");+ callbacks.add(callback);+ return () => callbacks.delete(callback);+ },++ pruneBefore(worldY) {+ assertLive();+ const boundary = Number(worldY) || 0;+ const removed = [];+ retained = retained.filter((trace) => {+ if (trace.maxY >= boundary) return true;+ removed.push(trace.id);+ return false;+ });+ totalPruned += removed.length;+ return removed;+ },++ reset(nextOptions = {}) {+ assertLive();+ initialize({ ...config, ...nextOptions });+ return api;+ },++ destroy() {+ if (destroyed) return;+ destroyed = true;+ callbacks.clear();+ retained = [];+ },++ get width() {+ return config.width;+ },++ get height() {+ return generatedThroughRow * config.pitch;+ },++ get generatedThrough() {+ return generatedThroughRow * config.pitch;+ },++ get traces() {+ return retained;+ },++ get retainedTraces() {+ return retained;+ },++ get stats() {+ const generatedCells = Math.max(1, generatedThroughRow * config.columns);+ return Object.freeze({+ chunks: nextChunkId,+ columns: config.columns,+ chunkRows: config.chunkRows,+ pitch: config.pitch,+ width: config.width,+ generatedThrough: generatedThroughRow * config.pitch,+ occupiedCells: totalOccupiedCells,+ occupancyFill: totalOccupiedCells / generatedCells,+ occupiedCellsRetained: occupied.size,+ occupiedCellsPruned: prunedOccupiedCells,+ occupancyRowsRetained: rowOccupancy.size,+ occupancyRowsPruned: prunedOccupancyRows,+ flowVorticesRetained: flowVortexCache.size,+ flowVorticesPruned: prunedFlowVortices,+ generationCacheMinimumRow,+ totalPublished,+ retainedTraces: retained.length,+ totalPruned,+ rejectedRoutes,+ routeGuardRows: config.routeGuardRows,+ occupancyRetainedForSafety: true,+ });+ },+ };++ initialize(options);+ return api;+}
src/circuit-geometry-v9.jsadded+1112@@ -0,0 +1,1112 @@+import { createConductorAnimation } from "./circuit-animation-conductor.js?v=1";+import {+ createObstacleField,+ obstacleEdgeWeight,+ obstacleOutlineTraces,+} from "./circuit-obstacles-v9.js?v=1";++const SVG_NS = "http://www.w3.org/2000/svg";++const DEFAULTS = Object.freeze({+ seed: "nitrogen",+ pitch: 7.895,+ scale: 1000 / 900,+ density: 1,+ fill: 0.668,+ routeLength: 0.78,+ horizontalFlow: 0.82,+ flowAngle: 0,+ swirl: 0.28,+ swirlScale: 0.8,+ diagonalFlow: 0.58,+ jogLength: 0.72,+ channelAttraction: 0.78,+ longFlow: 0.18,+ edgeDensity: 0.22,+ obstaclePreset: "none",+ obstacleMode: "avoid",+ obstacleScale: 0.66,+ obstacleX: 0.5,+ obstacleY: 0.66,+ obstacleClearance: 1.1,+ obstaclePull: 0.82,+ obstacles: Object.freeze([]),+ traceColor: "#151b25",+ traceWidth: 1.58,+ featureScale: 1,+ viaOuterRadius: 3.34,+ viaInnerRadius: 1.76,+ motion: true,+ interactive: true,+ animationSystem: "conductor",+ liveliness: 0.82,+ signalHalos: true,+ signalConvoys: true,+ signalWaves: true,+ pointerWake: true,+ nodeFlashes: true,+ ambientCurrents: true,+ ambientNodes: true,+ signalColors: [+ ["#00e6dc", 0.6],+ ["#64abff", 0.25],+ ["#c5b3ff", 0.15],+ ],+ signalInterval: 420,+ signalSpeed: 800,+ signalLength: 110,+ maxSignals: 28,+ ambientCurrentCount: 18,+ ambientNodeCount: 22,+ waveInterval: 6200,+ pointerWakeInterval: 170,+ sweepDuration: 15200,+ sweepAngle: 18,+ sweepWidth: 0.075,+ bloomInterval: 7600,+ bloomDuration: 4800,+ pointerRadius: 0.19,+ atmosphereStrength: 1,+});++const ANIMATION_PRESETS = Object.freeze({+ none: Object.freeze({+ animationSystem: "none",+ motion: false,+ liveliness: 0,+ atmosphereStrength: 0,+ }),+ conductor: Object.freeze({+ animationSystem: "conductor",+ motion: true,+ liveliness: 0.82,+ signalHalos: true,+ signalConvoys: true,+ signalWaves: true,+ pointerWake: true,+ nodeFlashes: true,+ ambientCurrents: true,+ ambientNodes: true,+ signalColors: [+ ["#00e6dc", 0.6],+ ["#64abff", 0.25],+ ["#c5b3ff", 0.15],+ ],+ signalInterval: 420,+ signalSpeed: 800,+ signalLength: 110,+ maxSignals: 28,+ ambientCurrentCount: 18,+ ambientNodeCount: 22,+ waveInterval: 6200,+ pointerWakeInterval: 170,+ atmosphereStrength: 1,+ }),+ adom: Object.freeze({+ animationSystem: "adom",+ motion: true,+ liveliness: 0.88,+ sweepDuration: 15200,+ sweepAngle: 18,+ sweepWidth: 0.075,+ bloomInterval: 7600,+ bloomDuration: 4800,+ pointerRadius: 0.19,+ atmosphereStrength: 1,+ }),+});++const DIRECTIONS = [[1, 0], [0, 1], [-1, 0], [0, -1]];+let instanceCount = 0;++function hashSeed(value) {+ let hash = 2166136261;+ for (const char of String(value)) {+ hash ^= char.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function mulberry32(seed) {+ return function random() {+ let value = (seed += 0x6d2b79f5);+ value = Math.imul(value ^ (value >>> 15), value | 1);+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;+ };+}++function integer(random, min, max) {+ return Math.floor(random() * (max - min + 1)) + min;+}++function weighted(random, entries) {+ let total = 0;+ for (const [, weight] of entries) total += weight;+ let roll = random() * total;+ for (const [value, weight] of entries) {+ roll -= weight;+ if (roll <= 0) return value;+ }+ return entries.at(-1)?.[0];+}++function shuffle(random, values) {+ for (let index = values.length - 1; index > 0; index -= 1) {+ const swap = integer(random, 0, index);+ [values[index], values[swap]] = [values[swap], values[index]];+ }+ return values;+}++function cellIndex(x, y, columns) {+ return y * columns + x;+}++function runLength(random, perpendicular, config, vector = [1, 0]) {+ const localDiagonalness = diagonalness(vector);+ let result;+ if (perpendicular) {+ result = random() < 0.22 ? integer(random, 4, 7) : integer(random, 1, 4);+ const scale = config.jogLength + (1 - config.jogLength) * localDiagonalness;+ return Math.max(1, Math.round(result * scale));+ }+ const roll = random();+ if (roll < 0.14) result = integer(random, 16, 28);+ else if (roll < 0.52) result = integer(random, 9, 16);+ else result = integer(random, 4, 10);+ const scale = 1 - localDiagonalness * config.diagonalFlow * 0.9;+ return Math.max(1, Math.round(result * scale));+}++function traceBudget(random, columns, rows, config) {+ const ceiling = Math.max(12, Math.min(86, Math.floor(Math.hypot(columns, rows) * 0.52)));+ const roll = random();+ let result;+ if (roll < 0.2) result = integer(random, Math.min(42, ceiling), ceiling);+ else if (roll < 0.65) result = integer(random, 24, Math.min(50, ceiling));+ else result = integer(random, 12, Math.min(28, ceiling));+ return Math.max(6, Math.round(result * config.routeLength));+}++function createFlowField(config, columns, rows) {+ const random = mulberry32(hashSeed(`${config.seed}:${columns}x${rows}:flow-field`));+ const minimumDimension = Math.min(columns, rows);+ const count = Math.max(2, Math.min(5, Math.round(columns * rows / 5200)));+ const vortices = [];+ for (let index = 0; index < count; index += 1) {+ const radius = minimumDimension * config.swirlScale * (0.55 + random() * 0.45);+ vortices.push({+ x: columns * (0.08 + random() * 0.84),+ y: rows * (0.08 + random() * 0.84),+ radius: Math.max(8, radius),+ spin: random() < 0.5 ? -1 : 1,+ strength: 0.72 + random() * 0.56,+ });+ }+ return { vortices };+}++function flowVector(x, y, angleDegrees, field, config) {+ const radians = angleDegrees * Math.PI / 180;+ let vx = Math.cos(radians);+ let vy = Math.sin(radians);+ for (const vortex of field.vortices) {+ const dx = x - vortex.x;+ const dy = y - vortex.y;+ const distance = Math.hypot(dx, dy);+ if (distance < 0.0001) continue;+ const falloff = Math.exp(-(distance * distance) / (2 * vortex.radius * vortex.radius));+ const influence = config.swirl * vortex.strength * falloff;+ vx += -dy / distance * vortex.spin * influence;+ vy += dx / distance * vortex.spin * influence;+ }+ const length = Math.hypot(vx, vy) || 1;+ return [vx / length, vy / length];+}++function closestDirection(vector) {+ let bestDirection = 0;+ let bestScore = -Infinity;+ for (let direction = 0; direction < DIRECTIONS.length; direction += 1) {+ const score = DIRECTIONS[direction][0] * vector[0] + DIRECTIONS[direction][1] * vector[1];+ if (score > bestScore) {+ bestScore = score;+ bestDirection = direction;+ }+ }+ return bestDirection;+}++function diagonalness(vector) {+ return 1 - Math.abs(Math.abs(vector[0]) - Math.abs(vector[1]));+}++function lookAhead(x, y, direction, blocked, local, columns, rows) {+ const [dx, dy] = DIRECTIONS[direction];+ let open = 0;+ for (let step = 1; step <= 5; step += 1) {+ const nx = x + dx * step;+ const ny = y + dy * step;+ if (nx < 0 || ny < 0 || nx >= columns || ny >= rows) break;+ const index = cellIndex(nx, ny, columns);+ if (blocked[index] || local.has(index)) break;+ open += 1;+ }+ return open;+}++function growOne(start, initialDirection, limit, blocked, local, columns, rows, random, config, field, angleDegrees, travelSign = 1, obstacle = null) {+ const points = [start];+ let [x, y] = start;+ let direction = initialDirection;+ const initialVector = flowVector(x, y, angleDegrees, field, config);+ const initialTarget = [initialVector[0] * travelSign, initialVector[1] * travelSign];+ let remaining = runLength(random, false, config, initialTarget);++ while (points.length <= limit) {+ const candidates = [];+ const directions = [direction, (direction + 1) % 4, (direction + 3) % 4];+ const sampledVector = flowVector(x, y, angleDegrees, field, config);+ const targetVector = [sampledVector[0] * travelSign, sampledVector[1] * travelSign];+ const primaryDirection = closestDirection(targetVector);+ for (const candidate of directions) {+ const [dx, dy] = DIRECTIONS[candidate];+ const nx = x + dx;+ const ny = y + dy;+ // Keep every endpoint (and therefore every via) fully inside the canvas.+ if (nx < 1 || ny < 1 || nx >= columns - 1 || ny >= rows - 1) continue;+ const index = cellIndex(nx, ny, columns);+ if (blocked[index] || local.has(index)) continue;+ const open = lookAhead(x, y, candidate, blocked, local, columns, rows);+ if (!open) continue;+ const straight = candidate === direction;+ let weight = straight ? (remaining > 0 ? 15 : 1.6) : (remaining > 0 ? 0.12 : 4.2);+ const alignment = dx * targetVector[0] + dy * targetVector[1];+ if (alignment < -0.16) continue;+ weight *= 0.45 + open * 0.34;+ let neighbors = 0;+ if (candidate % 2 === 0) {+ weight *= 0.45 + Math.max(0, alignment) * 2.2;+ if (ny > 0 && blocked[cellIndex(nx, ny - 1, columns)]) neighbors += 1;+ if (ny < rows - 1 && blocked[cellIndex(nx, ny + 1, columns)]) neighbors += 1;+ } else {+ if (nx > 0 && blocked[cellIndex(nx - 1, ny, columns)]) neighbors += 1;+ if (nx < columns - 1 && blocked[cellIndex(nx + 1, ny, columns)]) neighbors += 1;+ }+ weight *= 1 + neighbors * config.channelAttraction;+ weight *= obstacleEdgeWeight(+ obstacle,+ nx,+ ny,+ dx,+ dy,+ columns,+ Math.max(0, Number(config.obstaclePull) || 0),+ );+ candidates.push([candidate, weight]);+ }+ if (!candidates.length) break;+ const nextDirection = weighted(random, candidates);+ if (nextDirection !== direction) {+ direction = nextDirection;+ remaining = runLength(random, direction % 2 !== primaryDirection % 2, config, targetVector);+ } else {+ remaining -= 1;+ }+ x += DIRECTIONS[direction][0];+ y += DIRECTIONS[direction][1];+ const index = cellIndex(x, y, columns);+ local.add(index);+ points.push([x, y]);+ }+ return points;+}++function chamfer(path) {+ if (path.length < 3) return path;+ const result = [path[0]];+ for (let index = 1; index < path.length - 1; index += 1) {+ const previous = path[index - 1];+ const current = path[index];+ const next = path[index + 1];+ const ax = current[0] - previous[0];+ const ay = current[1] - previous[1];+ const bx = next[0] - current[0];+ const by = next[1] - current[1];+ if (ax * bx + ay * by === 0 && (ax !== bx || ay !== by)) continue;+ result.push(current);+ }+ result.push(path.at(-1));+ return result;+}++function simplify(path) {+ if (path.length < 3) return path;+ const result = [path[0]];+ for (let index = 1; index < path.length - 1; index += 1) {+ const previous = result.at(-1);+ const current = path[index];+ const next = path[index + 1];+ const ax = Math.sign(current[0] - previous[0]);+ const ay = Math.sign(current[1] - previous[1]);+ const bx = Math.sign(next[0] - current[0]);+ const by = Math.sign(next[1] - current[1]);+ if (ax !== bx || ay !== by) result.push(current);+ }+ result.push(path.at(-1));+ return result;+}++function pathLength(points) {+ let length = 0;+ for (let index = 1; index < points.length; index += 1) {+ length += Math.hypot(points[index][0] - points[index - 1][0], points[index][1] - points[index - 1][1]);+ }+ return length;+}++function commitTrace(cells, state) {+ if (cells.length < 6) return false;+ const { blocked, columns, rows, pitch, traces } = state;+ for (const [x, y] of cells) blocked[cellIndex(x, y, columns)] = 1;+ state.occupied += cells.length;+ const shaped = simplify(chamfer(cells));+ const points = shaped.map(([x, y]) => [x * pitch, y * pitch]);+ traces.push({+ points,+ length: pathLength(points),+ viaStart: true,+ viaEnd: true,+ });+ return true;+}++function makeInteriorTrace(start, state, random, config) {+ const { blocked, columns, rows } = state;+ const startIndex = cellIndex(start[0], start[1], columns);+ if (blocked[startIndex]) return false;+ const followsPrimary = random() < config.horizontalFlow;+ const angleDegrees = config.flowAngle + (followsPrimary ? 0 : 90);+ const startVector = flowVector(start[0], start[1], angleDegrees, state.flowField, config);+ const direction = closestDirection(startVector);+ const budget = traceBudget(random, columns, rows, config);+ const forwardBudget = Math.max(3, Math.floor(budget * (0.42 + random() * 0.16)));+ const local = new Set([startIndex]);+ const forward = growOne(start, direction, forwardBudget, blocked, local, columns, rows, random, config, state.flowField, angleDegrees, 1, state.obstacle);+ const backward = growOne(start, (direction + 2) % 4, budget - forwardBudget, blocked, local, columns, rows, random, config, state.flowField, angleDegrees, -1, state.obstacle);+ const cells = backward.slice(1).reverse().concat(forward);+ return commitTrace(cells, state);+}++function makeEdgeTrace(start, direction, state, random, config, options = {}) {+ const { blocked, columns, rows } = state;+ const startIndex = cellIndex(start[0], start[1], columns);+ if (blocked[startIndex]) return false;+ const local = new Set([startIndex]);+ const baseBudget = integer(random, 10, Math.max(14, Math.min(48, Math.floor(Math.hypot(columns, rows) * 0.3))));+ const budget = options.budget ?? Math.max(6, Math.round(baseBudget * config.routeLength));+ const angleDegrees = options.angleDegrees ?? config.flowAngle + (random() < config.horizontalFlow ? 0 : 90);+ const sampledVector = flowVector(start[0], start[1], angleDegrees, state.flowField, config);+ const inward = DIRECTIONS[direction][0] * sampledVector[0] + DIRECTIONS[direction][1] * sampledVector[1];+ const cells = growOne(start, direction, budget, blocked, local, columns, rows, random, config, state.flowField, angleDegrees, inward >= 0 ? 1 : -1, state.obstacle);+ if (cells.length < (options.minimumLength ?? 6)) return false;+ return commitTrace(cells, state);+}++export function generateCircuitField(options = {}) {+ const config = { ...DEFAULTS, ...options };+ const width = Math.max(240, config.width || 900);+ const height = Math.max(180, config.height || 450);+ const featureScale = Math.max(0.25, config.featureScale);+ const pitch = config.pitch * featureScale;+ const columns = Math.max(30, Math.floor(width / pitch));+ const rows = Math.max(22, Math.floor(height / pitch));+ const random = mulberry32(hashSeed(`${config.seed}:${columns}x${rows}`));+ const normalizedWidth = (columns - 1) * pitch;+ const normalizedHeight = (rows - 1) * pitch;+ const obstacle = createObstacleField(config, {+ width: normalizedWidth,+ height: normalizedHeight,+ pitch,+ columns,+ rows,+ });+ const state = {+ blocked: obstacle ? obstacle.blocked.slice() : new Uint8Array(columns * rows),+ columns,+ rows,+ pitch,+ traces: [],+ occupied: 0,+ obstacle,+ flowField: createFlowField(config, columns, rows),+ };+ const outlines = obstacleOutlineTraces(obstacle, {+ pitch,+ viaOuterRadius: config.viaOuterRadius * featureScale,+ });+ state.traces.push(...outlines);++ const flowRadians = config.flowAngle * Math.PI / 180;+ const absoluteX = Math.abs(Math.cos(flowRadians));+ const absoluteY = Math.abs(Math.sin(flowRadians));+ const primaryHorizontalWeight = absoluteX / (absoluteX + absoluteY || 1);+ const horizontalWeight = config.horizontalFlow * primaryHorizontalWeight + (1 - config.horizontalFlow) * (1 - primaryHorizontalWeight);+ const verticalWeight = 1 - horizontalWeight;+ const horizontalCarriers = [];+ for (let y = 1; y < rows - 1; y += 1) {+ horizontalCarriers.push([[1, y], 0], [[columns - 2, y], 2]);+ }+ shuffle(random, horizontalCarriers);+ const horizontalTarget = Math.round(rows * config.longFlow * horizontalWeight);+ let horizontalCarrierCount = 0;+ for (const [start, direction] of horizontalCarriers) {+ if (horizontalCarrierCount >= horizontalTarget) break;+ const minimumBudget = Math.max(12, Math.round(columns * 0.58 * config.routeLength));+ const maximumBudget = Math.max(minimumBudget, Math.round(columns * 1.02 * config.routeLength));+ const budget = integer(random, minimumBudget, maximumBudget);+ if (makeEdgeTrace(start, direction, state, random, config, {+ budget,+ angleDegrees: config.flowAngle,+ minimumLength: Math.round(columns * 0.3),+ })) horizontalCarrierCount += 1;+ }++ const verticalCarriers = [];+ for (let x = 1; x < columns - 1; x += 1) {+ verticalCarriers.push([[x, 1], 1], [[x, rows - 2], 3]);+ }+ shuffle(random, verticalCarriers);+ const verticalTarget = Math.round(columns * config.longFlow * verticalWeight * 0.34);+ let verticalCarrierCount = 0;+ for (const [start, direction] of verticalCarriers) {+ if (verticalCarrierCount >= verticalTarget) break;+ const minimumBudget = Math.max(12, Math.round(rows * 0.58 * config.routeLength));+ const maximumBudget = Math.max(minimumBudget, Math.round(rows * 1.02 * config.routeLength));+ const budget = integer(random, minimumBudget, maximumBudget);+ if (makeEdgeTrace(start, direction, state, random, config, {+ angleDegrees: config.flowAngle,+ budget,+ minimumLength: Math.round(rows * 0.3),+ })) verticalCarrierCount += 1;+ }++ const edgeSeeds = [];+ for (let x = 1; x < columns - 1; x += 1) {+ edgeSeeds.push([[x, 1], 1], [[x, rows - 2], 3]);+ }+ for (let y = 1; y < rows - 1; y += 1) {+ edgeSeeds.push([[1, y], 0], [[columns - 2, y], 2]);+ }+ shuffle(random, edgeSeeds);+ const edgeTarget = Math.round((columns + rows) * config.edgeDensity);+ let edgeCount = 0;+ for (const [start, direction] of edgeSeeds) {+ if (edgeCount >= edgeTarget) break;+ if (makeEdgeTrace(start, direction, state, random, config)) edgeCount += 1;+ }++ const interiorColumns = columns - 2;+ const interiorRows = rows - 2;+ const seeds = shuffle(random, Array.from(+ { length: interiorColumns * interiorRows },+ (_, index) => (Math.floor(index / interiorColumns) + 1) * columns + index % interiorColumns + 1,+ ));+ // Density controls occupied routing cells only. Feature scale changes the+ // physical size of the whole motif without secretly changing this target.+ const targetFill = Math.min(0.82, Math.max(0.18, config.fill * config.density));+ const fillCapacity = obstacle+ ? Math.max(1, interiorColumns * interiorRows - obstacle.blockedCells)+ : columns * rows;+ for (const index of seeds) {+ if (state.occupied / fillCapacity >= targetFill) break;+ if (state.blocked[index]) continue;+ makeInteriorTrace([index % columns, Math.floor(index / columns)], state, random, config);+ }++ return {+ width: normalizedWidth,+ height: normalizedHeight,+ columns,+ rows,+ fill: state.occupied / fillCapacity,+ traces: state.traces,+ obstacle: obstacle ? Object.freeze({+ count: obstacle.count,+ blockedCells: obstacle.blockedCells,+ outlineTraceCount: outlines.length,+ mode: obstacle.mode,+ }) : null,+ };+}++export function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x.toFixed(2)},${y.toFixed(2)}`).join("");+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++export function createCircuitBackground(mount, options = {}) {+ if (!(mount instanceof Element)) throw new TypeError("mount must be a DOM element");+ const id = `circuit-field-${++instanceCount}`;+ let config = { ...DEFAULTS, ...options };+ let field;+ let svg;+ let motionCanvas;+ let motionContext;+ let brandGradient;+ let conductor;+ let resizeObserver;+ let resizeTimer;+ let frameRequest;+ let frameCount = 0;+ let activeTraces = 0;+ let bloomsTriggered = 0;+ let visuals = [];+ let blooms = [];+ let pointer = null;+ let motionRandom;+ let lastSize = "";+ let sceneStart = 0;+ let lastFrameTime = 0;+ let lastPaintTime = 0;+ let nextBloomAt = 0;+ let bloomCursor = 0;+ let focus = { x: 0, y: 0 };+ let rendererPixelRatio = 1;+ let targetFrameRate = 60;+ let frameInterval = 1000 / targetFrameRate;+ let energyBudget = 0;+ let sparkBudget = 0;+ let nodeBudget = 0;+ let drawnEnergyTraces = 0;+ let drawnSparks = 0;+ let drawnNodes = 0;+ const energyCandidates = [];+ const sparkCandidates = [];+ const nodeCandidates = [];+ const interactionTarget = mount.parentElement || mount;+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const originalPosition = mount.style.position;+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";+ mount.style.overflow = "hidden";++ function life() {+ return Math.max(0, Math.min(1.5, config.liveliness));+ }++ function featureScale() {+ return Math.max(0.25, config.featureScale);+ }++ function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+ }++ function colorAt(position) {+ if (position < 0.46) return "#00e6dc";+ if (position < 0.76) return "#39b8ff";+ return "#8c6bf7";+ }++ function addVia(group, point) {+ const scale = featureScale();+ group.append(+ svgElement("circle", { cx: point[0], cy: point[1], r: config.viaOuterRadius * scale, fill: config.traceColor }),+ svgElement("circle", { cx: point[0], cy: point[1], r: config.viaInnerRadius * scale, fill: "var(--circuit-hole, #0d1117)" }),+ );+ }++ function build(force = false) {+ const pixelWidth = Math.max(1, mount.clientWidth);+ const pixelHeight = Math.max(1, mount.clientHeight);+ const worldWidth = pixelWidth / config.scale;+ const worldHeight = pixelHeight / config.scale;+ const pitch = config.pitch * featureScale();+ const size = `${Math.floor(worldWidth / pitch)}x${Math.floor(worldHeight / pitch)}`;+ if (!force && size === lastSize) return false;+ lastSize = size;+ activeTraces = 0;+ visuals = [];+ blooms = [];+ conductor?.destroy();+ conductor = undefined;+ motionCanvas?.remove();+ motionCanvas = undefined;+ motionContext = undefined;+ brandGradient = undefined;+ svg?.remove();+ field = generateCircuitField({ ...config, width: worldWidth, height: worldHeight });+ const motionSeed = config.animationSystem === "conductor"+ ? `${config.seed}:${size}:signals`+ : `${config.seed}:${size}:adom-motion`;+ motionRandom = mulberry32(hashSeed(motionSeed));+ svg = svgElement("svg", {+ id, "aria-hidden": true, focusable: false,+ viewBox: `0 0 ${field.width} ${field.height}`,+ preserveAspectRatio: "none",+ });+ Object.assign(svg.style, {+ position: "absolute", inset: "0", width: "100%", height: "100%",+ display: "block", pointerEvents: "none",+ });++ const traceLayer = svgElement("g", { "data-static-traces": "" });+ for (const trace of field.traces) {+ traceLayer.appendChild(svgElement("path", {+ d: pathData(trace.points), fill: "none", stroke: config.traceColor,+ "stroke-width": config.traceWidth * config.featureScale,+ "stroke-linecap": "butt", "stroke-linejoin": "miter",+ }));+ if (trace.viaStart) addVia(traceLayer, trace.points[0]);+ if (trace.viaEnd) addVia(traceLayer, trace.points.at(-1));+ }++ if (config.animationSystem === "none") {+ svg.append(traceLayer);+ mount.prepend(svg);+ return true;+ }++ if (config.animationSystem === "conductor") {+ svg.append(traceLayer);+ mount.prepend(svg);+ conductor = createConductorAnimation(svg, field, config, motionRandom);+ return true;+ }++ const angle = config.sweepAngle * Math.PI / 180;+ const axisX = Math.cos(angle);+ const axisY = Math.sin(angle);+ let projectionMin = Infinity;+ let projectionMax = -Infinity;+ const prepared = field.traces.map((trace, index) => {+ const midpoint = trace.points[Math.floor(trace.points.length / 2)];+ const projection = midpoint[0] * axisX + midpoint[1] * axisY;+ projectionMin = Math.min(projectionMin, projection);+ projectionMax = Math.max(projectionMax, projection);+ return { trace, index, midpoint, projection };+ });+ const projectionSpan = Math.max(1, projectionMax - projectionMin);+ const scale = featureScale();++ for (const preparedTrace of prepared) {+ const { trace, index, midpoint } = preparedTrace;+ const normalizedProjection = (preparedTrace.projection - projectionMin) / projectionSpan;+ const directionBias = trace.points[0][0] <= trace.points.at(-1)[0] ? 1 : -1;+ const sparkLength = clamp(trace.length * (0.1 + motionRandom() * 0.06), 10 * scale, 58 * scale);+ const endpoint = trace.points[(index + Math.round(normalizedProjection * 5)) % 2 ? 0 : trace.points.length - 1];+ let canvasPath = null;+ if (typeof Path2D === "function") {+ canvasPath = new Path2D();+ trace.points.forEach(([x, y], pointIndex) => {+ if (pointIndex) canvasPath.lineTo(x, y);+ else canvasPath.moveTo(x, y);+ });+ }+ visuals.push({+ trace, midpoint, projection: normalizedProjection,+ canvasPath, endpoint, nodeColor: colorAt(normalizedProjection),+ sparkLength, directionBias,+ charge: 0, phase: motionRandom(), sparkEligible: motionRandom() > 0.34,+ energyOpacity: 0, sparkOpacity: 0, nodeOpacity: 0,+ });+ }++ svg.append(traceLayer);+ mount.prepend(svg);++ const traceCount = visuals.length;+ targetFrameRate = traceCount > 1500 ? 24 : traceCount > 900 ? 30 : traceCount > 420 ? 45 : 60;+ frameInterval = 1000 / targetFrameRate;+ energyBudget = traceCount > 1500 ? 420 : traceCount > 900 ? 500 : traceCount > 420 ? 620 : traceCount;+ sparkBudget = traceCount > 1500 ? 28 : traceCount > 900 ? 36 : traceCount > 420 ? 46 : 58;+ nodeBudget = traceCount > 1500 ? 48 : traceCount > 900 ? 64 : traceCount > 420 ? 82 : 104;+ const deviceRatio = Math.max(1, window.devicePixelRatio || 1);+ rendererPixelRatio = Math.min(deviceRatio, traceCount > 1200 ? 1 : traceCount > 600 ? 1.25 : 1.5);++ motionCanvas = document.createElement("canvas");+ motionCanvas.setAttribute("aria-hidden", "true");+ motionCanvas.setAttribute("data-animation", "routed-field-canvas");+ Object.assign(motionCanvas.style, {+ position: "absolute", inset: "0", width: "100%", height: "100%",+ display: "block", pointerEvents: "none", mixBlendMode: "screen", zIndex: "1",+ });+ motionCanvas.width = Math.max(1, Math.round(pixelWidth * rendererPixelRatio));+ motionCanvas.height = Math.max(1, Math.round(pixelHeight * rendererPixelRatio));+ mount.appendChild(motionCanvas);+ motionContext = motionCanvas.getContext("2d", { alpha: true, desynchronized: true })+ || motionCanvas.getContext("2d");+ if (motionContext) {+ motionContext.setTransform(+ motionCanvas.width / field.width, 0,+ 0, motionCanvas.height / field.height, 0, 0,+ );+ brandGradient = motionContext.createLinearGradient(+ 0, field.height * 0.15, field.width, field.height * 0.85,+ );+ brandGradient.addColorStop(0, "#00e6dc");+ brandGradient.addColorStop(0.6, "#39b8ff");+ brandGradient.addColorStop(1, "#8c6bf7");+ }+ focus = { x: field.width * 0.5, y: field.height * 0.5 };+ return true;+ }++ function spawnBloom(origin = null, intensity = 1) {+ if (config.animationSystem !== "adom" || !config.motion || reducedMotion || !field?.traces.length) return false;+ const source = origin || { x: field.width * 0.24, y: field.height * 0.62 };+ const angle = Math.atan2(source.y - field.height * 0.5, source.x - field.width * 0.5);+ blooms.push({+ x: clamp(source.x, 0, field.width),+ y: clamp(source.y, 0, field.height),+ startedAt: performance.now(),+ duration: config.bloomDuration / clamp(life(), 0.55, 1.35),+ intensity: clamp(intensity, 0.35, 1.4),+ spin: angle / (Math.PI * 2) + motionRandom() * 0.18,+ });+ if (blooms.length > 3) blooms.shift();+ bloomsTriggered += 1;+ return true;+ }++ function spawnAutomaticBloom() {+ if (!visuals.length) return;+ const stride = Math.max(1, Math.floor(visuals.length * 0.381966));+ bloomCursor = (bloomCursor + stride) % visuals.length;+ const anchor = visuals[bloomCursor].midpoint;+ spawnBloom({ x: anchor[0], y: anchor[1] }, 0.78 + motionRandom() * 0.18);+ }++ function energyFromBloom(visual, bloom, timestamp, maximumDimension) {+ const progress = (timestamp - bloom.startedAt) / bloom.duration;+ if (progress < 0 || progress > 1) return 0;+ const dx = visual.midpoint[0] - bloom.x;+ const dy = visual.midpoint[1] - bloom.y;+ const distance = Math.hypot(dx, dy) / maximumDimension;+ const angle = (Math.atan2(dy, dx) / (Math.PI * 2) + 1 + bloom.spin) % 1;+ const arrival = distance * 1.08 + angle * 0.105;+ const distanceFromFront = progress - arrival;+ const crest = Math.exp(-(distanceFromFront * distanceFromFront) / (2 * 0.052 * 0.052));+ const afterglow = distanceFromFront > 0 && distanceFromFront < 0.24+ ? (1 - distanceFromFront / 0.24) ** 2 * 0.23+ : 0;+ return (crest + afterglow) * bloom.intensity;+ }++ function onPointerMove(event) {+ if (!field) return;+ const rect = mount.getBoundingClientRect();+ pointer = {+ x: (event.clientX - rect.left) / rect.width * field.width,+ y: (event.clientY - rect.top) / rect.height * field.height,+ at: performance.now(),+ };+ conductor?.pointerMoved(pointer);+ }++ function onPointerLeave() {+ if (pointer) pointer.at = performance.now() - 1800;+ }++ function onClick(event) {+ onPointerMove(event);+ if (config.animationSystem === "conductor") conductor?.clicked(pointer);+ else spawnBloom(pointer, 1.18);+ }++ function strokeCanvasPath(context, visual) {+ if (visual.canvasPath) {+ context.stroke(visual.canvasPath);+ return;+ }+ context.beginPath();+ visual.trace.points.forEach(([x, y], index) => {+ if (index) context.lineTo(x, y);+ else context.moveTo(x, y);+ });+ context.stroke();+ }++ function renderFrame(timestamp) {+ if (!motionCanvas?.isConnected || !motionContext || !visuals.length) return;+ frameRequest = window.requestAnimationFrame(renderFrame);+ if (document.hidden) return;+ const sincePaint = lastPaintTime ? timestamp - lastPaintTime : frameInterval;+ if (sincePaint < frameInterval) return;+ lastPaintTime = lastPaintTime+ ? timestamp - (sincePaint % frameInterval)+ : timestamp;+ frameCount += 1;+ const frameDelta = lastFrameTime ? clamp(timestamp - lastFrameTime, 8, 50) : 16;+ lastFrameTime = timestamp;++ const strength = life();+ const maximumDimension = Math.max(field.width, field.height);+ const elapsed = timestamp - sceneStart;+ const sweepPhase = ((elapsed % config.sweepDuration) + config.sweepDuration) % config.sweepDuration / config.sweepDuration;+ const sweepActive = sweepPhase < 0.73;+ const sweepFront = sweepActive ? -0.14 + sweepPhase / 0.73 * 1.28 : 2;+ const sweepWidth = config.sweepWidth / clamp(strength, 0.65, 1.25);++ if (timestamp >= nextBloomAt) {+ spawnAutomaticBloom();+ nextBloomAt = timestamp + config.bloomInterval / clamp(0.72 + strength * 0.28, 0.72, 1.12);+ }+ blooms = blooms.filter((bloom) => timestamp - bloom.startedAt <= bloom.duration);++ const pointerAge = pointer ? timestamp - pointer.at : Infinity;+ const pointerPresence = clamp(1 - pointerAge / 1450);+ const automaticFocus = {+ x: field.width * (0.5 + Math.sin(elapsed * 0.000095) * 0.27),+ y: field.height * (0.48 + Math.sin(elapsed * 0.000071 + 1.4) * 0.21),+ };+ const focusTarget = pointerPresence > 0.02 ? pointer : automaticFocus;+ const focusEase = pointerPresence > 0.02 ? 0.105 : 0.018;+ focus.x += (focusTarget.x - focus.x) * focusEase;+ focus.y += (focusTarget.y - focus.y) * focusEase;++ energyCandidates.length = 0;+ sparkCandidates.length = 0;+ nodeCandidates.length = 0;+ let active = 0;+ for (const visual of visuals) {+ const delta = sweepFront - visual.projection;+ const crest = sweepActive+ ? Math.exp(-(delta * delta) / (2 * sweepWidth * sweepWidth))+ : 0;+ const trail = sweepActive && delta > 0 && delta < 0.28+ ? (1 - delta / 0.28) ** 2 * 0.24+ : 0;+ let bloomEnergy = 0;+ for (const bloom of blooms) {+ bloomEnergy = Math.max(bloomEnergy, energyFromBloom(visual, bloom, timestamp, maximumDimension));+ }+ let pointerEnergy = 0;+ if (pointerPresence > 0.001) {+ const distance = Math.hypot(visual.midpoint[0] - pointer.x, visual.midpoint[1] - pointer.y);+ const radius = maximumDimension * config.pointerRadius;+ pointerEnergy = Math.exp(-(distance * distance) / (2 * radius * radius)) * pointerPresence * 0.42;+ }+ const ambient = 0.018 + (Math.sin(timestamp * 0.0005 + visual.phase * Math.PI * 2) + 1) * 0.006;+ const target = clamp((crest * 0.96 + trail + bloomEnergy + pointerEnergy + ambient) * strength, 0, 1.18);+ const response = target > visual.charge ? 1 - Math.exp(-frameDelta / 72) : 1 - Math.exp(-frameDelta / 610);+ visual.charge += (target - visual.charge) * response;++ const energyOpacity = clamp((visual.charge - 0.018) * 0.72, 0, 0.74);+ const sparkOpacity = visual.sparkEligible+ ? clamp((visual.charge - 0.25) * 1.48, 0, 0.92)+ : 0;+ const nodePulse = 0.82 + Math.sin(timestamp * 0.0031 + visual.phase * Math.PI * 2) * 0.18;+ const nodeOpacity = clamp((visual.charge - 0.34) * 1.65 * nodePulse, 0, 0.88);++ visual.energyOpacity = energyOpacity;+ visual.sparkOpacity = sparkOpacity;+ visual.nodeOpacity = nodeOpacity;+ if (energyOpacity > 0.008) energyCandidates.push(visual);+ if (sparkOpacity > 0.01) sparkCandidates.push(visual);+ if (nodeOpacity > 0.01) nodeCandidates.push(visual);+ if (visual.charge > 0.13) active += 1;+ }+ activeTraces = active;++ energyCandidates.sort((a, b) => b.energyOpacity - a.energyOpacity);+ sparkCandidates.sort((a, b) => b.sparkOpacity - a.sparkOpacity);+ nodeCandidates.sort((a, b) => b.nodeOpacity - a.nodeOpacity);+ drawnEnergyTraces = Math.min(energyBudget, energyCandidates.length);+ drawnSparks = Math.min(sparkBudget, sparkCandidates.length);+ drawnNodes = Math.min(nodeBudget, nodeCandidates.length);++ const context = motionContext;+ context.setTransform(1, 0, 0, 1, 0, 0);+ context.clearRect(0, 0, motionCanvas.width, motionCanvas.height);+ context.setTransform(+ motionCanvas.width / field.width, 0,+ 0, motionCanvas.height / field.height, 0, 0,+ );++ const focusWash = context.createRadialGradient(+ focus.x, focus.y, 0,+ focus.x, focus.y, maximumDimension * 0.54,+ );+ focusWash.addColorStop(0, "rgba(0,230,220,.16)");+ focusWash.addColorStop(0.35, "rgba(57,184,255,.075)");+ focusWash.addColorStop(0.72, "rgba(140,107,247,.025)");+ focusWash.addColorStop(1, "rgba(140,107,247,0)");+ context.globalCompositeOperation = "source-over";+ context.globalAlpha = (0.58 + pointerPresence * 0.24) * clamp(strength, 0, 1.2);+ context.fillStyle = focusWash;+ context.fillRect(0, 0, field.width, field.height);++ context.globalCompositeOperation = "lighter";+ context.strokeStyle = brandGradient;+ context.lineWidth = config.traceWidth * featureScale() * 1.18;+ context.lineCap = "round";+ context.lineJoin = "miter";+ context.setLineDash([]);+ for (let index = 0; index < drawnEnergyTraces; index += 1) {+ const visual = energyCandidates[index];+ context.globalAlpha = visual.energyOpacity;+ strokeCanvasPath(context, visual);+ }++ context.lineCap = "round";+ context.lineJoin = "round";+ for (let index = 0; index < drawnSparks; index += 1) {+ const visual = sparkCandidates[index];+ const distance = visual.trace.length + visual.sparkLength;+ const travel = (timestamp * (0.052 + strength * 0.026) + visual.phase * distance) % distance;+ context.setLineDash([visual.sparkLength, distance]);+ context.lineDashOffset = -travel * visual.directionBias;+ context.lineWidth = config.traceWidth * featureScale() * 3.15;+ context.globalAlpha = visual.sparkOpacity * 0.16;+ strokeCanvasPath(context, visual);+ context.lineWidth = config.traceWidth * featureScale() * 1.42;+ context.globalAlpha = visual.sparkOpacity;+ strokeCanvasPath(context, visual);+ }+ context.setLineDash([]);+ context.lineDashOffset = 0;++ const nodeRadius = config.viaInnerRadius * featureScale() * 0.78;+ for (let index = 0; index < drawnNodes; index += 1) {+ const visual = nodeCandidates[index];+ context.fillStyle = visual.nodeColor;+ context.globalAlpha = visual.nodeOpacity * 0.14;+ context.beginPath();+ context.arc(visual.endpoint[0], visual.endpoint[1], nodeRadius * 2.65, 0, Math.PI * 2);+ context.fill();+ context.globalAlpha = visual.nodeOpacity;+ context.beginPath();+ context.arc(visual.endpoint[0], visual.endpoint[1], nodeRadius, 0, Math.PI * 2);+ context.fill();+ }+ context.globalAlpha = 1;+ context.globalCompositeOperation = "source-over";+ }++ function stopMotion() {+ window.cancelAnimationFrame(frameRequest);+ conductor?.stop();+ frameRequest = undefined;+ activeTraces = 0;+ lastFrameTime = 0;+ lastPaintTime = 0;+ }++ function startMotion() {+ stopMotion();+ if (config.animationSystem === "none" || !config.motion || reducedMotion || life() <= 0.02) return;+ if (config.animationSystem === "conductor") {+ conductor?.start();+ return;+ }+ const now = performance.now();+ sceneStart = now - 760;+ nextBloomAt = now + 1180;+ frameCount = 0;+ spawnBloom({ x: field.width * 0.2, y: field.height * 0.64 }, 0.88);+ frameRequest = window.requestAnimationFrame(renderFrame);+ }++ function regenerate(nextOptions = {}) {+ stopMotion();+ config = { ...config, ...nextOptions };+ lastSize = "";+ build(true);+ startMotion();+ return api;+ }++ function exportSvg() {+ const clone = svg.cloneNode(true);+ clone.querySelectorAll("[data-animation]").forEach((layer) => layer.remove());+ clone.removeAttribute("style");+ return `<?xml version="1.0" encoding="UTF-8"?>\n${clone.outerHTML}`;+ }++ function destroy() {+ stopMotion();+ conductor?.destroy();+ conductor = undefined;+ window.clearTimeout(resizeTimer);+ resizeObserver?.disconnect();+ interactionTarget.removeEventListener("pointermove", onPointerMove);+ interactionTarget.removeEventListener("pointerleave", onPointerLeave);+ interactionTarget.removeEventListener("click", onClick);+ motionCanvas?.remove();+ motionCanvas = undefined;+ motionContext = undefined;+ svg?.remove();+ mount.style.position = originalPosition;+ }++ const api = {+ regenerate,+ triggerBloom: spawnBloom,+ triggerAnimation(origin = null) {+ return config.animationSystem === "conductor"+ ? conductor?.trigger(origin)+ : spawnBloom(origin, 1.12);+ },+ exportSvg,+ destroy,+ get field() { return field; },+ get animationStats() {+ if (config.animationSystem === "none") {+ return {+ system: "none",+ animationNodes: 0,+ frameCount: 0,+ reducedMotion,+ };+ }+ if (config.animationSystem === "conductor") return conductor?.stats;+ return {+ system: "adom-routed-field",+ activeTraces,+ activeBlooms: blooms.length,+ bloomsTriggered,+ frameCount,+ renderer: "canvas",+ animationNodes: motionCanvas ? 1 : 0,+ traceCount: visuals.length,+ targetFrameRate,+ rendererPixelRatio,+ energyBudget,+ sparkBudget,+ nodeBudget,+ drawnEnergyTraces,+ drawnSparks,+ drawnNodes,+ reducedMotion,+ };+ },+ };+ build(true);+ resizeObserver = new ResizeObserver(() => {+ window.clearTimeout(resizeTimer);+ resizeTimer = window.setTimeout(() => {+ if (build()) {+ stopMotion();+ startMotion();+ }+ }, 220);+ });+ resizeObserver.observe(mount);+ if (config.interactive) {+ interactionTarget.addEventListener("pointermove", onPointerMove, { passive: true });+ interactionTarget.addEventListener("pointerleave", onPointerLeave, { passive: true });+ interactionTarget.addEventListener("click", onClick);+ }+ startMotion();+ return api;+}++export { DEFAULTS, ANIMATION_PRESETS };
src/circuit-obstacles-v9.jsadded+405@@ -0,0 +1,405 @@+// Worker-safe obstacle geometry for circuit-background-v9.+// The ADOM contour is sourced from adom-elements/src/adom-white.svg.++const ADOM_PATH = "M1065.5,25.22h-58.49c-2.98,0-5.68,1.87-6.73,4.65l-44.4,117.54c-.06.17-.31.17-.37,0l-45.44-117.59c-1.07-2.75-3.76-4.6-6.72-4.6h-58.79c-4.09,0-7.4,3.31-7.4,7.4v35.06l-.03-.12c-1.24,4.99-5.89,6-5.89,6,0,0-4.51,1.02-7.61-2.53v.03c-17.82-29.81-50.31-48.93-89.04-48.93-41.5,0-75.86,21.85-92.76,55.23v-.07c-2.86,5.19-8.74,5.13-8.74,5.13,0,0-5.63-.01-8.41-4.61-16.49-32.68-50.56-52.59-94.79-52.59h-73.46c-4.09,0-7.4,3.31-7.4,7.4v121.27s0,.03,0,.04c-.95,5.15-4.75,5.94-4.75,5.94,0,0-3.88.85-6.77-3.32l.05.23-46.05-126.83c-1.03-2.84-3.75-4.74-6.77-4.74h-57.14c-3.01,0-5.73,1.9-6.76,4.73l-68.67,188.38c-1.05,2.88-.18,6.21,2.4,8.19,1.31,1.01,2.98,1.47,4.64,1.47h34.96s6.43,0,6.43,0c2.5,0,4.83-1.39,5.9-3.65,8.49-17.86,26.5-29.64,48.37-29.64s39.71,11.73,48.19,29.53c1.1,2.32,3.49,3.76,6.06,3.76h120.78c31.22,0,57.85-9.95,77.02-28.77,7.38-7.25,13.43-15.72,18.05-25.1v.09c2.74-5.19,8.37-5.13,8.37-5.13,0,0,5.43,0,8.08,4.64,4.88,9.88,11.26,18.78,18.91,26.42,18.6,18.6,44.61,29.78,74.26,29.78,38.74,0,71.23-19.18,89.05-49.07l-.02.07c3.1-3.55,7.61-2.53,7.61-2.53,0,0,4.65,1,5.89,6l.03-.12v36.32c0,4.09,3.31,7.4,7.4,7.4h45.79c4.09,0,7.4-3.31,7.4-7.4v-86.26c0-.23.32-.28.39-.06l30.37,88.86c1,2.91,3.74,4.87,6.81,4.87h39.69c3.08,0,5.82-1.96,6.81-4.87l30.1-88.02c.07-.21.39-.16.39.06v85.43c0,4.09,3.31,7.4,7.4,7.4h45.79c4.09,0,7.4-3.31,7.4-7.4V32.62c0-4.09-3.31-7.4-7.4-7.4ZM372.31,147.57c-.15.21-.5.57-1.1.57h-30.33c-.61,0-.95-.35-1.1-.56-.15-.21-.38-.65-.19-1.23l15.06-45.79c.27-.81.92-.94,1.29-.94h0c.37,0,1.02.12,1.29.93l15.26,45.8c.19.58-.04,1.01-.19,1.23ZM525.72,173.84h-14.52c-.86,0-1.56-.7-1.56-1.56v-92.16c0-.86.7-1.56,1.56-1.56h14.52c30.81,0,48.48,17.47,48.48,47.92s-17.67,47.36-48.48,47.36ZM734.6,173.26c-26.51,0-42.33-17.71-42.34-47.36,0-14.59,3.88-26.68,11.21-34.98,7.33-8.29,18.09-12.67,31.13-12.67,12.11,0,22.28,3.84,29.58,11.13.5.5.98,1.01,1.45,1.54,7.4,8.33,11.31,20.42,11.31,34.97,0,29.21-16.22,47.36-42.34,47.36Z";++const COMMAND = /^[a-z]$/i;+const NUMBER = /[a-z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi;++function cubicPoint(start, first, second, end, t) {+ const inverse = 1 - t;+ const a = inverse * inverse * inverse;+ const b = 3 * inverse * inverse * t;+ const c = 3 * inverse * t * t;+ const d = t * t * t;+ return [+ a * start[0] + b * first[0] + c * second[0] + d * end[0],+ a * start[1] + b * first[1] + c * second[1] + d * end[1],+ ];+}++function flattenSvgPath(data, curveSteps = 14) {+ const tokens = data.match(NUMBER) || [];+ const rings = [];+ let index = 0;+ let command = null;+ let current = [0, 0];+ let start = [0, 0];+ let previousControl = null;+ let previousCommand = null;+ let ring = [];++ const number = () => Number(tokens[index++]);+ const point = (relative) => {+ const result = [number(), number()];+ if (relative) {+ result[0] += current[0];+ result[1] += current[1];+ }+ return result;+ };+ const finishRing = () => {+ if (ring.length < 3) return;+ const last = ring.at(-1);+ if (last[0] !== start[0] || last[1] !== start[1]) ring.push(start.slice());+ rings.push(ring);+ ring = [];+ };++ while (index < tokens.length) {+ if (COMMAND.test(tokens[index])) command = tokens[index++];+ if (!command) throw new Error("Invalid ADOM path data");+ const relative = command === command.toLowerCase();+ const upper = command.toUpperCase();++ if (upper === "M") {+ if (ring.length) finishRing();+ current = point(relative);+ start = current.slice();+ ring = [current.slice()];+ command = relative ? "l" : "L";+ previousControl = null;+ } else if (upper === "L") {+ current = point(relative);+ ring.push(current.slice());+ previousControl = null;+ } else if (upper === "H") {+ const x = number() + (relative ? current[0] : 0);+ current = [x, current[1]];+ ring.push(current.slice());+ previousControl = null;+ } else if (upper === "V") {+ const y = number() + (relative ? current[1] : 0);+ current = [current[0], y];+ ring.push(current.slice());+ previousControl = null;+ } else if (upper === "C") {+ const first = point(relative);+ const second = point(relative);+ const end = point(relative);+ const origin = current;+ for (let step = 1; step <= curveSteps; step += 1) {+ ring.push(cubicPoint(origin, first, second, end, step / curveSteps));+ }+ current = end;+ previousControl = second;+ } else if (upper === "S") {+ const reflected = previousControl && (previousCommand === "C" || previousCommand === "S")+ ? [2 * current[0] - previousControl[0], 2 * current[1] - previousControl[1]]+ : current.slice();+ const second = point(relative);+ const end = point(relative);+ const origin = current;+ for (let step = 1; step <= curveSteps; step += 1) {+ ring.push(cubicPoint(origin, reflected, second, end, step / curveSteps));+ }+ current = end;+ previousControl = second;+ } else if (upper === "Z") {+ finishRing();+ current = start.slice();+ previousControl = null;+ command = null;+ } else {+ throw new Error(`Unsupported SVG path command: ${command}`);+ }+ previousCommand = upper;+ }+ if (ring.length) finishRing();+ return rings;+}++function boundsOfRings(rings) {+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (const ring of rings) {+ for (const [x, y] of ring) {+ minX = Math.min(minX, x);+ minY = Math.min(minY, y);+ maxX = Math.max(maxX, x);+ maxY = Math.max(maxY, y);+ }+ }+ return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };+}++const ADOM_RINGS = flattenSvgPath(ADOM_PATH);+const ADOM_BOUNDS = boundsOfRings(ADOM_RINGS);++function pointInRing(x, y, ring) {+ let inside = false;+ for (let current = 0, previous = ring.length - 1; current < ring.length; previous = current, current += 1) {+ const [cx, cy] = ring[current];+ const [px, py] = ring[previous];+ if ((cy > y) === (py > y)) continue;+ const crossing = (px - cx) * (y - cy) / (py - cy || Number.EPSILON) + cx;+ if (x < crossing) inside = !inside;+ }+ return inside;+}++function pointInRings(x, y, rings) {+ let inside = false;+ for (const ring of rings) if (pointInRing(x, y, ring)) inside = !inside;+ return inside;+}++function transformWordmark(spec, width, height) {+ const targetWidth = Math.max(24, width * Number(spec.width ?? spec.scale ?? 0.66));+ const targetHeight = targetWidth * ADOM_BOUNDS.height / ADOM_BOUNDS.width;+ const centerX = width * Number(spec.x ?? 0.5);+ const centerY = height * Number(spec.y ?? 0.66);+ const scale = targetWidth / ADOM_BOUNDS.width;+ return ADOM_RINGS.map((ring) => ring.map(([x, y]) => [+ centerX + (x - ADOM_BOUNDS.minX - ADOM_BOUNDS.width / 2) * scale,+ centerY + (y - ADOM_BOUNDS.minY - ADOM_BOUNDS.height / 2) * scale,+ ]));+}++function resolveValue(value, extent, normalized) {+ return Number(value || 0) * (normalized ? extent : 1);+}++function compileGenericObstacle(spec, width, height) {+ const normalized = spec.space !== "world";+ const centerX = resolveValue(spec.x ?? 0.5, width, normalized);+ const centerY = resolveValue(spec.y ?? 0.5, height, normalized);+ const obstacleWidth = Math.max(0, resolveValue(spec.width ?? 0.2, width, normalized));+ const obstacleHeight = Math.max(0, resolveValue(spec.height ?? 0.2, height, normalized));++ if (spec.type === "rect") {+ const left = centerX - obstacleWidth / 2;+ const top = centerY - obstacleHeight / 2;+ const ring = [[left, top], [left + obstacleWidth, top], [left + obstacleWidth, top + obstacleHeight], [left, top + obstacleHeight], [left, top]];+ return { id: spec.id || "rect", rings: [ring], contains: (x, y) => x >= left && x <= left + obstacleWidth && y >= top && y <= top + obstacleHeight };+ }+ if (spec.type === "ellipse") {+ const rx = obstacleWidth / 2;+ const ry = obstacleHeight / 2;+ const ring = Array.from({ length: 97 }, (_, index) => {+ const angle = index / 96 * Math.PI * 2;+ return [centerX + Math.cos(angle) * rx, centerY + Math.sin(angle) * ry];+ });+ return { id: spec.id || "ellipse", rings: [ring], contains: (x, y) => ((x - centerX) / (rx || 1)) ** 2 + ((y - centerY) / (ry || 1)) ** 2 <= 1 };+ }+ const sourceRings = spec.type === "polygon" ? [spec.points || []] : spec.rings || [];+ const rings = sourceRings.map((ring) => {+ const transformed = ring.map(([x, y]) => [resolveValue(x, width, normalized), resolveValue(y, height, normalized)]);+ if (transformed.length && transformed.at(-1).some((value, axis) => value !== transformed[0][axis])) transformed.push(transformed[0].slice());+ return transformed;+ }).filter((ring) => ring.length >= 4);+ return { id: spec.id || spec.type || "shape", rings, contains: (x, y) => pointInRings(x, y, rings) };+}++function normalizeSpecs(config) {+ const specs = Array.isArray(config.obstacles) ? config.obstacles.slice() : [];+ if (config.obstaclePreset === "adom") {+ specs.unshift({+ id: "adom-wordmark",+ type: "wordmark",+ preset: "adom",+ x: Number(config.obstacleX ?? 0.5),+ y: Number(config.obstacleY ?? 0.66),+ width: Number(config.obstacleScale ?? 0.66),+ });+ }+ return specs.filter((spec) => spec && spec.enabled !== false);+}++function compileObstacle(spec, width, height) {+ if (spec.type === "wordmark" || spec.preset === "adom") {+ const rings = transformWordmark(spec, width, height);+ return { id: spec.id || "adom-wordmark", rings, contains: (x, y) => pointInRings(x, y, rings) };+ }+ return compileGenericObstacle(spec, width, height);+}++function dilateMask(source, columns, rows, radius) {+ if (radius <= 0) return source.slice();+ const result = source.slice();+ const offsets = [];+ for (let dy = -radius; dy <= radius; dy += 1) {+ for (let dx = -radius; dx <= radius; dx += 1) {+ if (dx * dx + dy * dy <= radius * radius) offsets.push([dx, dy]);+ }+ }+ for (let y = 1; y < rows - 1; y += 1) {+ for (let x = 1; x < columns - 1; x += 1) {+ if (!source[y * columns + x]) continue;+ for (const [dx, dy] of offsets) {+ const nx = x + dx;+ const ny = y + dy;+ if (nx > 0 && ny > 0 && nx < columns - 1 && ny < rows - 1) result[ny * columns + nx] = 1;+ }+ }+ }+ return result;+}++function distanceField(blocked, columns, rows, band) {+ const unseen = 65535;+ const distance = new Uint16Array(columns * rows);+ distance.fill(unseen);+ const queue = new Int32Array(columns * rows);+ let head = 0;+ let tail = 0;+ for (let index = 0; index < blocked.length; index += 1) {+ if (!blocked[index]) continue;+ distance[index] = 0;+ queue[tail++] = index;+ }+ while (head < tail) {+ const index = queue[head++];+ const nextDistance = distance[index] + 1;+ if (nextDistance > band) continue;+ const x = index % columns;+ const y = Math.floor(index / columns);+ const neighbors = [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]];+ for (const [nx, ny] of neighbors) {+ if (nx < 0 || ny < 0 || nx >= columns || ny >= rows) continue;+ const next = ny * columns + nx;+ if (distance[next] <= nextDistance) continue;+ distance[next] = nextDistance;+ queue[tail++] = next;+ }+ }+ return distance;+}++function rasterizeObstacle(mask, obstacle, pitch, columns, rows) {+ for (let row = 1; row < rows - 1; row += 1) {+ const worldY = row * pitch;+ const intersections = [];+ for (const ring of obstacle.rings) {+ for (let current = 0, previous = ring.length - 1; current < ring.length; previous = current, current += 1) {+ const [cx, cy] = ring[current];+ const [px, py] = ring[previous];+ if ((cy > worldY) === (py > worldY)) continue;+ intersections.push(cx + (px - cx) * (worldY - cy) / (py - cy || Number.EPSILON));+ }+ }+ intersections.sort((left, right) => left - right);+ for (let pair = 0; pair + 1 < intersections.length; pair += 2) {+ const first = Math.max(1, Math.ceil(intersections[pair] / pitch));+ const last = Math.min(columns - 2, Math.floor(intersections[pair + 1] / pitch));+ for (let column = first; column <= last; column += 1) mask[row * columns + column] = 1;+ }+ }+}++export function createObstacleField(config, dimensions) {+ const { width, height, pitch, columns, rows } = dimensions;+ const specs = normalizeSpecs(config);+ if (!specs.length) return null;+ const compiled = specs.map((spec) => compileObstacle(spec, width, height)).filter((item) => item.rings.length);+ if (!compiled.length) return null;++ const inside = new Uint8Array(columns * rows);+ for (const obstacle of compiled) rasterizeObstacle(inside, obstacle, pitch, columns, rows);+ const viaClearance = Math.max(0, Number(config.viaOuterRadius) || 0) / pitch;+ const radius = Math.max(1, Math.ceil(Math.max(0, Number(config.obstacleClearance) || 0) + viaClearance));+ const blocked = dilateMask(inside, columns, rows, radius);+ const band = Math.max(4, Math.ceil(6 + (Number(config.obstaclePull) || 0) * 2));+ const distance = distanceField(blocked, columns, rows, band + 1);+ let blockedCells = 0;+ for (let y = 1; y < rows - 1; y += 1) {+ for (let x = 1; x < columns - 1; x += 1) blockedCells += blocked[y * columns + x];+ }+ return {+ blocked,+ distance,+ band,+ rings: compiled.flatMap((obstacle) => obstacle.rings.map((ring) => ({ id: obstacle.id, points: ring }))),+ count: compiled.length,+ blockedCells,+ mode: config.obstacleMode || "avoid",+ };+}++function sampleClosedRing(points, spacing) {+ const ring = points.slice();+ if (ring.length > 1 && ring[0][0] === ring.at(-1)[0] && ring[0][1] === ring.at(-1)[1]) ring.pop();+ if (ring.length < 3) return [];+ const segments = [];+ let total = 0;+ for (let index = 0; index < ring.length; index += 1) {+ const start = ring[index];+ const end = ring[(index + 1) % ring.length];+ const length = Math.hypot(end[0] - start[0], end[1] - start[1]);+ segments.push({ start, end, length, at: total });+ total += length;+ }+ const count = Math.max(12, Math.ceil(total / spacing));+ const result = [];+ let segmentIndex = 0;+ for (let sample = 0; sample < count; sample += 1) {+ const target = sample / count * total;+ while (segmentIndex < segments.length - 1 && segments[segmentIndex].at + segments[segmentIndex].length < target) segmentIndex += 1;+ const segment = segments[segmentIndex];+ const local = (target - segment.at) / (segment.length || 1);+ result.push([+ segment.start[0] + (segment.end[0] - segment.start[0]) * local,+ segment.start[1] + (segment.end[1] - segment.start[1]) * local,+ ]);+ }+ return result;+}++export function obstacleOutlineTraces(field, options) {+ if (!field || !field.mode.includes("outline")) return [];+ const pitch = options.pitch;+ const spacing = Math.max(2, pitch * 0.48);+ const viaRadius = Math.max(0, Number(options.viaOuterRadius) || 0);+ const traces = [];+ for (let ringIndex = 0; ringIndex < field.rings.length; ringIndex += 1) {+ const ring = field.rings[ringIndex];+ const sampled = sampleClosedRing(ring.points, spacing);+ if (sampled.length < 12) continue;+ let seam = 0;+ for (let index = 1; index < sampled.length; index += 1) {+ if (sampled[index][1] > sampled[seam][1] || (sampled[index][1] === sampled[seam][1] && sampled[index][0] > sampled[seam][0])) seam = index;+ }+ const gap = Math.min(Math.floor(sampled.length * 0.14), Math.max(2, Math.ceil((viaRadius * 2.4 + pitch * 0.45) / spacing)));+ const start = (seam + Math.ceil(gap / 2)) % sampled.length;+ const points = [];+ for (let offset = 0; offset <= sampled.length - gap; offset += 1) points.push(sampled[(start + offset) % sampled.length]);+ if (points.length < 6) continue;+ let length = 0;+ for (let index = 1; index < points.length; index += 1) length += Math.hypot(points[index][0] - points[index - 1][0], points[index][1] - points[index - 1][1]);+ traces.push({+ points,+ length,+ viaStart: true,+ viaEnd: true,+ kind: "obstacle-outline",+ obstacleId: ring.id,+ ringIndex,+ });+ }+ return traces;+}++export function obstacleEdgeWeight(field, x, y, dx, dy, columns, pull) {+ if (!field || !field.mode.includes("wrap") || pull <= 0) return 1;+ const index = y * columns + x;+ const distance = field.distance[index];+ if (!distance || distance > field.band) return 1;+ const left = field.distance[index - 1];+ const right = field.distance[index + 1];+ const up = field.distance[index - columns];+ const down = field.distance[index + columns];+ const gx = Math.min(right, field.band + 1) - Math.min(left, field.band + 1);+ const gy = Math.min(down, field.band + 1) - Math.min(up, field.band + 1);+ const magnitude = Math.hypot(gx, gy);+ if (magnitude < 0.001) return 1;+ const tangent = Math.abs((-gy * dx + gx * dy) / magnitude);+ const normal = Math.abs((gx * dx + gy * dy) / magnitude);+ const proximity = 1 - (distance - 1) / Math.max(1, field.band);+ const attraction = 1 + pull * proximity * (0.55 + tangent * tangent * 3.4);+ const approachPenalty = 1 - Math.min(0.68, pull * proximity * normal * 0.34);+ return Math.max(0.16, attraction * approachPenalty);+}++export const ADOM_WORDMARK_ASPECT = ADOM_BOUNDS.width / ADOM_BOUNDS.height;
src/circuit-reveal-flow.jsadded+391@@ -0,0 +1,391 @@+const SVG_NS = "http://www.w3.org/2000/svg";++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x} ${y}`).join(" ");+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) element.setAttribute(key, String(value));+ return element;+}++function brandColor(x, width) {+ const position = clamp(x / Math.max(1, width));+ if (position < 0.5) return `hsl(${176 + position * 58} 92% 63%)`;+ return `hsl(${205 + (position - 0.5) * 86} 91% 70%)`;+}++function clearRevealStyle(visual) {+ visual.path.setAttribute("d", visual.originalPathData);+ visual.path.removeAttribute("stroke-dasharray");+ visual.path.removeAttribute("stroke-dashoffset");+ visual.path.style.removeProperty("opacity");+ visual.path.style.removeProperty("will-change");+ for (const via of [visual.startVia, visual.endVia]) {+ via?.style.removeProperty("opacity");+ via?.style.removeProperty("will-change");+ }+}++export function createTraceFlowReveal(svg, field, config, random, { traceLayer = null, onComplete = null } = {}) {+ const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ const staticLayer = traceLayer || svg.querySelector("[data-static-traces]");+ const glowLayer = svgElement("g", {+ "data-animation": "trace-growth",+ "aria-hidden": "true",+ });+ glowLayer.style.mixBlendMode = "screen";+ svg.append(glowLayer);++ const traceGroups = [...staticLayer.querySelectorAll("[data-circuit-trace]")];+ const visuals = field.traces.map((trace, index) => {+ const group = traceGroups[index];+ return {+ index,+ trace,+ group,+ path: group.querySelector("[data-trace-path]"),+ startVia: group.querySelector('[data-trace-via="start"]'),+ endVia: group.querySelector('[data-trace-via="end"]'),+ sourceVia: null,+ destinationVia: null,+ overlay: null,+ startedAt: 0,+ duration: 0,+ desiredStart: 0,+ length: Math.max(1, trace.length),+ originalPathData: group.querySelector("[data-trace-path]").getAttribute("d"),+ revealed: true,+ };+ });++ let ordered = [];+ let active = new Map();+ let nextIndex = 0;+ let timelineStart = 0;+ let frameRequest = 0;+ let frameCount = 0;+ let lastFrameTime = 0;+ let running = false;+ let completed = true;++ const scale = Math.max(0.25, config.featureScale || 1);+ const life = clamp(config.revealPower ?? 0.72, 0, 1.5);+ const revealMotion = config.revealMotion !== false;+ const speedFactor = clamp(0.72 + life * 0.36, 0.72, 1.26);+ const glowStrength = clamp((config.revealGlow ?? config.growthGlow ?? 0.82) * (0.68 + life * 0.25), 0, 1.15);+ const requestedMaxActive = Number(config.revealMaxActiveTraces);+ const maxActive = Number.isFinite(requestedMaxActive)+ ? clamp(Math.round(requestedMaxActive), 1, 160)+ : clamp(Math.round(16 + Math.sqrt(visuals.length) * 1.55), 22, 54);+ const targetFrameRate = visuals.length > 1200 ? 30 : visuals.length > 600 ? 45 : 60;+ const frameInterval = 1000 / targetFrameRate;++ function removeOverlay(visual) {+ visual.overlay?.group.remove();+ visual.overlay = null;+ }++ function completeVisual(visual) {+ if (visual.revealed) return;+ clearRevealStyle(visual);+ removeOverlay(visual);+ visual.revealed = true;+ }++ function finish(notify = false) {+ if (completed && !running && active.size === 0) return;+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ running = false;+ completed = true;+ for (const visual of visuals) completeVisual(visual);+ glowLayer.replaceChildren();+ active.clear();+ nextIndex = ordered.length;+ if (notify) onComplete?.();+ }++ function prepareTimeline() {+ const requestedAngle = Number(config.spawnAngle ?? config.revealAngle ?? config.growthAngle);+ const generatedAngle = Number(config.flowAngle);+ const angleDegrees = Number.isFinite(requestedAngle)+ ? requestedAngle+ : Number.isFinite(generatedAngle)+ ? generatedAngle+ : 24;+ const angle = (angleDegrees * Math.PI) / 180;+ const direction = [Math.cos(angle), Math.sin(angle)];+ const across = [-direction[1], direction[0]];+ const span = Math.max(field.width, field.height);+ const phase = random() * Math.PI * 2;+ const requestedSwirl = Number(config.spawnSwirl);+ const swirl = Number.isFinite(requestedSwirl)+ ? clamp(requestedSwirl, 0, 0.35)+ : 0.065;+ const requestedMode = String(config.spawnMode || "flow").toLowerCase();+ const spawnMode = ["flow", "radial", "edges", "scatter"].includes(requestedMode)+ ? requestedMode+ : "flow";+ const radialOffset = Math.min(field.width, field.height) * 0.12;+ const radialCenter = [+ field.width * 0.5 - direction[0] * radialOffset,+ field.height * 0.5 - direction[1] * radialOffset,+ ];+ const flowPotential = (point) => {+ const projection = point[0] * direction[0] + point[1] * direction[1];+ const cross = point[0] * across[0] + point[1] * across[1];+ return projection+ + Math.sin((cross / Math.max(1, span)) * Math.PI * 3.1 + phase) * span * swirl;+ };+ const modePotential = (point) => {+ if (spawnMode === "radial") {+ const offsetX = point[0] - radialCenter[0];+ const offsetY = point[1] - radialCenter[1];+ const distance = Math.hypot(offsetX, offsetY);+ const bearing = Math.atan2(offsetY, offsetX) - angle;+ return distance+ + Math.sin(bearing * 2.6 + (distance / Math.max(1, span)) * Math.PI * 2.2 + phase)+ * span * swirl;+ }+ if (spawnMode === "edges") {+ const edgeDepth = Math.min(+ Math.max(0, point[0]),+ Math.max(0, field.width - point[0]),+ Math.max(0, point[1]),+ Math.max(0, field.height - point[1]),+ );+ const cross = point[0] * across[0] + point[1] * across[1];+ const directionalBias = flowPotential(point) * 0.055;+ return edgeDepth + directionalBias+ + Math.sin((cross / Math.max(1, span)) * Math.PI * 3.1 + phase) * span * swirl;+ }+ return flowPotential(point);+ };+ const entries = visuals.map((visual) => {+ const points = visual.trace.points;+ const first = points[0];+ const last = points.at(-1);+ const midpoint = points[Math.floor(points.length / 2)];+ const reverse = modePotential(first) > modePotential(last);+ const orientedPoints = reverse ? [...points].reverse() : points;+ visual.path.setAttribute("d", pathData(orientedPoints));+ visual.sourceVia = reverse ? visual.endVia : visual.startVia;+ visual.destinationVia = reverse ? visual.startVia : visual.endVia;++ const localVariation = (random() - 0.5) * span * 0.045;+ const key = spawnMode === "scatter"+ ? random() * span+ : modePotential(midpoint) + localVariation;+ return { visual, key };+ });++ entries.sort((first, second) => first.key - second.key || first.visual.index - second.visual.index);+ const minimum = entries[0]?.key || 0;+ const maximum = entries.at(-1)?.key || minimum + 1;+ const duration = clamp(config.revealDuration ?? config.growthDuration ?? 7600, 2600, 18000) / speedFactor;+ const startWindow = Math.max(900, duration - 1750);+ const range = Math.max(1, maximum - minimum);+ const baseDurations = entries.map(({ visual }) => (+ clamp(260 + Math.pow(visual.length, 0.88) * 5.6, 420, 3200) / speedFactor+ ));+ const averageDuration = baseDurations.reduce((sum, value) => sum + value, 0)+ / Math.max(1, baseDurations.length);+ const targetAverage = maxActive * startWindow * 0.82 / Math.max(1, entries.length);+ const durationScale = clamp(targetAverage / Math.max(1, averageDuration), 0.05, 1);+ const minimumDuration = clamp(160 * Math.sqrt(360 / Math.max(1, entries.length)), 52, 180);++ for (const [rank, entry] of entries.entries()) {+ const spatial = clamp((entry.key - minimum) / range);+ const orderedRank = entries.length > 1 ? rank / (entries.length - 1) : 0;+ entry.visual.desiredStart = (spatial * 0.78 + orderedRank * 0.22) * startWindow;+ entry.visual.duration = clamp(+ baseDurations[rank] * durationScale,+ minimumDuration,+ 3200 / speedFactor,+ );+ }+ return entries.map((entry) => entry.visual);+ }++ function prepareVisuals() {+ for (const visual of visuals) {+ removeOverlay(visual);+ visual.path.setAttribute("stroke-dasharray", `${visual.length} ${visual.length + 1}`);+ visual.path.setAttribute("stroke-dashoffset", String(visual.length));+ visual.path.style.opacity = "0";+ visual.revealed = false;+ for (const via of [visual.startVia, visual.endVia]) {+ if (!via) continue;+ via.style.opacity = "0";+ }+ }+ }++ function createOverlay(visual) {+ const color = brandColor(+ visual.trace.points[Math.floor(visual.trace.points.length / 2)][0],+ field.width,+ );+ const headLength = clamp(visual.length * 0.16, 12 * scale, 42 * scale);+ const pathAttributes = {+ d: visual.path.getAttribute("d"),+ fill: "none",+ stroke: color,+ "stroke-linecap": "round",+ "stroke-linejoin": "round",+ "stroke-dasharray": `${headLength} ${visual.length + headLength}`,+ "stroke-dashoffset": headLength,+ };+ const group = svgElement("g", { "data-growth-active": visual.index });+ const halo = svgElement("path", {+ ...pathAttributes,+ "stroke-width": config.traceWidth * scale * 4.2,+ opacity: 0,+ });+ const core = svgElement("path", {+ ...pathAttributes,+ "stroke-width": config.traceWidth * scale * 1.35,+ opacity: 0,+ });+ const source = visual.trace.points[0];+ const destination = visual.trace.points.at(-1);+ const sourcePoint = visual.sourceVia === visual.startVia ? source : destination;+ const destinationPoint = visual.destinationVia === visual.endVia ? destination : source;+ const sourceRing = svgElement("circle", {+ cx: sourcePoint[0], cy: sourcePoint[1], r: config.viaOuterRadius * scale,+ fill: "none", stroke: color, "stroke-width": Math.max(0.8, config.traceWidth * scale), opacity: 0,+ });+ const destinationRing = svgElement("circle", {+ cx: destinationPoint[0], cy: destinationPoint[1], r: config.viaOuterRadius * scale,+ fill: "none", stroke: color, "stroke-width": Math.max(0.8, config.traceWidth * scale), opacity: 0,+ });+ group.append(halo, core, sourceRing, destinationRing);+ glowLayer.append(group);+ return { group, halo, core, sourceRing, destinationRing, headLength };+ }++ function activate(visual, timestamp) {+ visual.startedAt = timestamp;+ visual.overlay = createOverlay(visual);+ active.set(visual.index, visual);+ }++ function drawVisual(visual, timestamp) {+ const progress = clamp((timestamp - visual.startedAt) / visual.duration);+ const routed = smoothstep(progress);+ const drawn = visual.length * routed;+ const energy = Math.sin(Math.PI * progress) * glowStrength;+ const sourceEnergy = 1 - smoothstep(progress / 0.28);+ const destinationEnergy = smoothstep((progress - 0.76) / 0.24);+ const overlay = visual.overlay;++ visual.path.setAttribute("stroke-dashoffset", String(visual.length - drawn));+ visual.path.style.opacity = String(clamp(0.46 + routed * 0.54));+ if (visual.sourceVia) visual.sourceVia.style.opacity = String(smoothstep(progress / 0.12));+ if (visual.destinationVia) visual.destinationVia.style.opacity = String(destinationEnergy);++ const dashOffset = overlay.headLength - drawn;+ overlay.halo.setAttribute("stroke-dashoffset", String(dashOffset));+ overlay.core.setAttribute("stroke-dashoffset", String(dashOffset));+ overlay.halo.setAttribute("opacity", String(energy * 0.16));+ overlay.core.setAttribute("opacity", String(energy * 0.92));+ overlay.sourceRing.setAttribute("r", String(config.viaOuterRadius * scale * (1 + sourceEnergy * 1.9)));+ overlay.sourceRing.setAttribute("opacity", String(sourceEnergy * glowStrength * 0.72));+ overlay.destinationRing.setAttribute("r", String(config.viaOuterRadius * scale * (1 + destinationEnergy * 1.35)));+ overlay.destinationRing.setAttribute("opacity", String((1 - destinationEnergy) * destinationEnergy * 3.2 * glowStrength));++ if (progress < 1) return false;+ completeVisual(visual);+ return true;+ }++ function renderFrame(timestamp) {+ frameRequest = window.requestAnimationFrame(renderFrame);+ const frameElapsed = lastFrameTime ? timestamp - lastFrameTime : frameInterval;+ if (frameElapsed < frameInterval) return;+ lastFrameTime = lastFrameTime+ ? timestamp - (frameElapsed % frameInterval)+ : timestamp;+ frameCount += 1;+ const elapsed = timestamp - timelineStart;++ while (+ nextIndex < ordered.length+ && ordered[nextIndex].desiredStart <= elapsed+ && active.size < maxActive+ ) {+ activate(ordered[nextIndex], timestamp);+ nextIndex += 1;+ }++ for (const [index, visual] of active) {+ if (!drawVisual(visual, timestamp)) continue;+ active.delete(index);+ }++ if (nextIndex >= ordered.length && active.size === 0) finish(true);+ }++ function start() {+ finish();+ ordered = prepareTimeline();+ nextIndex = 0;+ frameCount = 0;+ lastFrameTime = 0;+ if (!revealMotion || reducedMotion || life <= 0.02 || ordered.length === 0) return false;+ prepareVisuals();+ running = true;+ completed = false;+ timelineStart = performance.now();+ frameRequest = window.requestAnimationFrame(renderFrame);+ return true;+ }++ function stop() {+ finish();+ }++ function destroy() {+ finish();+ document.removeEventListener("visibilitychange", onVisibilityChange);+ glowLayer.remove();+ }++ function onVisibilityChange() {+ if (document.hidden && running) finish();+ }++ document.addEventListener("visibilitychange", onVisibilityChange);+ return {+ start,+ stop,+ trigger: start,+ destroy,+ get stats() {+ return {+ system: "trace-flow-sweep",+ animationNodes: glowLayer.childElementCount,+ activeTraces: active.size,+ revealedTraces: nextIndex - active.size,+ traceCount: visuals.length,+ maximumActiveTraces: maxActive,+ targetFrameRate,+ frameCount,+ running,+ completed,+ reducedMotion,+ };+ },+ };+}
src/circuit-reveal-scroll.jsadded+812@@ -0,0 +1,812 @@+const SVG_NS = "http://www.w3.org/2000/svg";+const DEFAULT_TRACE_WINDOW = 0.085;++let instanceCount = 0;++export const SCROLL_REVEAL_DEFAULTS = Object.freeze({+ progressSource: "scroll",+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ spawnOriginX: 0.5,+ spawnOriginY: 0.5,+ traceWindow: DEFAULT_TRACE_WINDOW,+ unlockLead: 0.025,+ maxActiveTraces: 72,+ traceDuration: 950,+ revealLaunchRate: 24,+ scrollSpeedResponse: 0.6,+ revealGlow: 0.82,+ once: true,+ startOffset: 0,+ endOffset: 0,+ autoStart: true,+});++export const TRACE_SPAWN_PRESETS = Object.freeze({+ downstream: Object.freeze({+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ traceWindow: 0.085,+ }),+ diagonal: Object.freeze({+ spawnMode: "flow",+ spawnAngle: 32,+ spawnSwirl: 0.105,+ traceWindow: 0.1,+ }),+ radial: Object.freeze({+ spawnMode: "radial",+ spawnOriginX: 0.5,+ spawnOriginY: 0.46,+ traceWindow: 0.115,+ }),+ scatter: Object.freeze({+ spawnMode: "scatter",+ traceWindow: 0.075,+ }),+});++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function brandColor(x, width) {+ const position = clamp(x / Math.max(1, width));+ if (position < 0.5) return "hsl(" + (176 + position * 58) + " 92% 63%)";+ return "hsl(" + (205 + (position - 0.5) * 86) + " 91% 70%)";+}++function hashSeed(value) {+ let hash = 2166136261;+ for (const character of String(value)) {+ hash ^= character.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function hashUnit(seed, index, salt = 0) {+ let value = seed ^ Math.imul(index + 1, 0x9e3779b1) ^ Math.imul(salt + 1, 0x85ebca6b);+ value = Math.imul(value ^ (value >>> 16), 0x7feb352d);+ value = Math.imul(value ^ (value >>> 15), 0x846ca68b);+ return ((value ^ (value >>> 16)) >>> 0) / 4294967296;+}++function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x} ${y}`).join(" ");+}++function polylineLength(points) {+ let length = 0;+ for (let index = 1; index < points.length; index += 1) {+ length += Math.hypot(+ points[index][0] - points[index - 1][0],+ points[index][1] - points[index - 1][1],+ );+ }+ return Math.max(1, length);+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) {+ element.setAttribute(key, String(value));+ }+ return element;+}++function upperBound(values, target) {+ let low = 0;+ let high = values.length;+ while (low < high) {+ const middle = (low + high) >>> 1;+ if (values[middle] <= target) low = middle + 1;+ else high = middle;+ }+ return low;+}++function mediaListener(media, method, listener) {+ if (media[method]) {+ media[method]("change", listener);+ return;+ }+ const legacyMethod = method === "addEventListener" ? "addListener" : "removeListener";+ media[legacyMethod]?.(listener);+}++/**+ * Queues trace growth as scroll progressively unlocks an existing circuit field.+ *+ * The module owns only its reveal layer. It temporarily hides the source trace+ * layer and restores it on destroy, which keeps it independent from generation+ * and ambient animation systems.+ */+export function createScrollTraceReveal(svg, field, config = {}, options = {}) {+ if (!(svg instanceof SVGElement)) throw new TypeError("svg must be an SVG element");+ if (!field || !Array.isArray(field.traces)) {+ throw new TypeError("field must contain a traces array");+ }++ const settings = {+ ...SCROLL_REVEAL_DEFAULTS,+ ...options,+ };+ const sourceLayer = settings.traceLayer || svg.querySelector("[data-static-traces]");+ if (!sourceLayer) throw new Error("A static circuit trace layer is required");++ const rangeElement = settings.rangeElement || svg.parentElement || svg;+ const scrollRoot = settings.scrollRoot || window;+ const motionPreference = window.matchMedia("(prefers-reduced-motion: reduce)");+ const seed = hashSeed(`${config.seed ?? "adom"}:scroll-reveal:${settings.seed ?? ""}`);+ const featureScale = Math.max(0.25, Number(config.featureScale) || 1);+ const traceWidth = Math.max(0.1, Number(config.traceWidth) || 1);+ const viaOuterRadius = Math.max(traceWidth, Number(config.viaOuterRadius) || traceWidth * 2.2);+ const viaInnerRadius = clamp(+ Number(config.viaInnerRadius) || viaOuterRadius * 0.48,+ 0,+ viaOuterRadius * 0.92,+ );+ const traceColor = config.traceColor || "currentColor";+ const holeColor = settings.holeColor || "var(--circuit-hole, #0d1117)";+ const configuredUnlockLead = Number(settings.unlockLead);+ const unlockLead = clamp(+ Number.isFinite(configuredUnlockLead) ? configuredUnlockLead : 0.025,+ 0,+ 0.25,+ );+ const instanceId = `circuit-scroll-reveal-${++instanceCount}`;+ const viaSymbolId = `${instanceId}-via`;+ const layer = svgElement("g", {+ "data-animation": "scroll-trace-reveal",+ "data-spawn-mode": settings.spawnMode,+ "aria-hidden": "true",+ });+ const definitions = svgElement("defs");+ const viaSymbol = svgElement("g", { id: viaSymbolId });+ viaSymbol.append(+ svgElement("circle", {+ cx: 0,+ cy: 0,+ r: viaOuterRadius * featureScale,+ fill: "currentColor",+ }),+ svgElement("circle", {+ cx: 0,+ cy: 0,+ r: viaInnerRadius * featureScale,+ fill: holeColor,+ }),+ );+ definitions.append(viaSymbol);+ layer.append(definitions);++ const sourceDisplay = sourceLayer.style.getPropertyValue("display");+ const sourceDisplayPriority = sourceLayer.style.getPropertyPriority("display");+ sourceLayer.style.setProperty("display", "none");+ sourceLayer.after(layer);++ const fieldWidth = Math.max(1, Number(field.width) || 1);+ const fieldHeight = Math.max(1, Number(field.height) || 1);+ const span = Math.max(fieldWidth, fieldHeight);+ const angle = (Number(settings.spawnAngle) || 0) * Math.PI / 180;+ const direction = [Math.cos(angle), Math.sin(angle)];+ const across = [-direction[1], direction[0]];+ const phase = hashUnit(seed, 0, 11) * Math.PI * 2;+ const origin = [+ clamp(Number(settings.spawnOriginX), 0, 1) * fieldWidth,+ clamp(Number(settings.spawnOriginY), 0, 1) * fieldHeight,+ ];++ function potential(point, index) {+ if (settings.spawnMode === "scatter") return hashUnit(seed, index, 19);+ if (settings.spawnMode === "radial") {+ const x = (point[0] - origin[0]) / fieldWidth;+ const y = (point[1] - origin[1]) / fieldHeight;+ return Math.hypot(x, y) + (hashUnit(seed, index, 23) - 0.5) * 0.025;+ }+ if (settings.spawnMode === "edges") {+ const edgeDistance = Math.min(+ point[0] / fieldWidth,+ (fieldWidth - point[0]) / fieldWidth,+ point[1] / fieldHeight,+ (fieldHeight - point[1]) / fieldHeight,+ );+ return edgeDistance + (hashUnit(seed, index, 29) - 0.5) * 0.018;+ }+ if (settings.spawnMode === "index") return index;++ const projection = point[0] * direction[0] + point[1] * direction[1];+ const cross = point[0] * across[0] + point[1] * across[1];+ const swirl = clamp(Number(settings.spawnSwirl) || 0, 0, 0.35);+ return projection+ + Math.sin(cross / span * Math.PI * 3.2 + phase) * span * swirl+ + Math.sin((projection + cross * 0.42) / span * Math.PI * 1.7 - phase) * span * swirl * 0.34+ + (hashUnit(seed, index, 31) - 0.5) * span * 0.012;+ }++ const entries = field.traces.map((trace, index) => {+ const originalPoints = trace.points || [];+ if (originalPoints.length < 2) return null;+ const first = originalPoints[0];+ const last = originalPoints.at(-1);+ const middle = originalPoints[Math.floor(originalPoints.length / 2)];+ const orientByPotential = !["scatter", "index"].includes(settings.spawnMode);+ const reverse = orientByPotential+ && potential(first, index) > potential(last, index);+ const points = reverse ? [...originalPoints].reverse() : originalPoints;+ const length = Math.max(1, Number(trace.length) || polylineLength(points));+ return {+ index,+ trace,+ points,+ length,+ key: potential(middle, index),+ color: brandColor(middle[0], fieldWidth),+ };+ }).filter(Boolean);++ entries.sort((first, second) => first.key - second.key || first.index - second.index);+ const maximumActiveTraces = Math.round(clamp(Number(settings.maxActiveTraces) || 72, 12, 160));+ const startDenominator = Math.max(1, entries.length - 1);+ const starts = [];+ const visuals = entries.map((entry, rank) => {+ const start = rank / startDenominator;+ starts.push(start);+ const path = svgElement("path", {+ d: pathData(entry.points),+ fill: "none",+ stroke: traceColor,+ "stroke-width": traceWidth * featureScale,+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ "stroke-dasharray": `${entry.length} ${entry.length + 1}`,+ "stroke-dashoffset": entry.length,+ opacity: 0,+ "data-scroll-trace": entry.index,+ });+ const startVia = svgElement("use", {+ href: `#${viaSymbolId}`,+ transform: `translate(${entry.points[0][0]} ${entry.points[0][1]})`,+ opacity: 0,+ "data-scroll-via": "start",+ color: traceColor,+ });+ const endVia = svgElement("use", {+ href: `#${viaSymbolId}`,+ transform: `translate(${entry.points.at(-1)[0]} ${entry.points.at(-1)[1]})`,+ opacity: 0,+ "data-scroll-via": "end",+ color: traceColor,+ });+ layer.append(path, startVia, endVia);+ return {+ ...entry,+ start,+ path,+ startVia,+ endVia,+ state: "hidden",+ localProgress: -1,+ startedAt: 0,+ duration: 0,+ };+ });++ let running = false;+ let destroyed = false;+ let frameRequest = 0;+ let scrollUpdatePending = false;+ let progress = 0;+ let maximumProgress = 0;+ let visualProgress = 0;+ let reportedProgress = -1;+ let unlockedEnd = 0;+ let launchedEnd = 0;+ let completedCount = 0;+ let settledEnd = 0;+ const pendingSettleRanges = [];+ let pendingSettleCount = 0;+ let launchCredit = 1;+ let previousFrameTime = 0;+ let lastVisualUpdateTime = 0;+ let stoppedAt = 0;+ let hiddenAt = 0;+ let lastScrollPosition;+ let lastScrollTime = 0;+ let scrollVelocity = 0;+ const active = new Set();+ let frameCount = 0;+ let resizeObserver;+ const configuredDurationValue = Number(config.revealDuration);+ const configuredDuration = Number.isFinite(configuredDurationValue) && configuredDurationValue > 0+ ? configuredDurationValue+ : 7600;+ const configuredPower = Number(config.revealPower);+ const revealPower = clamp(Number.isFinite(configuredPower) ? configuredPower : 0.72);+ const revealMotion = config.revealMotion !== false;+ const densityDurationFactor = clamp(+ Math.sqrt(600 / Math.max(1, visuals.length)),+ 0.55,+ 1.15,+ );+ const requestedTraceDuration = Number(settings.traceDuration);+ const baseTraceDuration = Number.isFinite(requestedTraceDuration)+ ? clamp(requestedTraceDuration, 240, 4000)+ : clamp(+ configuredDuration / 8 * (1.08 - revealPower * 0.18) * densityDurationFactor,+ 440,+ 1450,+ );+ const baseLaunchRate = clamp(Number(settings.revealLaunchRate) || 24, 1, 180);+ const speedResponse = clamp(Number(settings.scrollSpeedResponse) || 0, 0, 1.5);+ const glowStrength = clamp(Number(settings.revealGlow) || 0, 0, 1.5);+ const activeFrameInterval = visuals.length > 1200+ ? 1000 / 30+ : visuals.length > 600+ ? 1000 / 45+ : 0;++ function setHidden(visual) {+ if (visual.state === "hidden") return;+ visual.path.setAttribute("stroke-dashoffset", String(visual.length));+ visual.path.setAttribute("opacity", "0");+ visual.path.style.removeProperty("filter");+ visual.startVia.setAttribute("opacity", "0");+ visual.endVia.setAttribute("opacity", "0");+ visual.state = "hidden";+ visual.localProgress = 0;+ visual.startedAt = 0;+ visual.duration = 0;+ }++ function setComplete(visual) {+ if (visual.state === "complete") return;+ visual.path.setAttribute("stroke-dashoffset", "0");+ visual.path.setAttribute("stroke", traceColor);+ visual.startVia.setAttribute("color", traceColor);+ visual.endVia.setAttribute("color", traceColor);+ visual.path.setAttribute("opacity", "1");+ visual.path.style.removeProperty("filter");+ visual.startVia.setAttribute("opacity", "1");+ visual.endVia.setAttribute("opacity", "1");+ visual.state = "complete";+ visual.localProgress = 1;+ }++ function setPartial(visual, amount) {+ const local = smoothstep(amount);+ if (visual.state === "partial" && Math.abs(local - visual.localProgress) < 0.001) return;+ visual.path.setAttribute("stroke-dashoffset", String(visual.length * (1 - local)));+ visual.path.setAttribute("stroke", visual.color);+ visual.startVia.setAttribute("color", visual.color);+ visual.endVia.setAttribute("color", visual.color);+ visual.path.setAttribute("opacity", String(clamp(0.42 + local * 0.58)));+ visual.path.style.filter = glowStrength > 0.01+ ? "drop-shadow(0 0 " + (1.5 + glowStrength * 4 * featureScale) + "px " + visual.color + ")"+ : "none";+ visual.startVia.setAttribute("opacity", String(smoothstep(local / 0.12)));+ visual.endVia.setAttribute("opacity", String(smoothstep((local - 0.82) / 0.18)));+ visual.state = "partial";+ visual.localProgress = local;+ }++ function advanceSettledEnd() {+ while (settledEnd < visuals.length && visuals[settledEnd].state === "complete") {+ settledEnd += 1;+ }+ }++ function reportVisualProgress(force = false) {+ advanceSettledEnd();+ const frontier = visuals[settledEnd];+ const frontierProgress = frontier?.state === "partial"+ ? clamp(frontier.localProgress)+ : 0;+ const nextVisual = visuals.length > 0+ ? (settledEnd + frontierProgress) / visuals.length+ : 1;+ visualProgress = force && nextVisual < visualProgress+ ? nextVisual+ : Math.max(visualProgress, nextVisual);+ if (force || Math.abs(visualProgress - reportedProgress) >= 0.0001) {+ reportedProgress = visualProgress;+ settings.onProgress?.(visualProgress, api);+ }+ }++ function unlock(nextProgress) {+ const nextUnlockedEnd = upperBound(starts, clamp(nextProgress + unlockLead));+ unlockedEnd = Math.max(unlockedEnd, nextUnlockedEnd);+ }++ function launch(visual, now) {+ const speedFactor = 1 - clamp(scrollVelocity / 2.4) * speedResponse * 0.42;+ const lengthFactor = 0.8 + clamp(visual.length / span, 0, 0.55);+ const jitter = 0.88 + hashUnit(seed, visual.index, 41) * 0.24;+ visual.startedAt = now;+ visual.duration = clamp(+ baseTraceDuration * lengthFactor * jitter * speedFactor,+ 360,+ 1750,+ );+ visual.localProgress = -1;+ setPartial(visual, 0);+ active.add(visual);+ launchedEnd += 1;+ }++ function updateActive(now) {+ for (const visual of active) {+ const amount = clamp((now - visual.startedAt) / visual.duration);+ if (amount >= 1) {+ setComplete(visual);+ active.delete(visual);+ completedCount += 1;+ } else {+ setPartial(visual, amount);+ }+ }+ }++ function queueExcessBacklog() {+ const retainedBacklog = maximumActiveTraces * 2;+ const excess = Math.max(0, unlockedEnd - launchedEnd - retainedBacklog);+ if (!excess) return;+ const start = launchedEnd;+ const end = start + excess;+ const previousRange = pendingSettleRanges.at(-1);+ if (previousRange?.end === start) previousRange.end = end;+ else pendingSettleRanges.push({ next: start, end });+ pendingSettleCount += excess;+ launchedEnd = end;+ }++ function materializePendingSettles(limit = 120) {+ let remaining = limit;+ while (remaining > 0 && pendingSettleRanges.length > 0) {+ const range = pendingSettleRanges[0];+ const visual = visuals[range.next];+ setComplete(visual);+ completedCount += 1;+ pendingSettleCount -= 1;+ range.next += 1;+ remaining -= 1;+ if (range.next >= range.end) pendingSettleRanges.shift();+ }+ }++ function launchQueued(now, elapsed) {+ queueExcessBacklog();+ materializePendingSettles(120);+ const speed = clamp(scrollVelocity / 2.4);+ const backlog = clamp(+ (unlockedEnd - launchedEnd) / Math.max(1, maximumActiveTraces * 2),+ );+ const launchRate = Math.min(240,+ baseLaunchRate * (1 + speed * speedResponse * 2.1 + backlog * 0.9),+ );+ launchCredit = Math.min(12, launchCredit + elapsed * launchRate / 1000);+ while (+ launchCredit >= 1+ && launchedEnd < unlockedEnd+ && active.size < maximumActiveTraces+ ) {+ launch(visuals[launchedEnd], now);+ launchCredit -= 1;+ }+ if (launchedEnd >= unlockedEnd) launchCredit = Math.min(1, launchCredit);+ }+++ function scrollMetrics() {+ const rootIsWindow = scrollRoot === window;+ const rootRect = rootIsWindow+ ? { top: 0, height: window.innerHeight }+ : scrollRoot.getBoundingClientRect();+ const elementRect = rangeElement.getBoundingClientRect();+ const scrollPosition = rootIsWindow ? window.scrollY : scrollRoot.scrollTop;+ const viewportHeight = rootIsWindow ? window.innerHeight : scrollRoot.clientHeight;+ const elementTop = elementRect.top - rootRect.top + scrollPosition;+ const elementHeight = elementRect.height;+ const start = Number.isFinite(settings.scrollStart)+ ? settings.scrollStart+ : elementTop + Number(settings.startOffset || 0);+ let end = Number.isFinite(settings.scrollEnd)+ ? settings.scrollEnd+ : elementTop + elementHeight - viewportHeight + Number(settings.endOffset || 0);+ if (end <= start) end = start + Math.max(elementHeight, viewportHeight, 1);+ return {+ start,+ end,+ scrollPosition,+ progress: clamp((scrollPosition - start) / (end - start)),+ };+ }++ function complete() {+ if (destroyed) return api;+ if (+ settledEnd === visuals.length+ && completedCount === visuals.length+ && visualProgress === 1+ ) return api;+ active.clear();+ pendingSettleRanges.length = 0;+ pendingSettleCount = 0;+ unlockedEnd = visuals.length;+ launchedEnd = visuals.length;+ completedCount = visuals.length;+ settledEnd = visuals.length;+ for (const visual of visuals) setComplete(visual);+ maximumProgress = 1;+ progress = 1;+ visualProgress = 1;+ reportVisualProgress(true);+ return api;+ }++ function updateScrollTarget(now = performance.now()) {+ if (destroyed || settings.progressSource === "manual") return;+ const metrics = scrollMetrics();+ if (lastScrollPosition !== undefined && lastScrollTime) {+ const elapsed = Math.max(1, now - lastScrollTime);+ const forwardDelta = Math.max(0, metrics.scrollPosition - lastScrollPosition);+ const instantVelocity = forwardDelta / elapsed;+ scrollVelocity = scrollVelocity * 0.58 + instantVelocity * 0.42;+ }+ lastScrollPosition = metrics.scrollPosition;+ lastScrollTime = now;+ const next = metrics.progress;+ progress = settings.once ? Math.max(maximumProgress, next) : next;+ maximumProgress = Math.max(maximumProgress, next);+ if (!revealMotion || motionPreference.matches) {+ complete();+ return;+ }+ unlock(maximumProgress);+ }++ function renderFrame(now) {+ frameRequest = 0;+ if (destroyed || !running) return;++ if (scrollUpdatePending && settings.progressSource !== "manual") {+ scrollUpdatePending = false;+ updateScrollTarget(now);+ }++ const frameElapsed = previousFrameTime ? clamp(now - previousFrameTime, 0, 64) : 16;+ previousFrameTime = now;+ scrollVelocity *= Math.pow(0.91, frameElapsed / 16.67);++ const visualFrameDue = !activeFrameInterval+ || !lastVisualUpdateTime+ || now - lastVisualUpdateTime >= activeFrameInterval;+ if (visualFrameDue) {+ const visualElapsed = lastVisualUpdateTime+ ? clamp(now - lastVisualUpdateTime, 0, 100)+ : 16;+ lastVisualUpdateTime = now;+ updateActive(now);+ launchQueued(now, visualElapsed);+ reportVisualProgress();+ frameCount += 1;+ }++ if (+ scrollUpdatePending+ || active.size > 0+ || launchedEnd < unlockedEnd+ || pendingSettleCount > 0+ ) {+ scheduleFrame();+ } else {+ previousFrameTime = 0;+ lastVisualUpdateTime = 0;+ }+ }++ function scheduleFrame() {+ if (frameRequest || destroyed || !running) return;+ frameRequest = window.requestAnimationFrame(renderFrame);+ }++ function requestUpdate() {+ if (destroyed || !running) return;+ scrollUpdatePending = true;+ scheduleFrame();+ }++ function setProgress(nextProgress, { remember = settings.once } = {}) {+ if (destroyed) return api;+ const next = clamp(Number(nextProgress) || 0);+ progress = remember ? Math.max(maximumProgress, next) : next;+ maximumProgress = Math.max(maximumProgress, progress);+ if (!revealMotion || motionPreference.matches) {+ complete();+ } else {+ unlock(maximumProgress);+ scheduleFrame();+ }+ return api;+ }++ function refresh() {+ if (destroyed) return api;+ if (settings.progressSource === "manual") {+ if (!revealMotion || motionPreference.matches) complete();+ else {+ unlock(maximumProgress);+ scheduleFrame();+ }+ } else {+ updateScrollTarget();+ scheduleFrame();+ }+ return api;+ }++ function reset() {+ if (destroyed) return api;+ active.clear();+ pendingSettleRanges.length = 0;+ pendingSettleCount = 0;+ for (const visual of visuals) setHidden(visual);+ maximumProgress = 0;+ progress = 0;+ visualProgress = 0;+ reportedProgress = -1;+ unlockedEnd = 0;+ launchedEnd = 0;+ completedCount = 0;+ settledEnd = 0;+ launchCredit = 1;+ previousFrameTime = 0;+ lastVisualUpdateTime = 0;+ scrollVelocity = 0;+ lastScrollPosition = undefined;+ lastScrollTime = 0;+ if (!revealMotion || motionPreference.matches) return complete();+ reportVisualProgress(true);+ return api;+ }++ function onMotionPreferenceChange() {+ if (!revealMotion || motionPreference.matches) complete();+ else refresh();+ }++ function onVisibilityChange() {+ const now = performance.now();+ if (document.hidden) {+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ hiddenAt = now;+ return;+ }+ if (!hiddenAt) return;+ const pausedFor = now - hiddenAt;+ for (const visual of active) visual.startedAt += pausedFor;+ hiddenAt = 0;+ previousFrameTime = 0;+ lastVisualUpdateTime = 0;+ scheduleFrame();+ }++ function start() {+ if (destroyed || running) return api;+ if (stoppedAt) {+ const pausedFor = performance.now() - stoppedAt;+ for (const visual of active) visual.startedAt += pausedFor;+ stoppedAt = 0;+ }+ running = true;+ hiddenAt = document.hidden ? performance.now() : 0;+ document.addEventListener("visibilitychange", onVisibilityChange);+ if (settings.progressSource !== "manual") {+ scrollRoot.addEventListener("scroll", requestUpdate, { passive: true });+ window.addEventListener("resize", requestUpdate, { passive: true });+ resizeObserver = new ResizeObserver(requestUpdate);+ resizeObserver.observe(rangeElement);+ }+ mediaListener(motionPreference, "addEventListener", onMotionPreferenceChange);+ refresh();+ return api;+ }++ function stop() {+ if (!running) return api;+ running = false;+ const stoppedNow = performance.now();+ if (hiddenAt) {+ const hiddenFor = stoppedNow - hiddenAt;+ for (const visual of active) visual.startedAt += hiddenFor;+ hiddenAt = 0;+ }+ stoppedAt = stoppedNow;+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ scrollRoot.removeEventListener("scroll", requestUpdate);+ window.removeEventListener("resize", requestUpdate);+ resizeObserver?.disconnect();+ resizeObserver = undefined;+ mediaListener(motionPreference, "removeEventListener", onMotionPreferenceChange);+ document.removeEventListener("visibilitychange", onVisibilityChange);+ scrollUpdatePending = false;+ previousFrameTime = 0;+ lastVisualUpdateTime = 0;+ return api;+ }++ function destroy() {+ if (destroyed) return;+ stop();+ destroyed = true;+ active.clear();+ pendingSettleRanges.length = 0;+ pendingSettleCount = 0;+ layer.remove();+ if (sourceDisplay) {+ sourceLayer.style.setProperty("display", sourceDisplay, sourceDisplayPriority);+ } else {+ sourceLayer.style.removeProperty("display");+ }+ }++ const api = {+ start,+ stop,+ refresh,+ reset,+ complete,+ setProgress,+ destroy,+ get progress() {+ return progress;+ },+ get visualProgress() {+ return visualProgress;+ },+ get layer() {+ return layer;+ },+ get stats() {+ return {+ system: "scroll-trace-reveal",+ spawnMode: settings.spawnMode,+ progress,+ targetProgress: maximumProgress,+ visualProgress,+ traceCount: visuals.length,+ maximumActiveTraces,+ unlockLead,+ unlockedTraces: unlockedEnd,+ queuedTraces: Math.max(0, unlockedEnd - launchedEnd),+ catchUpTraces: pendingSettleCount,+ hiddenTraces: Math.max(0, visuals.length - completedCount - active.size),+ activeTraces: active.size,+ completedTraces: completedCount,+ settledTraces: settledEnd,+ scrollVelocity,+ animationNodes: layer.childElementCount,+ frameCount,+ running,+ revealMotion,+ reducedMotion: motionPreference.matches,+ };+ },+ };++ if (!revealMotion || motionPreference.matches) complete();+ else reportVisualProgress(true);+ if (settings.autoStart) start();+ return api;+}
src/circuit-reveal-stream-v8.jsadded+1072@@ -0,0 +1,1072 @@+const SVG_NS = "http://www.w3.org/2000/svg";++let instanceCount = 0;++export const STREAM_REVEAL_DEFAULTS = Object.freeze({+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ spawnOriginX: 0.5,+ unlockLead: 0.2,+ traceDuration: 950,+ revealLaunchRate: 24,+ scrollSpeedResponse: 0.72,+ maxActiveTraces: 72,+ maxLaunchesPerFrame: 12,+ maxOldSettlesPerFrame: 48,+ revealGlow: 0.78,+ revealPower: 0.72,+ autoStart: true,+});++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function finiteNumber(value, fallback) {+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+}++function hashSeed(value) {+ let hash = 2166136261;+ for (const character of String(value)) {+ hash ^= character.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function hashUnit(seed, index, salt = 0) {+ let value = seed ^ Math.imul(index + 1, 0x9e3779b1) ^ Math.imul(salt + 1, 0x85ebca6b);+ value = Math.imul(value ^ (value >>> 16), 0x7feb352d);+ value = Math.imul(value ^ (value >>> 15), 0x846ca68b);+ return ((value ^ (value >>> 16)) >>> 0) / 4294967296;+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) {+ element.setAttribute(key, String(value));+ }+ return element;+}++function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x} ${y}`).join(" ");+}++function polylineLength(points) {+ let length = 0;+ for (let index = 1; index < points.length; index += 1) {+ length += Math.hypot(+ points[index][0] - points[index - 1][0],+ points[index][1] - points[index - 1][1],+ );+ }+ return Math.max(1, length);+}++function brandColor(x, width) {+ const position = clamp(x / Math.max(1, width));+ if (position < 0.5) return `hsl(${176 + position * 58} 92% 63%)`;+ return `hsl(${205 + (position - 0.5) * 86} 91% 70%)`;+}++function normalizeVelocity(value, viewportHeight) {+ const velocity = Math.max(0, finiteNumber(value, 0));+ const pixelsPerSecond = velocity > 20 ? velocity : velocity * 1000;+ return pixelsPerSecond / Math.max(1, viewportHeight);+}++/**+ * Reveals an append-only stream of absolute world-space traces.+ *+ * Viewport movement only unlocks work. Once launched, every trace follows its+ * own fixed timeline and never scrubs backward with scroll position.+ */+export function createStreamingTraceReveal(svg, config = {}, options = {}) {+ if (!svg || svg.namespaceURI !== SVG_NS) {+ throw new TypeError("svg must be an SVG element");+ }++ let settings = {+ ...STREAM_REVEAL_DEFAULTS,+ ...config,+ ...options,+ };+ const instanceId = `circuit-stream-reveal-${++instanceCount}`;+ const seed = hashSeed(`${config.seed ?? "adom"}:${settings.seed ?? ""}:stream`);+ const viewBox = svg.viewBox?.baseVal;+ const fieldWidth = Math.max(+ 1,+ finiteNumber(settings.width, viewBox?.width || svg.clientWidth || 1),+ );+ const featureScale = Math.max(0.25, finiteNumber(settings.featureScale, 1));+ const layer = svgElement("g", {+ "data-animation": "stream-trace-reveal",+ "data-spawn-mode": settings.spawnMode,+ "data-export-ready": "true",+ "aria-hidden": "true",+ });+ const pathLayer = svgElement("g", {+ "data-stream-trace-paths": "",+ fill: "none",+ stroke: traceColor(),+ "stroke-width": traceWidth(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ const viaLayer = svgElement("g", {+ "data-stream-trace-vias": "",+ fill: holeColor(),+ stroke: traceColor(),+ "stroke-width": Math.max(0.5, viaOuterRadius() - viaInnerRadius()),+ });+ layer.append(pathLayer, viaLayer);+ svg.append(layer);++ const entries = [];+ const entriesById = new Map();+ const active = new Set();+ const stateCounts = {+ hidden: 0,+ queued: 0,+ active: 0,+ complete: 0,+ };+ let hiddenFrontier = [];+ let hiddenHead = 0;+ let queue = [];+ let queueHead = 0;+ let queueVersion = 0;+ let exhaustedOldQueueVersion = -1;+ let exhaustedOldMinimumMaxY = Number.NEGATIVE_INFINITY;+ let appendIndex = 0;+ let running = false;+ let destroyed = false;+ let frameRequest = 0;+ let previousFrameTime = 0;+ let stoppedAt = 0;+ let launchCredit = 1;+ let viewport = {+ topWorldY: 0,+ bottomWorldY: 0,+ height: 1,+ velocity: 0,+ };+ let hasViewport = false;+ let furthestBottomWorldY = Number.NEGATIVE_INFINITY;+ let generatedFrontier = Number.NEGATIVE_INFINITY;+ let revealedThroughWorldY = Number.NEGATIVE_INFINITY;+ let completedTotal = 0;+ let exportReady = true;+ const reducedMotion = typeof window.matchMedia === "function"+ ? window.matchMedia("(prefers-reduced-motion: reduce)")+ : { matches: false };++ function traceWidth() {+ return Math.max(0.1, finiteNumber(settings.traceWidth, 1)) * featureScale;+ }++ function viaOuterRadius() {+ const baseTraceWidth = Math.max(0.1, finiteNumber(settings.traceWidth, 1));+ return Math.max(+ baseTraceWidth,+ finiteNumber(settings.viaOuterRadius, baseTraceWidth * 2.2),+ ) * featureScale;+ }++ function viaInnerRadius() {+ const baseOuterRadius = viaOuterRadius() / featureScale;+ return clamp(+ finiteNumber(settings.viaInnerRadius, baseOuterRadius * 0.48) * featureScale,+ 0,+ viaOuterRadius() * 0.92,+ );+ }++ function traceColor() {+ return settings.traceColor || "currentColor";+ }++ function holeColor() {+ return settings.holeColor || "var(--circuit-hole, #0d1117)";+ }++ function setRenderAttribute(entry, element, name, value, cacheKey) {+ const textValue = String(value);+ if (entry[cacheKey] === textValue) return;+ element.setAttribute(name, textValue);+ entry[cacheKey] = textValue;+ }++ function applyActiveStyles(entry, glow) {+ if (!entry.hasActiveStyles) {+ entry.path.setAttribute("stroke", entry.activeColor);+ entry.startVia.setAttribute("fill", entry.hiddenHoleColor);+ entry.endVia.setAttribute("fill", entry.hiddenHoleColor);+ entry.startVia.setAttribute("stroke", entry.activeColor);+ entry.endVia.setAttribute("stroke", entry.activeColor);+ entry.hasActiveStyles = true;+ }+ if (entry.activeGlow === glow) return;+ if (glow > 0.01) {+ entry.path.style.filter = `drop-shadow(0 0 ${1.5 + glow * 4 * featureScale}px ${entry.activeColor})`;+ entry.hasGlowFilter = true;+ } else if (entry.hasGlowFilter) {+ entry.path.style.removeProperty("filter");+ entry.hasGlowFilter = false;+ }+ entry.activeGlow = glow;+ }++ function clearActiveStyles(entry) {+ if (entry.hasActiveStyles) {+ entry.path.removeAttribute("stroke");+ entry.startVia.removeAttribute("fill");+ entry.endVia.removeAttribute("fill");+ entry.startVia.removeAttribute("stroke");+ entry.endVia.removeAttribute("stroke");+ entry.hasActiveStyles = false;+ }+ if (entry.hasGlowFilter) {+ entry.path.style.removeProperty("filter");+ entry.hasGlowFilter = false;+ }+ entry.activeGlow = Number.NaN;+ }++ function spawnMetadata(entry) {+ const points = entry.originalPoints;+ const middle = points[Math.floor(points.length / 2)];+ const localSpan = Math.max(1, entry.maxY - entry.minY, fieldWidth * 0.08);+ const originX = clamp(finiteNumber(settings.spawnOriginX, 0.5)) * fieldWidth;+ const angle = finiteNumber(settings.spawnAngle, 90) * Math.PI / 180;+ const direction = [Math.cos(angle), Math.sin(angle)];+ const across = [-direction[1], direction[0]];+ const swirl = clamp(finiteNumber(settings.spawnSwirl, 0.075), 0, 0.5);+ const phase = hashUnit(seed, entry.hashIndex, 11) * Math.PI * 2;+ const normalizedPoint = (point) => [+ (point[0] - fieldWidth * 0.5) / fieldWidth,+ (point[1] - entry.minY) / localSpan - 0.5,+ ];+ const potential = (point) => {+ const normalized = normalizedPoint(point);+ if (settings.spawnMode === "radial") {+ return Math.hypot(+ (point[0] - originX) / fieldWidth,+ normalized[1] * 0.55,+ );+ }+ if (settings.spawnMode === "edges") {+ return Math.min(+ point[0] / fieldWidth,+ (fieldWidth - point[0]) / fieldWidth,+ Math.abs(normalized[1] + 0.5),+ Math.abs(0.5 - normalized[1]),+ );+ }+ if (settings.spawnMode === "scatter") {+ return hashUnit(seed, entry.hashIndex, 19);+ }+ if (settings.spawnMode === "index") return entry.hashIndex;+ return normalized[0] * direction[0] + normalized[1] * direction[1];+ };++ const orientByPotential = !["scatter", "index"].includes(settings.spawnMode);+ const reverse = orientByPotential+ && potential(points[0]) > potential(points.at(-1));+ const orientedPoints = reverse ? [...points].reverse() : points;+ const normalizedMiddle = normalizedPoint(middle);+ let offsetUnit;+ if (settings.spawnMode === "radial") {+ offsetUnit = Math.hypot((middle[0] - originX) / fieldWidth, normalizedMiddle[1] * 0.4) - 0.28;+ } else if (settings.spawnMode === "edges") {+ offsetUnit = Math.min(middle[0], fieldWidth - middle[0]) / fieldWidth - 0.2;+ } else if (settings.spawnMode === "scatter") {+ offsetUnit = hashUnit(seed, entry.hashIndex, 23) * 2 - 1;+ } else if (settings.spawnMode === "index") {+ offsetUnit = (hashUnit(seed, entry.hashIndex, 29) - 0.5) * 0.6;+ } else {+ const projection = normalizedMiddle[0] * direction[0] + normalizedMiddle[1] * direction[1];+ const cross = normalizedMiddle[0] * across[0] + normalizedMiddle[1] * across[1];+ offsetUnit = cross * 0.7+ + Math.sin(projection * Math.PI * 2.2 + phase) * swirl+ + Math.sin(cross * Math.PI * 3.1 - phase) * swirl * 0.38;+ }+ return {+ points: orientedPoints,+ offsetUnit: clamp(offsetUnit, -1, 1),+ orderJitter: hashUnit(seed, entry.hashIndex, 31),+ };+ }++ function applyGeometry(entry) {+ const metadata = spawnMetadata(entry);+ entry.points = metadata.points;+ entry.offsetUnit = metadata.offsetUnit;+ entry.orderJitter = metadata.orderJitter;+ entry.activeColor = brandColor(+ entry.points[Math.floor(entry.points.length / 2)][0],+ fieldWidth,+ );+ entry.path.setAttribute("d", pathData(entry.points));+ entry.startVia.setAttribute(+ "transform",+ `translate(${entry.points[0][0]} ${entry.points[0][1]})`,+ );+ entry.endVia.setAttribute(+ "transform",+ `translate(${entry.points.at(-1)[0]} ${entry.points.at(-1)[1]})`,+ );+ }++ function transitionState(entry, nextState) {+ const previousState = entry.state;+ if (previousState === nextState) return;+ if (previousState && Object.hasOwn(stateCounts, previousState)) {+ stateCounts[previousState] -= 1;+ }+ if (nextState && Object.hasOwn(stateCounts, nextState)) {+ stateCounts[nextState] += 1;+ }+ entry.state = nextState;+ }++ function setHidden(entry) {+ active.delete(entry);+ entry.hiddenHoleColor = holeColor();+ setRenderAttribute(entry, entry.path, "stroke-dashoffset", entry.length, "pathOffset");+ setRenderAttribute(entry, entry.path, "opacity", 0, "pathOpacity");+ clearActiveStyles(entry);+ setRenderAttribute(entry, entry.startVia, "opacity", 0, "startViaOpacity");+ setRenderAttribute(entry, entry.endVia, "opacity", 0, "endViaOpacity");+ transitionState(entry, "hidden");+ entry.progress = 0;+ entry.startedAt = 0;+ entry.duration = 0;+ }++ function setPartial(entry, amount) {+ const progress = smoothstep(amount);+ const power = clamp(finiteNumber(settings.revealPower, 0.72), 0, 1.5);+ const glow = clamp(finiteNumber(settings.revealGlow, 0.78), 0, 1.5);+ applyActiveStyles(entry, glow);+ setRenderAttribute(+ entry,+ entry.path,+ "stroke-dashoffset",+ entry.length * (1 - progress),+ "pathOffset",+ );+ setRenderAttribute(+ entry,+ entry.path,+ "opacity",+ clamp(0.38 + progress * 0.62),+ "pathOpacity",+ );+ setRenderAttribute(+ entry,+ entry.startVia,+ "opacity",+ smoothstep((progress + 0.03) / 0.1),+ "startViaOpacity",+ );+ setRenderAttribute(+ entry,+ entry.endVia,+ "opacity",+ smoothstep((progress - 0.82 + power * 0.025) / 0.16),+ "endViaOpacity",+ );+ if (entry.state !== "active") transitionState(entry, "active");+ entry.progress = progress;+ }++ function setComplete(entry) {+ if (entry.state === "complete") return;+ active.delete(entry);+ setRenderAttribute(entry, entry.path, "stroke-dashoffset", 0, "pathOffset");+ setRenderAttribute(entry, entry.path, "opacity", 1, "pathOpacity");+ clearActiveStyles(entry);+ setRenderAttribute(entry, entry.startVia, "opacity", 1, "startViaOpacity");+ setRenderAttribute(entry, entry.endVia, "opacity", 1, "endViaOpacity");+ transitionState(entry, "complete");+ entry.progress = 1;+ completedTotal += 1;+ revealedThroughWorldY = Math.max(revealedThroughWorldY, entry.maxY);+ }++ function unlockY(entry) {+ const localOffsetBound = viewport.height * 0.32;+ return entry.minY + entry.offsetUnit * localOffsetBound;+ }++ function updateUnlockKey(entry) {+ entry.unlockWorldY = unlockY(entry);+ return entry.unlockWorldY;+ }++ function compareRevealOrder(first, second) {+ return first.unlockWorldY - second.unlockWorldY+ || first.orderJitter - second.orderJitter+ || first.hashIndex - second.hashIndex;+ }++ function compactHiddenFrontier() {+ hiddenFrontier = hiddenFrontier+ .slice(hiddenHead)+ .filter((entry) => entry.state === "hidden");+ hiddenHead = 0;+ }++ function addToHiddenFrontier(newEntries) {+ if (!newEntries.length) return;+ for (const entry of newEntries) updateUnlockKey(entry);+ newEntries.sort(compareRevealOrder);++ if (hiddenHead >= hiddenFrontier.length) {+ hiddenFrontier = newEntries;+ hiddenHead = 0;+ return;+ }++ const lastPending = hiddenFrontier.at(-1);+ if (compareRevealOrder(lastPending, newEntries[0]) <= 0) {+ hiddenFrontier.push(...newEntries);+ return;+ }++ compactHiddenFrontier();+ const merged = [];+ let currentIndex = 0;+ let newIndex = 0;+ while (currentIndex < hiddenFrontier.length && newIndex < newEntries.length) {+ if (compareRevealOrder(hiddenFrontier[currentIndex], newEntries[newIndex]) <= 0) {+ merged.push(hiddenFrontier[currentIndex]);+ currentIndex += 1;+ } else {+ merged.push(newEntries[newIndex]);+ newIndex += 1;+ }+ }+ merged.push(+ ...hiddenFrontier.slice(currentIndex),+ ...newEntries.slice(newIndex),+ );+ hiddenFrontier = merged;+ }++ function rebuildEligibilityIndex() {+ hiddenFrontier = [];+ hiddenHead = 0;+ for (const entry of entries) {+ if (entry.state === "hidden" || entry.state === "queued") {+ updateUnlockKey(entry);+ }+ if (entry.state === "hidden") hiddenFrontier.push(entry);+ }+ hiddenFrontier.sort(compareRevealOrder);+ if (queueHead < queue.length) sortQueue();+ }++ function compactQueue() {+ queue = queue+ .slice(queueHead)+ .filter((entry) => entry.state === "queued");+ queueHead = 0;+ }++ function sortQueue() {+ compactQueue();+ queue.sort(compareRevealOrder);+ }++ function addToQueue(newEntries) {+ if (!newEntries.length) return;+ queueVersion += 1;+ if (queueHead >= queue.length) {+ queue = newEntries;+ queueHead = 0;+ return;+ }++ const lastPending = queue.at(-1);+ if (compareRevealOrder(lastPending, newEntries[0]) <= 0) {+ queue.push(...newEntries);+ return;+ }++ compactQueue();+ const merged = [];+ let currentIndex = 0;+ let newIndex = 0;+ while (currentIndex < queue.length && newIndex < newEntries.length) {+ if (compareRevealOrder(queue[currentIndex], newEntries[newIndex]) <= 0) {+ merged.push(queue[currentIndex]);+ currentIndex += 1;+ } else {+ merged.push(newEntries[newIndex]);+ newIndex += 1;+ }+ }+ merged.push(...queue.slice(currentIndex), ...newEntries.slice(newIndex));+ queue = merged;+ }++ function evaluateEligibility() {+ if (!hasViewport || destroyed) return;+ const lead = clamp(finiteNumber(settings.unlockLead, 0.2), 0, 3) * viewport.height;+ const eligibleThrough = furthestBottomWorldY + lead;+ const newlyQueued = [];+ while (hiddenHead < hiddenFrontier.length) {+ const entry = hiddenFrontier[hiddenHead];+ if (entry.unlockWorldY > eligibleThrough) break;+ hiddenHead += 1;+ if (entry.state !== "hidden") continue;+ transitionState(entry, "queued");+ newlyQueued.push(entry);+ }+ addToQueue(newlyQueued);+ if (hiddenHead > 2048 && hiddenHead > hiddenFrontier.length / 2) {+ compactHiddenFrontier();+ }+ if (settings.revealMotion === false || reducedMotion.matches) {+ for (let index = queueHead; index < queue.length; index += 1) {+ setComplete(queue[index]);+ }+ compactQueue();+ }+ updateExportReadiness();+ }++ function baseTraceDuration() {+ const explicit = finiteNumber(settings.traceDuration, Number.NaN);+ const fallback = finiteNumber(settings.revealDuration, STREAM_REVEAL_DEFAULTS.traceDuration);+ return clamp(Number.isFinite(explicit) ? explicit : fallback, 120, 12000);+ }++ function launch(entry, now) {+ const viewportsPerSecond = normalizeVelocity(viewport.velocity, viewport.height);+ const response = clamp(finiteNumber(settings.scrollSpeedResponse, 0.72), 0, 2);+ const speedAmount = clamp(viewportsPerSecond / 2.2);+ const speedDurationFactor = 1 - clamp(speedAmount * response * 0.2, 0, 0.32);+ const lengthReference = Math.max(80, viewport.height * 0.55);+ const lengthFactor = clamp(0.78 + entry.length / lengthReference * 0.22, 0.78, 1.35);+ const jitter = 0.88 + hashUnit(seed, entry.hashIndex, 41) * 0.24;+ entry.startedAt = now;+ entry.duration = clamp(+ baseTraceDuration() * lengthFactor * jitter * speedDurationFactor,+ 120,+ 12000,+ );+ setPartial(entry, 0);+ active.add(entry);+ }++ function settleOldQueue() {+ const pendingCount = queue.length - queueHead;+ if (!pendingCount) return;+ const maximumActive = Math.round(clamp(+ finiteNumber(settings.maxActiveTraces, 72),+ 1,+ 320,+ ));+ const backlogLimit = maximumActive * 3;+ if (pendingCount <= backlogLimit) return;+ const settleLimit = Math.round(clamp(+ finiteNumber(settings.maxOldSettlesPerFrame, 48),+ 1,+ 240,+ ));+ const oldThreshold = viewport.topWorldY - viewport.height * 0.2;+ // Generated circuit traces live at non-negative world coordinates. Until+ // the viewport has passed the first fifth of a screen, no queued trace can+ // be old, so scanning Dense's entire queue every frame cannot change state.+ if (oldThreshold <= 0) return;+ // A complete scan records the lowest maxY still queued. Queue removals can+ // only raise that bound, so repeat the scan only after the old cutoff passes+ // it or newly eligible traces join the queue.+ if (+ exhaustedOldQueueVersion === queueVersion+ && oldThreshold <= exhaustedOldMinimumMaxY+ ) return;++ let settled = 0;+ let exhausted = true;+ let minimumRemainingMaxY = Number.POSITIVE_INFINITY;+ for (let index = queueHead; index < queue.length; index += 1) {+ if (pendingCount - settled <= backlogLimit || settled >= settleLimit) {+ exhausted = false;+ break;+ }+ const entry = queue[index];+ if (entry.state !== "queued") continue;+ if (entry.maxY >= oldThreshold) {+ minimumRemainingMaxY = Math.min(minimumRemainingMaxY, entry.maxY);+ continue;+ }+ setComplete(entry);+ settled += 1;+ }+ if (settled) compactQueue();+ if (exhausted) {+ exhaustedOldQueueVersion = queueVersion;+ exhaustedOldMinimumMaxY = minimumRemainingMaxY;+ }+ }++ function launchQueued(now, elapsed) {+ settleOldQueue();+ const maximumActive = Math.round(clamp(+ finiteNumber(settings.maxActiveTraces, 72),+ 1,+ 320,+ ));+ const viewportsPerSecond = normalizeVelocity(viewport.velocity, viewport.height);+ const response = clamp(finiteNumber(settings.scrollSpeedResponse, 0.72), 0, 2);+ const speedAmount = clamp(viewportsPerSecond / 2);+ const baseRate = clamp(finiteNumber(settings.revealLaunchRate, 24), 0.5, 240);+ const launchRate = Math.min(360, baseRate * (1 + speedAmount * response * 2.2));+ const maximumLaunches = Math.round(clamp(+ finiteNumber(settings.maxLaunchesPerFrame, 12),+ 1,+ 48,+ ));+ launchCredit = Math.min(maximumLaunches, launchCredit + elapsed * launchRate / 1000);+ let launched = 0;+ while (+ launchCredit >= 1+ && launched < maximumLaunches+ && active.size < maximumActive+ && queueHead < queue.length+ ) {+ const entry = queue[queueHead];+ queueHead += 1;+ if (entry.state !== "queued") continue;+ launch(entry, now);+ launchCredit -= 1;+ launched += 1;+ }+ if (queueHead >= queue.length) {+ queue.length = 0;+ queueHead = 0;+ launchCredit = Math.min(1, launchCredit);+ } else if (queueHead > 1024 && queueHead > queue.length / 2) {+ compactQueue();+ }+ }++ function updateActive(now) {+ for (const entry of active) {+ const amount = clamp((now - entry.startedAt) / Math.max(1, entry.duration));+ if (amount >= 1) setComplete(entry);+ else setPartial(entry, amount);+ }+ }++ function updateExportReadiness() {+ const ready = active.size === 0 && queueHead >= queue.length;+ if (ready === exportReady) return;+ exportReady = ready;+ layer.setAttribute("data-export-ready", String(ready));+ }++ function renderFrame(now) {+ frameRequest = 0;+ if (!running || destroyed) return;+ const elapsed = previousFrameTime ? clamp(now - previousFrameTime, 0, 80) : 16;+ previousFrameTime = now;+ updateActive(now);+ launchQueued(now, elapsed);+ viewport.velocity *= Math.pow(0.9, elapsed / 16.67);+ updateExportReadiness();+ if (active.size > 0 || queueHead < queue.length) scheduleFrame();+ else previousFrameTime = 0;+ }++ function scheduleFrame() {+ if (!running || destroyed || frameRequest) return;+ frameRequest = window.requestAnimationFrame(renderFrame);+ }++ function appendTraces(traces) {+ if (destroyed) return api;+ if (!Array.isArray(traces)) throw new TypeError("traces must be an array");+ const pathFragment = document.createDocumentFragment();+ const viaFragment = document.createDocumentFragment();+ const newEntries = [];+ const viaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ for (const trace of traces) {+ if (!trace || !Array.isArray(trace.points) || trace.points.length < 2) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const id = String(trace.id ?? appendIndex);+ if (entriesById.has(id)) throw new Error(`duplicate streaming trace id: ${id}`);+ let originalPoints = trace.points;+ let normalizedPoints = null;+ let derivedMinY = Number.POSITIVE_INFINITY;+ let derivedMaxY = Number.NEGATIVE_INFINITY;+ for (let pointIndex = 0; pointIndex < trace.points.length; pointIndex += 1) {+ const point = trace.points[pointIndex];+ if (!Array.isArray(point) || point.length < 2) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const x = Number(point[0]);+ const y = Number(point[1]);+ if (!Number.isFinite(x) || !Number.isFinite(y)) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const reusable = point.length === 2+ && typeof point[0] === "number"+ && typeof point[1] === "number";+ if (!reusable && !normalizedPoints) {+ normalizedPoints = trace.points.slice(0, pointIndex)+ .map((previous) => [Number(previous[0]), Number(previous[1])]);+ }+ normalizedPoints?.push([x, y]);+ derivedMinY = Math.min(derivedMinY, y);+ derivedMaxY = Math.max(derivedMaxY, y);+ }+ if (normalizedPoints) originalPoints = normalizedPoints;+ const minY = finiteNumber(trace.minY, derivedMinY);+ const maxY = finiteNumber(trace.maxY, derivedMaxY);+ const suppliedLength = Number(trace.length);+ const length = Math.max(+ 1,+ Number.isFinite(suppliedLength) ? suppliedLength : polylineLength(originalPoints),+ );+ const path = svgElement("path", {+ "stroke-dasharray": `${length} ${length + 1}`,+ "data-stream-trace": id,+ });+ const viaAttributes = {+ cx: 0,+ cy: 0,+ r: viaRadius,+ };+ const startVia = svgElement("circle", {+ ...viaAttributes,+ "data-stream-via": "start",+ "data-trace-id": id,+ });+ const endVia = svgElement("circle", {+ ...viaAttributes,+ "data-stream-via": "end",+ "data-trace-id": id,+ });+ const entry = {+ id,+ hashIndex: appendIndex,+ trace,+ originalPoints,+ points: originalPoints,+ length,+ minY: Math.min(minY, maxY),+ maxY: Math.max(minY, maxY),+ path,+ startVia,+ endVia,+ offsetUnit: 0,+ orderJitter: 0,+ state: null,+ progress: 0,+ startedAt: 0,+ duration: 0,+ };+ appendIndex += 1;+ applyGeometry(entry);+ setHidden(entry);+ entries.push(entry);+ newEntries.push(entry);+ entriesById.set(id, entry);+ pathFragment.append(path);+ viaFragment.append(startVia, endVia);+ generatedFrontier = Math.max(generatedFrontier, entry.maxY);+ }+ pathLayer.append(pathFragment);+ viaLayer.append(viaFragment);+ addToHiddenFrontier(newEntries);+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function pruneBefore(worldY) {+ if (destroyed) return 0;+ const threshold = finiteNumber(worldY, Number.NEGATIVE_INFINITY);+ let removed = 0;+ let retained = 0;+ for (const entry of entries) {+ if (entry.state === "complete" && entry.maxY < threshold && !active.has(entry)) {+ entry.path.remove();+ entry.startVia.remove();+ entry.endVia.remove();+ entriesById.delete(entry.id);+ transitionState(entry, null);+ removed += 1;+ } else {+ entries[retained] = entry;+ retained += 1;+ }+ }+ entries.length = retained;+ updateExportReadiness();+ return removed;+ }++ function setViewport(nextViewport = {}) {+ if (destroyed) return api;+ const height = Math.max(1, finiteNumber(+ nextViewport.height,+ finiteNumber(nextViewport.bottomWorldY, viewport.bottomWorldY)+ - finiteNumber(nextViewport.topWorldY, viewport.topWorldY),+ ));+ const heightChanged = height !== viewport.height;+ const topWorldY = finiteNumber(nextViewport.topWorldY, viewport.topWorldY);+ const bottomWorldY = finiteNumber(nextViewport.bottomWorldY, topWorldY + height);+ viewport = {+ topWorldY,+ bottomWorldY: Math.max(topWorldY, bottomWorldY),+ height,+ velocity: Math.max(0, finiteNumber(nextViewport.velocity, 0)),+ };+ if (heightChanged) rebuildEligibilityIndex();+ hasViewport = true;+ furthestBottomWorldY = Math.max(furthestBottomWorldY, viewport.bottomWorldY);+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function updateOptions(next = {}) {+ if (destroyed) return api;+ const previousSpawnMode = settings.spawnMode;+ const previousSpawnAngle = settings.spawnAngle;+ const previousSpawnSwirl = settings.spawnSwirl;+ const previousSpawnOriginX = settings.spawnOriginX;+ const previousTraceWidth = traceWidth();+ const previousViaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ const previousViaStrokeWidth = Math.max(0.5, viaOuterRadius() - viaInnerRadius());+ const previousTraceColor = traceColor();+ const previousHoleColor = holeColor();+ settings = { ...settings, ...next };+ const nextTraceWidth = traceWidth();+ const nextViaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ const nextViaStrokeWidth = Math.max(0.5, viaOuterRadius() - viaInnerRadius());+ const nextTraceColor = traceColor();+ const nextHoleColor = holeColor();+ const spawnChanged = previousSpawnMode !== settings.spawnMode+ || previousSpawnAngle !== settings.spawnAngle+ || previousSpawnSwirl !== settings.spawnSwirl+ || previousSpawnOriginX !== settings.spawnOriginX;++ if (previousSpawnMode !== settings.spawnMode) {+ layer.setAttribute("data-spawn-mode", settings.spawnMode);+ }+ if (previousTraceWidth !== nextTraceWidth) {+ pathLayer.setAttribute("stroke-width", String(nextTraceWidth));+ }+ if (previousViaStrokeWidth !== nextViaStrokeWidth) {+ viaLayer.setAttribute("stroke-width", String(nextViaStrokeWidth));+ }+ if (previousTraceColor !== nextTraceColor) {+ pathLayer.setAttribute("stroke", nextTraceColor);+ viaLayer.setAttribute("stroke", nextTraceColor);+ }+ if (previousHoleColor !== nextHoleColor) {+ viaLayer.setAttribute("fill", nextHoleColor);+ }+ if (previousViaRadius !== nextViaRadius) {+ for (const entry of entries) {+ entry.startVia.setAttribute("r", String(nextViaRadius));+ entry.endVia.setAttribute("r", String(nextViaRadius));+ }+ }+ if (spawnChanged) {+ for (const entry of entries) {+ if (entry.state === "hidden" || entry.state === "queued") applyGeometry(entry);+ }+ rebuildEligibilityIndex();+ }+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function complete() {+ if (destroyed) return api;+ active.clear();+ queue.length = 0;+ queueHead = 0;+ hiddenFrontier.length = 0;+ hiddenHead = 0;+ for (const entry of entries) setComplete(entry);+ furthestBottomWorldY = Math.max(furthestBottomWorldY, generatedFrontier);+ updateExportReadiness();+ return api;+ }++ function start() {+ if (destroyed || running) return api;+ const now = performance.now();+ if (stoppedAt) {+ const pauseDuration = now - stoppedAt;+ for (const entry of active) entry.startedAt += pauseDuration;+ }+ stoppedAt = 0;+ running = true;+ previousFrameTime = 0;+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function stop() {+ if (destroyed || !running) return api;+ running = false;+ stoppedAt = performance.now();+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ previousFrameTime = 0;+ return api;+ }++ function reset() {+ if (destroyed) return api;+ active.clear();+ queue.length = 0;+ queueHead = 0;+ completedTotal = 0;+ revealedThroughWorldY = Number.NEGATIVE_INFINITY;+ launchCredit = 1;+ for (const entry of entries) {+ applyGeometry(entry);+ setHidden(entry);+ }+ rebuildEligibilityIndex();+ furthestBottomWorldY = hasViewport+ ? viewport.bottomWorldY+ : Number.NEGATIVE_INFINITY;+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function stats() {+ return {+ retained: entries.length,+ unlocked: entries.length - stateCounts.hidden,+ queued: stateCounts.queued,+ active: active.size,+ completed: stateCounts.complete,+ completedTotal,+ generatedFrontier: Number.isFinite(generatedFrontier) ? generatedFrontier : null,+ revealedThroughWorldY: Number.isFinite(revealedThroughWorldY)+ ? revealedThroughWorldY+ : null,+ velocity: viewport.velocity,+ };+ }++ function exportState() {+ const settled = entries+ .filter((entry) => entry.state === "complete")+ .map((entry) => ({+ id: entry.id,+ points: entry.points.map((point) => [...point]),+ length: entry.length,+ minY: entry.minY,+ maxY: entry.maxY,+ }));+ return {+ ready: active.size === 0 && queueHead >= queue.length,+ generatedFrontier: Number.isFinite(generatedFrontier) ? generatedFrontier : null,+ revealedThroughWorldY: Number.isFinite(revealedThroughWorldY)+ ? revealedThroughWorldY+ : null,+ traces: settled,+ };+ }++ function createExportLayer() {+ const exportLayer = svgElement("g", {+ "data-animation": "stream-trace-reveal",+ "data-export-ready": "true",+ "aria-hidden": "true",+ });+ const exportPaths = svgElement("g", {+ "data-stream-trace-paths": "",+ fill: "none",+ stroke: traceColor(),+ "stroke-width": traceWidth(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ const exportVias = svgElement("g", {+ "data-stream-trace-vias": "",+ fill: holeColor(),+ stroke: traceColor(),+ "stroke-width": Math.max(0.5, viaOuterRadius() - viaInnerRadius()),+ });+ for (const entry of entries) {+ if (entry.state !== "complete") continue;+ exportPaths.append(entry.path.cloneNode(true));+ exportVias.append(+ entry.startVia.cloneNode(true),+ entry.endVia.cloneNode(true),+ );+ }+ exportLayer.append(exportPaths, exportVias);+ return exportLayer;+ }++ function destroy() {+ if (destroyed) return;+ stop();+ destroyed = true;+ entries.length = 0;+ entriesById.clear();+ active.clear();+ stateCounts.hidden = 0;+ stateCounts.queued = 0;+ stateCounts.active = 0;+ stateCounts.complete = 0;+ hiddenFrontier.length = 0;+ hiddenHead = 0;+ queue.length = 0;+ queueHead = 0;+ layer.remove();+ }++ const api = {+ appendTraces,+ pruneBefore,+ setViewport,+ updateOptions,+ complete,+ start,+ stop,+ reset,+ destroy,+ exportState,+ createExportLayer,+ layer,+ get stats() {+ return stats();+ },+ get settledState() {+ return exportState();+ },+ };++ if (settings.autoStart !== false) start();+ return api;+}
src/circuit-reveal-stream.jsadded+1042@@ -0,0 +1,1042 @@+const SVG_NS = "http://www.w3.org/2000/svg";++let instanceCount = 0;++export const STREAM_REVEAL_DEFAULTS = Object.freeze({+ spawnMode: "flow",+ spawnAngle: 90,+ spawnSwirl: 0.075,+ spawnOriginX: 0.5,+ unlockLead: 0.2,+ traceDuration: 950,+ revealLaunchRate: 24,+ scrollSpeedResponse: 0.72,+ maxActiveTraces: 72,+ maxLaunchesPerFrame: 12,+ maxOldSettlesPerFrame: 48,+ revealGlow: 0.78,+ revealPower: 0.72,+ autoStart: true,+});++function clamp(value, minimum = 0, maximum = 1) {+ return Math.max(minimum, Math.min(maximum, value));+}++function smoothstep(value) {+ const amount = clamp(value);+ return amount * amount * (3 - 2 * amount);+}++function finiteNumber(value, fallback) {+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+}++function hashSeed(value) {+ let hash = 2166136261;+ for (const character of String(value)) {+ hash ^= character.charCodeAt(0);+ hash = Math.imul(hash, 16777619);+ }+ return hash >>> 0;+}++function hashUnit(seed, index, salt = 0) {+ let value = seed ^ Math.imul(index + 1, 0x9e3779b1) ^ Math.imul(salt + 1, 0x85ebca6b);+ value = Math.imul(value ^ (value >>> 16), 0x7feb352d);+ value = Math.imul(value ^ (value >>> 15), 0x846ca68b);+ return ((value ^ (value >>> 16)) >>> 0) / 4294967296;+}++function svgElement(name, attributes = {}) {+ const element = document.createElementNS(SVG_NS, name);+ for (const [key, value] of Object.entries(attributes)) {+ element.setAttribute(key, String(value));+ }+ return element;+}++function pathData(points) {+ return points.map(([x, y], index) => `${index ? "L" : "M"}${x} ${y}`).join(" ");+}++function polylineLength(points) {+ let length = 0;+ for (let index = 1; index < points.length; index += 1) {+ length += Math.hypot(+ points[index][0] - points[index - 1][0],+ points[index][1] - points[index - 1][1],+ );+ }+ return Math.max(1, length);+}++function brandColor(x, width) {+ const position = clamp(x / Math.max(1, width));+ if (position < 0.5) return `hsl(${176 + position * 58} 92% 63%)`;+ return `hsl(${205 + (position - 0.5) * 86} 91% 70%)`;+}++function normalizeVelocity(value, viewportHeight) {+ const velocity = Math.max(0, finiteNumber(value, 0));+ const pixelsPerSecond = velocity > 20 ? velocity : velocity * 1000;+ return pixelsPerSecond / Math.max(1, viewportHeight);+}++/**+ * Reveals an append-only stream of absolute world-space traces.+ *+ * Viewport movement only unlocks work. Once launched, every trace follows its+ * own fixed timeline and never scrubs backward with scroll position.+ */+export function createStreamingTraceReveal(svg, config = {}, options = {}) {+ if (!svg || svg.namespaceURI !== SVG_NS) {+ throw new TypeError("svg must be an SVG element");+ }++ let settings = {+ ...STREAM_REVEAL_DEFAULTS,+ ...config,+ ...options,+ };+ const instanceId = `circuit-stream-reveal-${++instanceCount}`;+ const seed = hashSeed(`${config.seed ?? "adom"}:${settings.seed ?? ""}:stream`);+ const viewBox = svg.viewBox?.baseVal;+ const fieldWidth = Math.max(+ 1,+ finiteNumber(settings.width, viewBox?.width || svg.clientWidth || 1),+ );+ const featureScale = Math.max(0.25, finiteNumber(settings.featureScale, 1));+ const layer = svgElement("g", {+ "data-animation": "stream-trace-reveal",+ "data-spawn-mode": settings.spawnMode,+ "data-export-ready": "true",+ "aria-hidden": "true",+ });+ const pathLayer = svgElement("g", {+ "data-stream-trace-paths": "",+ fill: "none",+ stroke: traceColor(),+ "stroke-width": traceWidth(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ const viaLayer = svgElement("g", {+ "data-stream-trace-vias": "",+ fill: holeColor(),+ stroke: traceColor(),+ "stroke-width": Math.max(0.5, viaOuterRadius() - viaInnerRadius()),+ });+ layer.append(pathLayer, viaLayer);+ svg.append(layer);++ const entries = [];+ const entriesById = new Map();+ const active = new Set();+ const stateCounts = {+ hidden: 0,+ queued: 0,+ active: 0,+ complete: 0,+ };+ let hiddenFrontier = [];+ let hiddenHead = 0;+ let queue = [];+ let queueHead = 0;+ let appendIndex = 0;+ let running = false;+ let destroyed = false;+ let frameRequest = 0;+ let previousFrameTime = 0;+ let stoppedAt = 0;+ let launchCredit = 1;+ let viewport = {+ topWorldY: 0,+ bottomWorldY: 0,+ height: 1,+ velocity: 0,+ };+ let hasViewport = false;+ let furthestBottomWorldY = Number.NEGATIVE_INFINITY;+ let generatedFrontier = Number.NEGATIVE_INFINITY;+ let revealedThroughWorldY = Number.NEGATIVE_INFINITY;+ let completedTotal = 0;+ let exportReady = true;+ const reducedMotion = typeof window.matchMedia === "function"+ ? window.matchMedia("(prefers-reduced-motion: reduce)")+ : { matches: false };++ function traceWidth() {+ return Math.max(0.1, finiteNumber(settings.traceWidth, 1)) * featureScale;+ }++ function viaOuterRadius() {+ const baseTraceWidth = Math.max(0.1, finiteNumber(settings.traceWidth, 1));+ return Math.max(+ baseTraceWidth,+ finiteNumber(settings.viaOuterRadius, baseTraceWidth * 2.2),+ ) * featureScale;+ }++ function viaInnerRadius() {+ const baseOuterRadius = viaOuterRadius() / featureScale;+ return clamp(+ finiteNumber(settings.viaInnerRadius, baseOuterRadius * 0.48) * featureScale,+ 0,+ viaOuterRadius() * 0.92,+ );+ }++ function traceColor() {+ return settings.traceColor || "currentColor";+ }++ function holeColor() {+ return settings.holeColor || "var(--circuit-hole, #0d1117)";+ }++ function setRenderAttribute(entry, element, name, value, cacheKey) {+ const textValue = String(value);+ if (entry[cacheKey] === textValue) return;+ element.setAttribute(name, textValue);+ entry[cacheKey] = textValue;+ }++ function applyActiveStyles(entry, glow) {+ if (!entry.hasActiveStyles) {+ entry.path.setAttribute("stroke", entry.activeColor);+ entry.startVia.setAttribute("fill", entry.hiddenHoleColor);+ entry.endVia.setAttribute("fill", entry.hiddenHoleColor);+ entry.startVia.setAttribute("stroke", entry.activeColor);+ entry.endVia.setAttribute("stroke", entry.activeColor);+ entry.hasActiveStyles = true;+ }+ if (entry.activeGlow === glow) return;+ if (glow > 0.01) {+ entry.path.style.filter = `drop-shadow(0 0 ${1.5 + glow * 4 * featureScale}px ${entry.activeColor})`;+ entry.hasGlowFilter = true;+ } else if (entry.hasGlowFilter) {+ entry.path.style.removeProperty("filter");+ entry.hasGlowFilter = false;+ }+ entry.activeGlow = glow;+ }++ function clearActiveStyles(entry) {+ if (entry.hasActiveStyles) {+ entry.path.removeAttribute("stroke");+ entry.startVia.removeAttribute("fill");+ entry.endVia.removeAttribute("fill");+ entry.startVia.removeAttribute("stroke");+ entry.endVia.removeAttribute("stroke");+ entry.hasActiveStyles = false;+ }+ if (entry.hasGlowFilter) {+ entry.path.style.removeProperty("filter");+ entry.hasGlowFilter = false;+ }+ entry.activeGlow = Number.NaN;+ }++ function spawnMetadata(entry) {+ const points = entry.originalPoints;+ const middle = points[Math.floor(points.length / 2)];+ const localSpan = Math.max(1, entry.maxY - entry.minY, fieldWidth * 0.08);+ const originX = clamp(finiteNumber(settings.spawnOriginX, 0.5)) * fieldWidth;+ const angle = finiteNumber(settings.spawnAngle, 90) * Math.PI / 180;+ const direction = [Math.cos(angle), Math.sin(angle)];+ const across = [-direction[1], direction[0]];+ const swirl = clamp(finiteNumber(settings.spawnSwirl, 0.075), 0, 0.5);+ const phase = hashUnit(seed, entry.hashIndex, 11) * Math.PI * 2;+ const normalizedPoint = (point) => [+ (point[0] - fieldWidth * 0.5) / fieldWidth,+ (point[1] - entry.minY) / localSpan - 0.5,+ ];+ const potential = (point) => {+ const normalized = normalizedPoint(point);+ if (settings.spawnMode === "radial") {+ return Math.hypot(+ (point[0] - originX) / fieldWidth,+ normalized[1] * 0.55,+ );+ }+ if (settings.spawnMode === "edges") {+ return Math.min(+ point[0] / fieldWidth,+ (fieldWidth - point[0]) / fieldWidth,+ Math.abs(normalized[1] + 0.5),+ Math.abs(0.5 - normalized[1]),+ );+ }+ if (settings.spawnMode === "scatter") {+ return hashUnit(seed, entry.hashIndex, 19);+ }+ if (settings.spawnMode === "index") return entry.hashIndex;+ return normalized[0] * direction[0] + normalized[1] * direction[1];+ };++ const orientByPotential = !["scatter", "index"].includes(settings.spawnMode);+ const reverse = orientByPotential+ && potential(points[0]) > potential(points.at(-1));+ const orientedPoints = reverse ? [...points].reverse() : points;+ const normalizedMiddle = normalizedPoint(middle);+ let offsetUnit;+ if (settings.spawnMode === "radial") {+ offsetUnit = Math.hypot((middle[0] - originX) / fieldWidth, normalizedMiddle[1] * 0.4) - 0.28;+ } else if (settings.spawnMode === "edges") {+ offsetUnit = Math.min(middle[0], fieldWidth - middle[0]) / fieldWidth - 0.2;+ } else if (settings.spawnMode === "scatter") {+ offsetUnit = hashUnit(seed, entry.hashIndex, 23) * 2 - 1;+ } else if (settings.spawnMode === "index") {+ offsetUnit = (hashUnit(seed, entry.hashIndex, 29) - 0.5) * 0.6;+ } else {+ const projection = normalizedMiddle[0] * direction[0] + normalizedMiddle[1] * direction[1];+ const cross = normalizedMiddle[0] * across[0] + normalizedMiddle[1] * across[1];+ offsetUnit = cross * 0.7+ + Math.sin(projection * Math.PI * 2.2 + phase) * swirl+ + Math.sin(cross * Math.PI * 3.1 - phase) * swirl * 0.38;+ }+ return {+ points: orientedPoints,+ offsetUnit: clamp(offsetUnit, -1, 1),+ orderJitter: hashUnit(seed, entry.hashIndex, 31),+ };+ }++ function applyGeometry(entry) {+ const metadata = spawnMetadata(entry);+ entry.points = metadata.points;+ entry.offsetUnit = metadata.offsetUnit;+ entry.orderJitter = metadata.orderJitter;+ entry.activeColor = brandColor(+ entry.points[Math.floor(entry.points.length / 2)][0],+ fieldWidth,+ );+ entry.path.setAttribute("d", pathData(entry.points));+ entry.startVia.setAttribute(+ "transform",+ `translate(${entry.points[0][0]} ${entry.points[0][1]})`,+ );+ entry.endVia.setAttribute(+ "transform",+ `translate(${entry.points.at(-1)[0]} ${entry.points.at(-1)[1]})`,+ );+ }++ function transitionState(entry, nextState) {+ const previousState = entry.state;+ if (previousState === nextState) return;+ if (previousState && Object.hasOwn(stateCounts, previousState)) {+ stateCounts[previousState] -= 1;+ }+ if (nextState && Object.hasOwn(stateCounts, nextState)) {+ stateCounts[nextState] += 1;+ }+ entry.state = nextState;+ }++ function setHidden(entry) {+ active.delete(entry);+ entry.hiddenHoleColor = holeColor();+ setRenderAttribute(entry, entry.path, "stroke-dashoffset", entry.length, "pathOffset");+ setRenderAttribute(entry, entry.path, "opacity", 0, "pathOpacity");+ clearActiveStyles(entry);+ setRenderAttribute(entry, entry.startVia, "opacity", 0, "startViaOpacity");+ setRenderAttribute(entry, entry.endVia, "opacity", 0, "endViaOpacity");+ transitionState(entry, "hidden");+ entry.progress = 0;+ entry.startedAt = 0;+ entry.duration = 0;+ }++ function setPartial(entry, amount) {+ const progress = smoothstep(amount);+ const power = clamp(finiteNumber(settings.revealPower, 0.72), 0, 1.5);+ const glow = clamp(finiteNumber(settings.revealGlow, 0.78), 0, 1.5);+ applyActiveStyles(entry, glow);+ setRenderAttribute(+ entry,+ entry.path,+ "stroke-dashoffset",+ entry.length * (1 - progress),+ "pathOffset",+ );+ setRenderAttribute(+ entry,+ entry.path,+ "opacity",+ clamp(0.38 + progress * 0.62),+ "pathOpacity",+ );+ setRenderAttribute(+ entry,+ entry.startVia,+ "opacity",+ smoothstep((progress + 0.03) / 0.1),+ "startViaOpacity",+ );+ setRenderAttribute(+ entry,+ entry.endVia,+ "opacity",+ smoothstep((progress - 0.82 + power * 0.025) / 0.16),+ "endViaOpacity",+ );+ if (entry.state !== "active") transitionState(entry, "active");+ entry.progress = progress;+ }++ function setComplete(entry) {+ if (entry.state === "complete") return;+ active.delete(entry);+ setRenderAttribute(entry, entry.path, "stroke-dashoffset", 0, "pathOffset");+ setRenderAttribute(entry, entry.path, "opacity", 1, "pathOpacity");+ clearActiveStyles(entry);+ setRenderAttribute(entry, entry.startVia, "opacity", 1, "startViaOpacity");+ setRenderAttribute(entry, entry.endVia, "opacity", 1, "endViaOpacity");+ transitionState(entry, "complete");+ entry.progress = 1;+ completedTotal += 1;+ revealedThroughWorldY = Math.max(revealedThroughWorldY, entry.maxY);+ }++ function unlockY(entry) {+ const localOffsetBound = viewport.height * 0.32;+ return entry.minY + entry.offsetUnit * localOffsetBound;+ }++ function updateUnlockKey(entry) {+ entry.unlockWorldY = unlockY(entry);+ return entry.unlockWorldY;+ }++ function compareRevealOrder(first, second) {+ return first.unlockWorldY - second.unlockWorldY+ || first.orderJitter - second.orderJitter+ || first.hashIndex - second.hashIndex;+ }++ function compactHiddenFrontier() {+ hiddenFrontier = hiddenFrontier+ .slice(hiddenHead)+ .filter((entry) => entry.state === "hidden");+ hiddenHead = 0;+ }++ function addToHiddenFrontier(newEntries) {+ if (!newEntries.length) return;+ for (const entry of newEntries) updateUnlockKey(entry);+ newEntries.sort(compareRevealOrder);++ if (hiddenHead >= hiddenFrontier.length) {+ hiddenFrontier = newEntries;+ hiddenHead = 0;+ return;+ }++ const lastPending = hiddenFrontier.at(-1);+ if (compareRevealOrder(lastPending, newEntries[0]) <= 0) {+ hiddenFrontier.push(...newEntries);+ return;+ }++ compactHiddenFrontier();+ const merged = [];+ let currentIndex = 0;+ let newIndex = 0;+ while (currentIndex < hiddenFrontier.length && newIndex < newEntries.length) {+ if (compareRevealOrder(hiddenFrontier[currentIndex], newEntries[newIndex]) <= 0) {+ merged.push(hiddenFrontier[currentIndex]);+ currentIndex += 1;+ } else {+ merged.push(newEntries[newIndex]);+ newIndex += 1;+ }+ }+ merged.push(+ ...hiddenFrontier.slice(currentIndex),+ ...newEntries.slice(newIndex),+ );+ hiddenFrontier = merged;+ }++ function rebuildEligibilityIndex() {+ hiddenFrontier = [];+ hiddenHead = 0;+ for (const entry of entries) {+ if (entry.state === "hidden" || entry.state === "queued") {+ updateUnlockKey(entry);+ }+ if (entry.state === "hidden") hiddenFrontier.push(entry);+ }+ hiddenFrontier.sort(compareRevealOrder);+ if (queueHead < queue.length) sortQueue();+ }++ function compactQueue() {+ queue = queue+ .slice(queueHead)+ .filter((entry) => entry.state === "queued");+ queueHead = 0;+ }++ function sortQueue() {+ compactQueue();+ queue.sort(compareRevealOrder);+ }++ function addToQueue(newEntries) {+ if (!newEntries.length) return;+ if (queueHead >= queue.length) {+ queue = newEntries;+ queueHead = 0;+ return;+ }++ const lastPending = queue.at(-1);+ if (compareRevealOrder(lastPending, newEntries[0]) <= 0) {+ queue.push(...newEntries);+ return;+ }++ compactQueue();+ const merged = [];+ let currentIndex = 0;+ let newIndex = 0;+ while (currentIndex < queue.length && newIndex < newEntries.length) {+ if (compareRevealOrder(queue[currentIndex], newEntries[newIndex]) <= 0) {+ merged.push(queue[currentIndex]);+ currentIndex += 1;+ } else {+ merged.push(newEntries[newIndex]);+ newIndex += 1;+ }+ }+ merged.push(...queue.slice(currentIndex), ...newEntries.slice(newIndex));+ queue = merged;+ }++ function evaluateEligibility() {+ if (!hasViewport || destroyed) return;+ const lead = clamp(finiteNumber(settings.unlockLead, 0.2), 0, 3) * viewport.height;+ const eligibleThrough = furthestBottomWorldY + lead;+ const newlyQueued = [];+ while (hiddenHead < hiddenFrontier.length) {+ const entry = hiddenFrontier[hiddenHead];+ if (entry.unlockWorldY > eligibleThrough) break;+ hiddenHead += 1;+ if (entry.state !== "hidden") continue;+ transitionState(entry, "queued");+ newlyQueued.push(entry);+ }+ addToQueue(newlyQueued);+ if (hiddenHead > 2048 && hiddenHead > hiddenFrontier.length / 2) {+ compactHiddenFrontier();+ }+ if (settings.revealMotion === false || reducedMotion.matches) {+ for (let index = queueHead; index < queue.length; index += 1) {+ setComplete(queue[index]);+ }+ compactQueue();+ }+ updateExportReadiness();+ }++ function baseTraceDuration() {+ const explicit = finiteNumber(settings.traceDuration, Number.NaN);+ const fallback = finiteNumber(settings.revealDuration, STREAM_REVEAL_DEFAULTS.traceDuration);+ return clamp(Number.isFinite(explicit) ? explicit : fallback, 120, 12000);+ }++ function launch(entry, now) {+ const viewportsPerSecond = normalizeVelocity(viewport.velocity, viewport.height);+ const response = clamp(finiteNumber(settings.scrollSpeedResponse, 0.72), 0, 2);+ const speedAmount = clamp(viewportsPerSecond / 2.2);+ const speedDurationFactor = 1 - clamp(speedAmount * response * 0.2, 0, 0.32);+ const lengthReference = Math.max(80, viewport.height * 0.55);+ const lengthFactor = clamp(0.78 + entry.length / lengthReference * 0.22, 0.78, 1.35);+ const jitter = 0.88 + hashUnit(seed, entry.hashIndex, 41) * 0.24;+ entry.startedAt = now;+ entry.duration = clamp(+ baseTraceDuration() * lengthFactor * jitter * speedDurationFactor,+ 120,+ 12000,+ );+ setPartial(entry, 0);+ active.add(entry);+ }++ function settleOldQueue() {+ const pendingCount = queue.length - queueHead;+ if (!pendingCount) return;+ const maximumActive = Math.round(clamp(+ finiteNumber(settings.maxActiveTraces, 72),+ 1,+ 320,+ ));+ const backlogLimit = maximumActive * 3;+ const settleLimit = Math.round(clamp(+ finiteNumber(settings.maxOldSettlesPerFrame, 48),+ 1,+ 240,+ ));+ const oldThreshold = viewport.topWorldY - viewport.height * 0.2;+ let settled = 0;+ for (let index = queueHead; index < queue.length; index += 1) {+ if (pendingCount - settled <= backlogLimit || settled >= settleLimit) break;+ const entry = queue[index];+ if (entry.state !== "queued" || entry.maxY >= oldThreshold) continue;+ setComplete(entry);+ settled += 1;+ }+ if (settled) compactQueue();+ }++ function launchQueued(now, elapsed) {+ settleOldQueue();+ const maximumActive = Math.round(clamp(+ finiteNumber(settings.maxActiveTraces, 72),+ 1,+ 320,+ ));+ const viewportsPerSecond = normalizeVelocity(viewport.velocity, viewport.height);+ const response = clamp(finiteNumber(settings.scrollSpeedResponse, 0.72), 0, 2);+ const speedAmount = clamp(viewportsPerSecond / 2);+ const baseRate = clamp(finiteNumber(settings.revealLaunchRate, 24), 0.5, 240);+ const launchRate = Math.min(360, baseRate * (1 + speedAmount * response * 2.2));+ const maximumLaunches = Math.round(clamp(+ finiteNumber(settings.maxLaunchesPerFrame, 12),+ 1,+ 48,+ ));+ launchCredit = Math.min(maximumLaunches, launchCredit + elapsed * launchRate / 1000);+ let launched = 0;+ while (+ launchCredit >= 1+ && launched < maximumLaunches+ && active.size < maximumActive+ && queueHead < queue.length+ ) {+ const entry = queue[queueHead];+ queueHead += 1;+ if (entry.state !== "queued") continue;+ launch(entry, now);+ launchCredit -= 1;+ launched += 1;+ }+ if (queueHead >= queue.length) {+ queue.length = 0;+ queueHead = 0;+ launchCredit = Math.min(1, launchCredit);+ } else if (queueHead > 1024 && queueHead > queue.length / 2) {+ compactQueue();+ }+ }++ function updateActive(now) {+ for (const entry of active) {+ const amount = clamp((now - entry.startedAt) / Math.max(1, entry.duration));+ if (amount >= 1) setComplete(entry);+ else setPartial(entry, amount);+ }+ }++ function updateExportReadiness() {+ const ready = active.size === 0 && queueHead >= queue.length;+ if (ready === exportReady) return;+ exportReady = ready;+ layer.setAttribute("data-export-ready", String(ready));+ }++ function renderFrame(now) {+ frameRequest = 0;+ if (!running || destroyed) return;+ const elapsed = previousFrameTime ? clamp(now - previousFrameTime, 0, 80) : 16;+ previousFrameTime = now;+ updateActive(now);+ launchQueued(now, elapsed);+ viewport.velocity *= Math.pow(0.9, elapsed / 16.67);+ updateExportReadiness();+ if (active.size > 0 || queueHead < queue.length) scheduleFrame();+ else previousFrameTime = 0;+ }++ function scheduleFrame() {+ if (!running || destroyed || frameRequest) return;+ frameRequest = window.requestAnimationFrame(renderFrame);+ }++ function appendTraces(traces) {+ if (destroyed) return api;+ if (!Array.isArray(traces)) throw new TypeError("traces must be an array");+ const pathFragment = document.createDocumentFragment();+ const viaFragment = document.createDocumentFragment();+ const newEntries = [];+ const viaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ for (const trace of traces) {+ if (!trace || !Array.isArray(trace.points) || trace.points.length < 2) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const id = String(trace.id ?? appendIndex);+ if (entriesById.has(id)) throw new Error(`duplicate streaming trace id: ${id}`);+ let originalPoints = trace.points;+ let normalizedPoints = null;+ let derivedMinY = Number.POSITIVE_INFINITY;+ let derivedMaxY = Number.NEGATIVE_INFINITY;+ for (let pointIndex = 0; pointIndex < trace.points.length; pointIndex += 1) {+ const point = trace.points[pointIndex];+ if (!Array.isArray(point) || point.length < 2) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const x = Number(point[0]);+ const y = Number(point[1]);+ if (!Number.isFinite(x) || !Number.isFinite(y)) {+ throw new TypeError("each trace must contain at least two finite points");+ }+ const reusable = point.length === 2+ && typeof point[0] === "number"+ && typeof point[1] === "number";+ if (!reusable && !normalizedPoints) {+ normalizedPoints = trace.points.slice(0, pointIndex)+ .map((previous) => [Number(previous[0]), Number(previous[1])]);+ }+ normalizedPoints?.push([x, y]);+ derivedMinY = Math.min(derivedMinY, y);+ derivedMaxY = Math.max(derivedMaxY, y);+ }+ if (normalizedPoints) originalPoints = normalizedPoints;+ const minY = finiteNumber(trace.minY, derivedMinY);+ const maxY = finiteNumber(trace.maxY, derivedMaxY);+ const suppliedLength = Number(trace.length);+ const length = Math.max(+ 1,+ Number.isFinite(suppliedLength) ? suppliedLength : polylineLength(originalPoints),+ );+ const path = svgElement("path", {+ "stroke-dasharray": `${length} ${length + 1}`,+ "data-stream-trace": id,+ });+ const viaAttributes = {+ cx: 0,+ cy: 0,+ r: viaRadius,+ };+ const startVia = svgElement("circle", {+ ...viaAttributes,+ "data-stream-via": "start",+ "data-trace-id": id,+ });+ const endVia = svgElement("circle", {+ ...viaAttributes,+ "data-stream-via": "end",+ "data-trace-id": id,+ });+ const entry = {+ id,+ hashIndex: appendIndex,+ trace,+ originalPoints,+ points: originalPoints,+ length,+ minY: Math.min(minY, maxY),+ maxY: Math.max(minY, maxY),+ path,+ startVia,+ endVia,+ offsetUnit: 0,+ orderJitter: 0,+ state: null,+ progress: 0,+ startedAt: 0,+ duration: 0,+ };+ appendIndex += 1;+ applyGeometry(entry);+ setHidden(entry);+ entries.push(entry);+ newEntries.push(entry);+ entriesById.set(id, entry);+ pathFragment.append(path);+ viaFragment.append(startVia, endVia);+ generatedFrontier = Math.max(generatedFrontier, entry.maxY);+ }+ pathLayer.append(pathFragment);+ viaLayer.append(viaFragment);+ addToHiddenFrontier(newEntries);+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function pruneBefore(worldY) {+ if (destroyed) return 0;+ const threshold = finiteNumber(worldY, Number.NEGATIVE_INFINITY);+ let removed = 0;+ let retained = 0;+ for (const entry of entries) {+ if (entry.state === "complete" && entry.maxY < threshold && !active.has(entry)) {+ entry.path.remove();+ entry.startVia.remove();+ entry.endVia.remove();+ entriesById.delete(entry.id);+ transitionState(entry, null);+ removed += 1;+ } else {+ entries[retained] = entry;+ retained += 1;+ }+ }+ entries.length = retained;+ updateExportReadiness();+ return removed;+ }++ function setViewport(nextViewport = {}) {+ if (destroyed) return api;+ const height = Math.max(1, finiteNumber(+ nextViewport.height,+ finiteNumber(nextViewport.bottomWorldY, viewport.bottomWorldY)+ - finiteNumber(nextViewport.topWorldY, viewport.topWorldY),+ ));+ const heightChanged = height !== viewport.height;+ const topWorldY = finiteNumber(nextViewport.topWorldY, viewport.topWorldY);+ const bottomWorldY = finiteNumber(nextViewport.bottomWorldY, topWorldY + height);+ viewport = {+ topWorldY,+ bottomWorldY: Math.max(topWorldY, bottomWorldY),+ height,+ velocity: Math.max(0, finiteNumber(nextViewport.velocity, 0)),+ };+ if (heightChanged) rebuildEligibilityIndex();+ hasViewport = true;+ furthestBottomWorldY = Math.max(furthestBottomWorldY, viewport.bottomWorldY);+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function updateOptions(next = {}) {+ if (destroyed) return api;+ const previousSpawnMode = settings.spawnMode;+ const previousSpawnAngle = settings.spawnAngle;+ const previousSpawnSwirl = settings.spawnSwirl;+ const previousSpawnOriginX = settings.spawnOriginX;+ const previousTraceWidth = traceWidth();+ const previousViaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ const previousViaStrokeWidth = Math.max(0.5, viaOuterRadius() - viaInnerRadius());+ const previousTraceColor = traceColor();+ const previousHoleColor = holeColor();+ settings = { ...settings, ...next };+ const nextTraceWidth = traceWidth();+ const nextViaRadius = (viaOuterRadius() + viaInnerRadius()) * 0.5;+ const nextViaStrokeWidth = Math.max(0.5, viaOuterRadius() - viaInnerRadius());+ const nextTraceColor = traceColor();+ const nextHoleColor = holeColor();+ const spawnChanged = previousSpawnMode !== settings.spawnMode+ || previousSpawnAngle !== settings.spawnAngle+ || previousSpawnSwirl !== settings.spawnSwirl+ || previousSpawnOriginX !== settings.spawnOriginX;++ if (previousSpawnMode !== settings.spawnMode) {+ layer.setAttribute("data-spawn-mode", settings.spawnMode);+ }+ if (previousTraceWidth !== nextTraceWidth) {+ pathLayer.setAttribute("stroke-width", String(nextTraceWidth));+ }+ if (previousViaStrokeWidth !== nextViaStrokeWidth) {+ viaLayer.setAttribute("stroke-width", String(nextViaStrokeWidth));+ }+ if (previousTraceColor !== nextTraceColor) {+ pathLayer.setAttribute("stroke", nextTraceColor);+ viaLayer.setAttribute("stroke", nextTraceColor);+ }+ if (previousHoleColor !== nextHoleColor) {+ viaLayer.setAttribute("fill", nextHoleColor);+ }+ if (previousViaRadius !== nextViaRadius) {+ for (const entry of entries) {+ entry.startVia.setAttribute("r", String(nextViaRadius));+ entry.endVia.setAttribute("r", String(nextViaRadius));+ }+ }+ if (spawnChanged) {+ for (const entry of entries) {+ if (entry.state === "hidden" || entry.state === "queued") applyGeometry(entry);+ }+ rebuildEligibilityIndex();+ }+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function complete() {+ if (destroyed) return api;+ active.clear();+ queue.length = 0;+ queueHead = 0;+ hiddenFrontier.length = 0;+ hiddenHead = 0;+ for (const entry of entries) setComplete(entry);+ furthestBottomWorldY = Math.max(furthestBottomWorldY, generatedFrontier);+ updateExportReadiness();+ return api;+ }++ function start() {+ if (destroyed || running) return api;+ const now = performance.now();+ if (stoppedAt) {+ const pauseDuration = now - stoppedAt;+ for (const entry of active) entry.startedAt += pauseDuration;+ }+ stoppedAt = 0;+ running = true;+ previousFrameTime = 0;+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function stop() {+ if (destroyed || !running) return api;+ running = false;+ stoppedAt = performance.now();+ window.cancelAnimationFrame(frameRequest);+ frameRequest = 0;+ previousFrameTime = 0;+ return api;+ }++ function reset() {+ if (destroyed) return api;+ active.clear();+ queue.length = 0;+ queueHead = 0;+ completedTotal = 0;+ revealedThroughWorldY = Number.NEGATIVE_INFINITY;+ launchCredit = 1;+ for (const entry of entries) {+ applyGeometry(entry);+ setHidden(entry);+ }+ rebuildEligibilityIndex();+ furthestBottomWorldY = hasViewport+ ? viewport.bottomWorldY+ : Number.NEGATIVE_INFINITY;+ evaluateEligibility();+ scheduleFrame();+ return api;+ }++ function stats() {+ return {+ retained: entries.length,+ unlocked: entries.length - stateCounts.hidden,+ queued: stateCounts.queued,+ active: active.size,+ completed: stateCounts.complete,+ completedTotal,+ generatedFrontier: Number.isFinite(generatedFrontier) ? generatedFrontier : null,+ revealedThroughWorldY: Number.isFinite(revealedThroughWorldY)+ ? revealedThroughWorldY+ : null,+ velocity: viewport.velocity,+ };+ }++ function exportState() {+ const settled = entries+ .filter((entry) => entry.state === "complete")+ .map((entry) => ({+ id: entry.id,+ points: entry.points.map((point) => [...point]),+ length: entry.length,+ minY: entry.minY,+ maxY: entry.maxY,+ }));+ return {+ ready: active.size === 0 && queueHead >= queue.length,+ generatedFrontier: Number.isFinite(generatedFrontier) ? generatedFrontier : null,+ revealedThroughWorldY: Number.isFinite(revealedThroughWorldY)+ ? revealedThroughWorldY+ : null,+ traces: settled,+ };+ }++ function createExportLayer() {+ const exportLayer = svgElement("g", {+ "data-animation": "stream-trace-reveal",+ "data-export-ready": "true",+ "aria-hidden": "true",+ });+ const exportPaths = svgElement("g", {+ "data-stream-trace-paths": "",+ fill: "none",+ stroke: traceColor(),+ "stroke-width": traceWidth(),+ "stroke-linecap": "butt",+ "stroke-linejoin": "miter",+ });+ const exportVias = svgElement("g", {+ "data-stream-trace-vias": "",+ fill: holeColor(),+ stroke: traceColor(),+ "stroke-width": Math.max(0.5, viaOuterRadius() - viaInnerRadius()),+ });+ for (const entry of entries) {+ if (entry.state !== "complete") continue;+ exportPaths.append(entry.path.cloneNode(true));+ exportVias.append(+ entry.startVia.cloneNode(true),+ entry.endVia.cloneNode(true),+ );+ }+ exportLayer.append(exportPaths, exportVias);+ return exportLayer;+ }++ function destroy() {+ if (destroyed) return;+ stop();+ destroyed = true;+ entries.length = 0;+ entriesById.clear();+ active.clear();+ stateCounts.hidden = 0;+ stateCounts.queued = 0;+ stateCounts.active = 0;+ stateCounts.complete = 0;+ hiddenFrontier.length = 0;+ hiddenHead = 0;+ queue.length = 0;+ queueHead = 0;+ layer.remove();+ }++ const api = {+ appendTraces,+ pruneBefore,+ setViewport,+ updateOptions,+ complete,+ start,+ stop,+ reset,+ destroy,+ exportState,+ createExportLayer,+ layer,+ get stats() {+ return stats();+ },+ get settledState() {+ return exportState();+ },+ };++ if (settings.autoStart !== false) start();+ return api;+}
src/circuit-trace-stager-v8.jsadded+132@@ -0,0 +1,132 @@+function finiteNumber(value, fallback) {+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+}++function batchBounds(traces) {+ let minimum = Number.POSITIVE_INFINITY;+ let maximum = Number.NEGATIVE_INFINITY;+ for (const trace of traces) {+ const minY = finiteNumber(trace?.minY, Number.NaN);+ const maxY = finiteNumber(trace?.maxY, Number.NaN);+ if (Number.isFinite(minY) && Number.isFinite(maxY)) {+ minimum = Math.min(minimum, minY, maxY);+ maximum = Math.max(maximum, minY, maxY);+ continue;+ }+ for (const point of trace?.points || []) {+ const y = Number(point?.[1]);+ if (!Number.isFinite(y)) continue;+ minimum = Math.min(minimum, y);+ maximum = Math.max(maximum, y);+ }+ }+ return [+ Number.isFinite(minimum) ? minimum : 0,+ Number.isFinite(maximum) ? maximum : 0,+ ];+}++/**+ * Keeps pre-generated trace geometry off the SVG until its page is close+ * enough to the viewport to participate in reveal ordering.+ *+ * Batches are always materialized in publication order. That preserves the+ * reveal hash index and therefore the deterministic spawn order of an+ * unstaged append stream.+ */+export function createPageTraceStager(options = {}) {+ const materialize = options.materialize;+ if (typeof materialize !== "function") {+ throw new TypeError("materialize must be a function");+ }++ let pending = [];+ let pendingHead = 0;+ let materializedBatches = 0;+ let materializedTraces = 0;+ let bufferedTraces = 0;+ let generatedTraces = 0;+ let through = Number.NEGATIVE_INFINITY;+ let destroyed = false;++ function compact() {+ if (!pendingHead) return;+ pending = pending.slice(pendingHead);+ pendingHead = 0;+ }++ function flush() {+ if (destroyed) return 0;+ let appended = 0;+ while (pendingHead < pending.length) {+ const batch = pending[pendingHead];+ if (batch.minY > through) break;+ pendingHead += 1;+ bufferedTraces -= batch.traces.length;+ materializedBatches += 1;+ materializedTraces += batch.traces.length;+ appended += batch.traces.length;+ materialize(batch.traces, batch);+ }+ if (pendingHead > 64 && pendingHead > pending.length / 2) compact();+ return appended;+ }++ const api = {+ stage(traces) {+ if (destroyed) return 0;+ if (!Array.isArray(traces)) throw new TypeError("traces must be an array");+ if (!traces.length) return 0;+ const [minY, maxY] = batchBounds(traces);+ const batch = Object.freeze({+ traces,+ minY,+ maxY,+ index: materializedBatches + pending.length - pendingHead,+ });+ pending.push(batch);+ bufferedTraces += traces.length;+ generatedTraces += traces.length;+ return flush();+ },++ materializeThrough(worldY) {+ if (destroyed) return 0;+ through = Math.max(through, finiteNumber(worldY, through));+ return flush();+ },++ clear() {+ pending.length = 0;+ pendingHead = 0;+ materializedBatches = 0;+ materializedTraces = 0;+ bufferedTraces = 0;+ generatedTraces = 0;+ through = Number.NEGATIVE_INFINITY;+ return api;+ },++ destroy() {+ if (destroyed) return;+ destroyed = true;+ pending.length = 0;+ pendingHead = 0;+ bufferedTraces = 0;+ },++ get stats() {+ return Object.freeze({+ generatedTraces,+ materializedTraces,+ bufferedTraces,+ materializedBatches,+ bufferedBatches: pending.length - pendingHead,+ materializedThroughWorldY: Number.isFinite(through) ? through : null,+ });+ },+ };++ return api;+}
src/index-reveal.htmladded+530@@ -0,0 +1,530 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Procedural Circuit Background — reveal</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0d1117;+ --surface: #161b22;+ --border: #30363d;+ --text: #e6edf3;+ --muted: #8b949e;+ --accent: #00b8b0;+ --accent-bright: #00e6dc;+ }++ * { box-sizing: border-box; }+ html, body { min-height: 100%; margin: 0; }+ body {+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ }++ .hero {+ --circuit-hole: var(--bg);+ position: relative;+ min-height: 100svh;+ overflow: hidden;+ display: grid;+ place-items: center;+ isolation: isolate;+ }++ .circuit-layer {+ position: absolute;+ inset: 0;+ z-index: -2;+ }++ .glow {+ position: absolute;+ inset: 0;+ z-index: -1;+ pointer-events: none;+ background:+ radial-gradient(circle at 52% 44%, rgba(0, 230, 220, .06), transparent 34%),+ linear-gradient(to top, var(--bg) 0, transparent 12rem);+ }++ main {+ width: min(760px, calc(100% - 40px));+ text-align: center;+ padding: 80px 0 180px;+ }++ .eyebrow {+ margin: 0 0 20px;+ color: var(--accent-bright);+ font: 600 12px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .18em;+ text-transform: uppercase;+ }++ h1 {+ margin: 0;+ font-size: clamp(2.6rem, 8vw, 5.6rem);+ line-height: .9;+ letter-spacing: -.055em;+ color: transparent;+ background: linear-gradient(110deg, #e9ffff, #7bc9c9 62%, var(--accent-bright));+ background-clip: text;+ filter: drop-shadow(0 0 .4em rgba(255,255,255,.18));+ }++ .lede {+ max-width: 570px;+ margin: 28px auto 0;+ color: #bac6d3;+ font-size: clamp(1rem, 2vw, 1.25rem);+ line-height: 1.6;+ }++ .hint {+ margin-top: 24px;+ color: var(--muted);+ font: 500 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }++ .controls {+ position: fixed;+ left: 50%;+ bottom: 12px;+ z-index: 5;+ width: min(940px, calc(100% - 24px));+ transform: translateX(-50%);+ display: grid;+ grid-template-columns: minmax(104px, .6fr) minmax(0, 3fr) auto auto auto;+ align-items: end;+ gap: 8px;+ padding: 10px 12px;+ border: 1px solid rgba(48, 54, 61, .9);+ border-radius: 12px;+ background: rgba(22, 27, 34, .88);+ box-shadow: 0 18px 70px rgba(0,0,0,.38);+ backdrop-filter: blur(18px);+ }++ label { display: grid; gap: 5px; color: var(--muted); font-size: 12px; }+ input[type="text"] {+ width: 100%;+ height: 32px;+ padding: 0 10px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 7px;+ outline: none;+ background: #0d1117;+ font: 500 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ input[type="text"]:focus { border-color: var(--accent); }+ input[type="range"] { width: 100%; accent-color: var(--accent); }++ button {+ height: 32px;+ padding: 0 12px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 7px;+ background: #21262d;+ font: 700 13px system-ui, sans-serif;+ cursor: pointer;+ }+ button:hover { border-color: #59636e; background: #282e36; }+ button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); }+ button.primary:hover { background: var(--accent-bright); }++ /* Sits in the top row where Density + Live signals used to be, and is+ labelled like the other fields ("Seed" above its input). */+ .presets-field { display: grid; gap: 5px; min-width: 0; }+ .presets-label { color: var(--muted); font-size: 12px; }+ .presets {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 5px;+ }+ .presets button {+ height: 32px;+ padding: 0 9px;+ font: 600 12px system-ui, sans-serif;+ }+ .presets button.active {+ color: #062d2b;+ border-color: var(--accent);+ background: var(--accent);+ }++ /* The reveal row spans the whole control bar, under the top row. */+ .reveal-field { grid-column: 1 / -1; }+ .reveal-field .presets { align-items: center; }+ .presets .replay { margin-left: 6px; }++ .tuning {+ grid-column: 1 / -1;+ border-top: 1px solid rgba(48, 54, 61, .7);+ padding-top: 8px;+ }+ .tuning summary {+ cursor: pointer;+ color: var(--muted);+ font: 600 12px system-ui, sans-serif;+ user-select: none;+ }+ .tuning summary:hover { color: var(--text); }+ .tuning .knobs {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 7px 14px;+ padding-top: 9px;+ }+ .knob span {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ }+ .knob output { color: var(--accent-bright); font-variant-numeric: tabular-nums; }+ .tuning .reset-row { margin-top: 9px; display: flex; justify-content: flex-end; }+ .tuning button { height: 27px; font-size: 12px; }++ @media (max-width: 760px) {+ .controls { grid-template-columns: 1fr 1fr; max-height: 60svh; overflow-y: auto; }+ /* Direct children only — preset chips and panel resets keep their size. */+ .controls > button { width: 100%; }+ .presets-field { grid-column: 1 / -1; }+ main { padding-bottom: 270px; }+ }+ </style>+ </head>+ <body>+ <section class="hero" id="hero">+ <div class="circuit-layer" id="circuit"></div>+ <div class="glow" aria-hidden="true"></div>+ <main>+ <p class="eyebrow">Seeded SVG generator · occupancy-grid engine · reveal build</p>+ <h1>Live circuitry</h1>+ <p class="lede">+ Procedural generation of Nitrogen's trace pattern — routed live: every trace grows+ out of a via with a spark on its tip, and the pads light up as it reaches them.+ </p>+ <p class="hint">Move the pointer to attract signals · click anywhere for a burst</p>+ </main>+ </section>++ <form class="controls" id="controls" autocomplete="off">+ <label>+ Seed+ <input id="seed" type="text" value="nitrogen" autocomplete="off" spellcheck="false" />+ </label>+ <div class="presets-field">+ <span class="presets-label">Animation</span>+ <div class="presets" id="presets"></div>+ </div>+ <button class="primary" type="submit">Generate</button>+ <button id="download" type="button">Download SVG</button>+ <button id="downloadTile" type="button">Download Tile</button>++ <div class="presets-field reveal-field">+ <span class="presets-label">Reveal — how the board grows in</span>+ <div class="presets" id="revealPresets">+ <button class="replay" id="replay" type="button">Replay ⟳</button>+ </div>+ </div>++ <details class="tuning">+ <summary>Generation tuning</summary>+ <div class="knobs">+ <label class="knob">+ <span>Density <output>1.05</output></span>+ <input type="range" data-key="density" min="0.35" max="1.45" step="0.05" value="1.05" />+ </label>+ <label class="knob">+ <span>Formations <output>96</output></span>+ <input type="range" data-key="formations" min="24" max="96" step="4" value="96" />+ </label>+ <label class="knob">+ <span>Bus width <output>1</output></span>+ <input type="range" data-key="busWidth" min="0.5" max="2" step="0.1" value="1" />+ </label>+ <label class="knob">+ <span>Turn penalty <output>0.55</output></span>+ <input type="range" data-key="turnPenalty" min="0.1" max="1.2" step="0.05" value="0.55" />+ </label>+ <label class="knob">+ <span>Weave spacing <output>0.22</output></span>+ <input type="range" data-key="weave" min="0" max="0.45" step="0.01" value="0.22" />+ </label>+ <label class="knob">+ <span>Cramp aversion <output>0.4</output></span>+ <input type="range" data-key="cramp" min="0" max="0.8" step="0.05" value="0.4" />+ </label>+ <label class="knob">+ <span>Horizontal bias <output>0.6</output></span>+ <input type="range" data-key="horizontalBias" min="0.35" max="0.9" step="0.05" value="0.6" />+ </label>+ <label class="knob">+ <span>Net reach <output>42</output></span>+ <input type="range" data-key="netReach" min="16" max="60" step="2" value="42" />+ </label>+ <label class="knob">+ <span>Jog bias <output>5</output></span>+ <input type="range" data-key="jogBias" min="0" max="10" step="1" value="5" />+ </label>+ <label class="knob">+ <span>Stub chance <output>0</output></span>+ <input type="range" data-key="stubChance" min="0" max="1" step="0.05" value="0" />+ </label>+ <label class="knob">+ <span>Inline vias <output>0.03</output></span>+ <input type="range" data-key="inlineViaChance" min="0" max="0.12" step="0.005" value="0.03" />+ </label>+ <label class="knob">+ <span>Tap combs <output>8</output></span>+ <input type="range" data-key="combs" min="0" max="16" step="1" value="8" />+ </label>+ </div>+ <div class="reset-row">+ <button class="reset-tuning" type="button">Reset generation</button>+ </div>+ </details>++ <details class="tuning" data-panel="animation">+ <summary>Animation tuning</summary>+ <div class="knobs">+ <label class="knob">+ <span>Signal speed <output>420</output></span>+ <input type="range" data-key="signalSpeed" min="100" max="1200" step="20" value="420" />+ </label>+ <label class="knob">+ <span>Spawn rate (ms) <output>240</output></span>+ <input type="range" data-key="signalInterval" min="80" max="900" step="20" value="240" />+ </label>+ <label class="knob">+ <span>Cursor range <output>110</output></span>+ <input type="range" data-key="spawnRadius" min="25" max="200" step="5" value="110" />+ </label>+ <label class="knob">+ <span>Max signals <output>12</output></span>+ <input type="range" data-key="maxSignals" min="2" max="20" step="1" value="12" />+ </label>+ <label class="knob">+ <span>Passive survival <output>0.4</output></span>+ <input type="range" data-key="hopSurvival" min="0" max="0.95" step="0.05" value="0.4" />+ </label>+ <label class="knob">+ <span>Click survival <output>0.72</output></span>+ <input type="range" data-key="burstSurvival" min="0" max="0.95" step="0.01" value="0.72" />+ </label>+ <label class="knob">+ <span>Click boost <output>7</output></span>+ <input type="range" data-key="burstBoost" min="0" max="11" step="1" value="7" />+ </label>+ </div>+ <div class="reset-row">+ <button class="reset-tuning" type="button">Reset animation</button>+ </div>+ </details>++ <details class="tuning" data-panel="reveal">+ <summary>Reveal tuning</summary>+ <div class="knobs">+ <label class="knob">+ <span>Total reveal (ms) <output>3400</output></span>+ <input type="range" data-key="revealDuration" min="600" max="9000" step="100" value="3400" />+ </label>+ <label class="knob">+ <span>Tip speed <output>420</output></span>+ <input type="range" data-key="revealSpeed" min="120" max="1200" step="20" value="420" />+ </label>+ <label class="knob">+ <span>Head length <output>46</output></span>+ <input type="range" data-key="revealHead" min="12" max="160" step="2" value="46" />+ </label>+ <label class="knob">+ <span>Tip bloom <output>0.18</output></span>+ <input type="range" data-key="revealBloom" min="0" max="0.5" step="0.02" value="0.18" />+ </label>+ <label class="knob">+ <span>Hot swell <output>1.35</output></span>+ <input type="range" data-key="revealSwell" min="1" max="3" step="0.05" value="1.35" />+ </label>+ <label class="knob">+ <span>Heat fade (ms) <output>25</output></span>+ <input type="range" data-key="revealCool" min="25" max="3000" step="25" value="25" />+ </label>+ <label class="knob">+ <span>Settle tint <output>1</output></span>+ <input type="range" data-key="revealSettle" min="0" max="1" step="0.02" value="1" />+ </label>+ <label class="knob">+ <span>Colour zones (px) <output>380</output></span>+ <input type="range" data-key="revealZone" min="120" max="900" step="20" value="380" />+ </label>+ </div>+ <div class="reset-row">+ <button class="reset-tuning" type="button">Reset reveal</button>+ </div>+ </details>+ </form>++ <script type="module">+ import {+ createCircuitBackground,+ ANIMATION_PRESETS,+ REVEAL_PRESETS,+ } from "./circuit-background-reveal.js";++ const mount = document.querySelector("#circuit");+ const controls = document.querySelector("#controls");+ const seed = document.querySelector("#seed");+ const download = document.querySelector("#download");+ const downloadTile = document.querySelector("#downloadTile");+ const presetBar = document.querySelector("#presets");+ const revealBar = document.querySelector("#revealPresets");+ const replay = document.querySelector("#replay");++ // Animation on/off now lives entirely in the presets ("None" = off);+ // the page opens on None, so the board starts static.+ let signalsOn = false;+ // Which reveal style the board grows in with — the page opens on Etch,+ // so the first thing a visitor sees is the board routing itself.+ let revealStyle = "flood";++ const circuit = createCircuitBackground(mount, {+ seed: seed.value,+ signals: signalsOn,+ reveal: revealStyle,+ });++ // Every slider (density included) is a data-key knob inside a tuning+ // panel, so `tuning()` collects them all straight into the config.+ const knobs = [...document.querySelectorAll(".tuning input[type=range]")];+ const knobDefaults = new Map(knobs.map((knob) => [knob, knob.value]));+ const knobByKey = new Map(knobs.map((knob) => [knob.dataset.key, knob]));+ const tuning = () =>+ Object.fromEntries(knobs.map((knob) => [knob.dataset.key, Number(knob.value)]));+ const settings = () => ({+ seed: seed.value.trim() || "nitrogen",+ signals: signalsOn,+ reveal: revealStyle,+ ...tuning(),+ });++ // --- animation presets --------------------------------------------------+ const presetButtons = new Map();+ const clearActivePreset = () => {+ for (const button of presetButtons.values()) button.classList.remove("active");+ };+ const syncKnob = (knob) => {+ knob.parentElement.querySelector("output").value = knob.value;+ };+ const applyPreset = (name) => {+ const preset = ANIMATION_PRESETS[name];+ for (const [key, value] of Object.entries(preset)) {+ if (key === "signals") { signalsOn = value; continue; }+ const knob = knobByKey.get(key);+ if (knob) { knob.value = value; syncKnob(knob); }+ }+ clearActivePreset();+ presetButtons.get(name).classList.add("active");+ circuit.regenerate(settings());+ };+ for (const name of Object.keys(ANIMATION_PRESETS)) {+ const button = document.createElement("button");+ button.type = "button";+ button.textContent = name;+ button.addEventListener("click", () => applyPreset(name));+ presetBar.appendChild(button);+ presetButtons.set(name, button);+ }+ // Reflect the initial "None" state in the preset bar.+ presetButtons.get("None").classList.add("active");++ // --- reveal presets -----------------------------------------------------+ // Same shape as the animation presets, but these only touch how the+ // board arrives: pick a style and it regrows immediately.+ const revealButtons = new Map();+ const syncRevealBar = () => {+ for (const [name, button] of revealButtons) {+ button.classList.toggle("active", REVEAL_PRESETS[name].reveal === revealStyle);+ }+ };+ const applyRevealPreset = (name) => {+ for (const [key, value] of Object.entries(REVEAL_PRESETS[name])) {+ if (key === "reveal") { revealStyle = value; continue; }+ const knob = knobByKey.get(key);+ if (knob) { knob.value = value; syncKnob(knob); }+ }+ syncRevealBar();+ // Regrow the board that is already up — no need to re-route it.+ circuit.replayReveal(revealStyle);+ };+ for (const name of Object.keys(REVEAL_PRESETS)) {+ const button = document.createElement("button");+ button.type = "button";+ button.textContent = name;+ button.addEventListener("click", () => applyRevealPreset(name));+ revealBar.insertBefore(button, replay);+ revealButtons.set(name, button);+ }+ syncRevealBar();+ replay.addEventListener("click", () => circuit.replayReveal(revealStyle));++ // Only animation knobs invalidate the highlighted preset — retuning+ // generation (density, formations, ...) leaves the animation untouched.+ const isAnimationPanel = (node) => node.closest("details")?.dataset.panel === "animation";++ for (const knob of knobs) {+ const out = knob.parentElement.querySelector("output");+ const show = () => { out.value = knob.value; };+ show();+ knob.addEventListener("input", show);+ knob.addEventListener("change", () => {+ if (isAnimationPanel(knob)) clearActivePreset();+ circuit.regenerate(settings());+ });+ }++ // Each panel's reset button restores only that panel's own knobs.+ for (const resetButton of document.querySelectorAll(".reset-tuning")) {+ resetButton.addEventListener("click", () => {+ const panelKnobs = resetButton.closest("details").querySelectorAll("input[type=range]");+ for (const knob of panelKnobs) {+ knob.value = knobDefaults.get(knob);+ knob.parentElement.querySelector("output").value = knob.value;+ }+ if (isAnimationPanel(resetButton)) clearActivePreset();+ circuit.regenerate(settings());+ });+ }++ controls.addEventListener("submit", (event) => {+ event.preventDefault();+ circuit.regenerate(settings());+ });++ function saveBlob(text, name) {+ const blob = new Blob([text], { type: "image/svg+xml" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ URL.revokeObjectURL(url);+ }++ const slug = () => (seed.value || "seed").replace(/[^a-z0-9_-]+/gi, "-");++ download.addEventListener("click", () => {+ saveBlob(circuit.exportSvg(), `circuit-${slug()}.svg`);+ });++ downloadTile.addEventListener("click", () => {+ saveBlob(circuit.exportTileSvg(), `circuit-tile-${slug()}.svg`);+ });+ </script>+ </body>+</html>
src/index-v6.htmladded+574@@ -0,0 +1,574 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Procedural Circuit Background</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0d1117;+ --surface: #161b22;+ --border: #30363d;+ --text: #e6edf3;+ --muted: #8b949e;+ --accent: #00b8b0;+ --accent-bright: #00e6dc;+ }++ * { box-sizing: border-box; }+ html, body { min-height: 100%; margin: 0; }+ body {+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ }++ .hero {+ --circuit-hole: var(--bg);+ position: relative;+ min-height: 100svh;+ overflow: hidden;+ display: grid;+ place-items: center;+ isolation: isolate;+ }++ .circuit-layer {+ position: absolute;+ inset: 0;+ z-index: 0;+ }++ .glow {+ --atmosphere-strength: 1;+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background:+ radial-gradient(ellipse 46% 34% at 50% 45%, rgba(13, 17, 23, .64), rgba(13, 17, 23, .34) 48%, transparent 100%),+ linear-gradient(to top, var(--bg) 0, transparent 13rem);+ }++ .glow::before {+ content: "";+ position: absolute;+ inset: -12%;+ background:+ radial-gradient(ellipse 28% 38% at 22% 48%, rgba(0, 230, 220, .06), transparent 72%),+ radial-gradient(ellipse 34% 42% at 58% 46%, rgba(57, 184, 255, .045), transparent 72%),+ radial-gradient(ellipse 30% 38% at 84% 52%, rgba(140, 107, 247, .045), transparent 72%);+ mix-blend-mode: screen;+ opacity: calc(var(--atmosphere-strength) * .72);+ filter: blur(34px);+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow {+ background:+ radial-gradient(circle at 52% 44%, rgba(0, 230, 220, .06), transparent 34%),+ linear-gradient(to top, var(--bg) 0, transparent 12rem);+ animation: atmosphere-breathe 8s ease-in-out infinite alternate;+ will-change: opacity, filter;+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow::before {+ inset: -18%;+ background:+ radial-gradient(circle at 28% 38%, rgba(0, 230, 220, .075), transparent 20%),+ radial-gradient(circle at 72% 58%, rgba(100, 171, 255, .055), transparent 24%),+ radial-gradient(circle at 52% 82%, rgba(197, 179, 255, .04), transparent 18%);+ opacity: 1;+ filter: none;+ animation: atmosphere-drift 19s cubic-bezier(.45,.05,.55,.95) infinite alternate;+ will-change: transform;+ }++ @keyframes atmosphere-breathe {+ from { opacity: var(--atmosphere-low, .66); filter: saturate(.82); }+ to { opacity: var(--atmosphere-high, 1); filter: saturate(1.18); }+ }++ @keyframes atmosphere-drift {+ 0% { transform: translate3d(-3%, -2%, 0) scale(1); }+ 45% { transform: translate3d(4%, 1%, 0) scale(1.08); }+ 100% { transform: translate3d(-1%, 5%, 0) scale(1.03); }+ }++ main {+ position: relative;+ z-index: 2;+ width: min(760px, calc(100% - 40px));+ text-align: center;+ padding: 80px 0 180px;+ }++ .hero-copy { position: relative; }++ .eyebrow {+ margin: 0 0 20px;+ color: var(--accent-bright);+ font: 600 12px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .18em;+ text-transform: uppercase;+ }++ h1 {+ margin: 0;+ font-size: clamp(3.2rem, 10vw, 7.5rem);+ line-height: .9;+ letter-spacing: -.055em;+ color: transparent;+ background: linear-gradient(100deg, #e6edf3 4%, #00e6dc 38%, #39b8ff 66%, #8c6bf7 96%);+ background-clip: text;+ filter: drop-shadow(0 0 .4em rgba(255,255,255,.18));+ }++ .lede {+ max-width: 570px;+ margin: 28px auto 0;+ color: #bac6d3;+ font-size: clamp(1rem, 2vw, 1.25rem);+ line-height: 1.6;+ }++ .hint {+ margin-top: 24px;+ color: var(--muted);+ font: 500 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }++ .controls {+ position: fixed;+ left: 50%;+ bottom: 12px;+ z-index: 5;+ width: min(1180px, calc(100% - 24px));+ transform: translateX(-50%);+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ padding: 10px;+ border: 1px solid rgba(48, 54, 61, .9);+ border-radius: 12px;+ background: rgba(22, 27, 34, .88);+ box-shadow: 0 18px 70px rgba(0,0,0,.38);+ backdrop-filter: blur(18px);+ }++ label { min-width: 0; display: grid; gap: 4px; color: var(--muted); font-size: 10px; }+ label > span { display: flex; justify-content: space-between; gap: 3px; white-space: nowrap; }+ input[type="text"] {+ width: 100%;+ height: 32px;+ padding: 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 500 11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ input[type="text"]:focus { border-color: var(--accent); }+ input[type="range"] { width: 100%; accent-color: var(--accent); }++ button {+ height: 32px;+ padding: 0 11px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ background: #21262d;+ font: 700 12px system-ui, sans-serif;+ cursor: pointer;+ }+ button:hover { border-color: #59636e; background: #282e36; }+ button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); }+ button.primary:hover { background: var(--accent-bright); }++ .preset-bar {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .preset-title {+ margin-right: 3px;+ color: var(--muted);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .12em;+ text-transform: uppercase;+ }+ .preset-bar button {+ height: 28px;+ padding: 0 10px;+ color: #aab5c1;+ font-size: 11px;+ }+ .preset-bar button[aria-pressed="true"] {+ color: #082f2d;+ border-color: var(--accent);+ background: var(--accent);+ }+ .parameter-panel {+ grid-column: 1 / -1;+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ }+ .parameter-panel[hidden] { display: none; }+ /* A quiet text toggle, not a button: it opens a drawer, it does not pick a preset. */+ .preset-bar .panel-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ width: auto;+ height: 28px;+ padding: 0 2px;+ margin-left: 4px;+ color: var(--muted);+ border: 0;+ border-radius: 0;+ background: none;+ font: 600 11px system-ui, sans-serif;+ }+ .preset-bar .panel-toggle:hover { color: var(--text); border: 0; background: none; }+ .preset-bar .panel-toggle:focus-visible { outline: 1px solid var(--accent); outline-offset: 3px; }+ .preset-bar .panel-toggle[aria-expanded="true"] { color: var(--accent-bright); }+ .panel-toggle .chevron { display: inline-block; font-size: 9px; line-height: 1; transition: transform .15s ease; }+ .panel-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }++ .animation-bar {+ padding-top: 8px;+ border-top: 1px solid rgba(48, 54, 61, .72);+ }+ .movement-power {+ flex: 1 1 150px;+ max-width: 180px;+ margin-left: 6px;+ }+ .movement-power input { margin: 0; }+ .trace-count {+ margin-left: auto;+ color: var(--accent-bright);+ font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: nowrap;+ }++ @media (max-width: 1180px) {+ .controls {+ grid-template-columns: repeat(6, minmax(0, 1fr));+ max-height: calc(100svh - 24px);+ overflow-y: auto;+ }+ .parameter-panel { grid-template-columns: repeat(6, minmax(0, 1fr)); }+ .preset-bar { flex-wrap: wrap; }+ }++ @media (max-width: 760px) {+ .controls { grid-template-columns: 1fr 1fr; bottom: 12px; }+ .parameter-panel { grid-template-columns: 1fr 1fr; }+ .controls button { width: 100%; }+ .preset-title { width: 100%; }+ .trace-count { margin-left: 0; }+ main { padding-bottom: 360px; }+ }++ @media (prefers-reduced-motion: reduce) {+ .glow, .glow::before { animation: none; }+ .panel-toggle .chevron { transition: none; }+ }+ </style>+ </head>+ <body>+ <section class="hero" id="hero">+ <div class="circuit-layer" id="circuit"></div>+ <div class="glow" aria-hidden="true"></div>+ <main>+ <div class="hero-copy" data-circuit-reading-zone>+ <p class="eyebrow">Seeded SVG generator</p>+ <h1>Live circuitry</h1>+ <p class="lede">+ A procedural version of the Nitrogen hero pattern: dense routed traces, 45° chamfers,+ annular vias, continuous trace packing, and multiple animation systems for the generated topology.+ </p>+ <p class="hint" id="motionHint">Static circuit · no animation layers</p>+ </div>+ </main>+ </section>++ <form class="controls" id="controls">+ <div class="preset-bar" aria-label="Generator presets">+ <span class="preset-title">Generation</span>+ <button type="button" data-preset="original" aria-pressed="true">Original match</button>+ <button type="button" data-preset="dense" aria-pressed="false">Dense</button>+ <button type="button" data-preset="diagonal" aria-pressed="false">Diagonal sweep</button>+ <button type="button" data-preset="swirl" aria-pressed="false">Broad swirl</button>+ <button type="button" data-preset="sparse" aria-pressed="false">Sparse</button>+ <button type="button" class="panel-toggle" id="parameterToggle" aria-expanded="false" aria-controls="parameterPanel">+ Parameters<span class="chevron" aria-hidden="true">▾</span>+ </button>+ <output class="trace-count" id="traceCount">235 traces</output>+ </div>+ <div class="parameter-panel" id="parameterPanel" hidden>+ <label>+ Seed+ <input id="seed" type="text" value="nitrogen" autocomplete="off" spellcheck="false" />+ </label>+ <label>+ <span>Density <output id="fillValue">74.4%</output></span>+ <input id="fill" type="range" min="0.35" max="0.76" step="0.001" value="0.744" />+ </label>+ <label>+ <span>Avg length <output id="routeLengthValue">1.14×</output></span>+ <input id="routeLength" type="range" min="0.55" max="2.25" step="0.01" value="1.14" />+ </label>+ <label>+ <span>Primary flow <output id="horizontalFlowValue">90%</output></span>+ <input id="horizontalFlow" type="range" min="0.3" max="0.98" step="0.01" value="0.9" />+ </label>+ <label>+ <span>Angle <output id="flowAngleValue">153°</output></span>+ <input id="flowAngle" type="range" min="0" max="180" step="1" value="153" />+ </label>+ <label>+ <span>Diagonal <output id="diagonalFlowValue">100%</output></span>+ <input id="diagonalFlow" type="range" min="0" max="1" step="0.01" value="1" />+ </label>+ <label>+ <span>Long flow <output id="longFlowValue">31%</output></span>+ <input id="longFlow" type="range" min="0" max="0.36" step="0.01" value="0.31" />+ </label>+ <label>+ <span>Swirl <output id="swirlValue">82%</output></span>+ <input id="swirl" type="range" min="0" max="1.4" step="0.01" value="0.82" />+ </label>+ <label>+ <span>Swirl scale <output id="swirlScaleValue">0.72×</output></span>+ <input id="swirlScale" type="range" min="0.25" max="1.4" step="0.01" value="0.72" />+ </label>+ <label>+ <span>Jog size <output id="jogLengthValue">0.42×</output></span>+ <input id="jogLength" type="range" min="0.3" max="1.8" step="0.01" value="0.42" />+ </label>+ <label>+ <span>Channel pull <output id="channelAttractionValue">150%</output></span>+ <input id="channelAttraction" type="range" min="0" max="1.5" step="0.01" value="1.5" />+ </label>+ <label>+ <span>Scale <output id="featureScaleValue">1.37×</output></span>+ <input id="featureScale" type="range" min="0.55" max="2" step="0.01" value="1.37" />+ </label>+ </div>+ <div class="preset-bar animation-bar" aria-label="Animation presets">+ <span class="preset-title">Animation</span>+ <button type="button" data-animation-preset="none" aria-pressed="true">None</button>+ <button type="button" data-animation-preset="growth" aria-pressed="false">Trace growth</button>+ <button type="button" data-animation-preset="reflection" aria-pressed="false">Adom reflection</button>+ <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>+ <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>+ <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ <label class="movement-power">+ <span>Movement power <output id="livelinessValue">0%</output></span>+ <input id="liveliness" type="range" min="0" max="1.5" step="0.01" value="0" />+ </label>+ <button class="primary" type="submit">Generate</button>+ <button id="download" type="button">Export SVG</button>+ </div>+ </form>++ <script type="module">+ import { ANIMATION_PRESETS, createCircuitBackground } from "./circuit-background-v6.js?v=1";++ const mount = document.querySelector("#circuit");+ const controls = document.querySelector("#controls");+ const generationPresetButtons = [...document.querySelectorAll("[data-preset]")];+ const animationPresetButtons = [...document.querySelectorAll("[data-animation-preset]")];+ const traceCount = document.querySelector("#traceCount");+ const hero = document.querySelector("#hero");+ const glow = document.querySelector(".glow");+ const seed = document.querySelector("#seed");+ const parameterToggle = document.querySelector("#parameterToggle");+ const parameterPanel = document.querySelector("#parameterPanel");+ const motionHint = document.querySelector("#motionHint");+ const download = document.querySelector("#download");++ const geometryParameterIds = ["fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow", "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale"];+ const animationParameterIds = ["liveliness"];+ const parameterIds = [...geometryParameterIds, ...animationParameterIds];+ const parameters = Object.fromEntries(parameterIds.map((id) => [id, document.querySelector(`#${id}`)]));+ const presets = {+ original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37 },+ dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65 },+ diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28 },+ swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1 },+ sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88 },+ };+ const animationHints = {+ none: "Static circuit · no animation layers",+ conductor: "Move to shape the current · click anywhere to activate the network",+ adom: "Move to steer the routed field · click to launch a local bloom",+ handshake: "Move to bias the next handshake · click to request a local exchange",+ growth: "A curved routing front grows each trace from its source via to its destination",+ reflection: "Move to catch the light · click to send a quiet reflection across the board",+ };+ const formats = {+ fill: (value) => `${Number((value * 100).toFixed(1))}%`,+ routeLength: (value) => `${value.toFixed(2)}×`,+ horizontalFlow: (value) => `${Math.round(value * 100)}%`,+ flowAngle: (value) => `${Math.round(value)}°`,+ diagonalFlow: (value) => `${Math.round(value * 100)}%`,+ longFlow: (value) => `${Math.round(value * 100)}%`,+ swirl: (value) => `${Math.round(value * 100)}%`,+ swirlScale: (value) => `${value.toFixed(2)}×`,+ jogLength: (value) => `${value.toFixed(2)}×`,+ channelAttraction: (value) => `${Math.round(value * 100)}%`,+ featureScale: (value) => `${value.toFixed(2)}×`,+ liveliness: (value) => `${Math.round(value * 100)}%`,+ };++ const query = new URLSearchParams(location.search);+ const requestedAnimationPreset = query.get("animationPreset");+ const initialAnimationPreset = ANIMATION_PRESETS[requestedAnimationPreset]+ ? requestedAnimationPreset+ : "none";+ let animationOptions = { ...ANIMATION_PRESETS[initialAnimationPreset] };+ if (query.has("seed")) seed.value = query.get("seed").slice(0, 80);+ for (const id of parameterIds) {+ if (!query.has(id)) continue;+ const value = Number(query.get(id));+ if (Number.isFinite(value)) parameters[id].value = String(value);+ }+ // A deep link that tunes parameters should show them, not hide the reason the render differs.+ if (geometryParameterIds.some((id) => query.has(id))) {+ parameterToggle.setAttribute("aria-expanded", "true");+ parameterPanel.hidden = false;+ }+ if (!query.has("liveliness")) parameters.liveliness.value = String(animationOptions.liveliness);+ if (query.has("motion")) {+ animationOptions.motion = !["0", "false", "off"].includes(query.get("motion").toLowerCase());+ }++ function setActiveGenerationPreset(name) {+ for (const button of generationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.preset === name));+ }+ }++ function setActiveAnimationPreset(name) {+ for (const button of animationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.animationPreset === name));+ }+ }++ function applyAtmosphere(options) {+ const amount = Math.max(0, Math.min(1.25, options.atmosphereStrength));+ hero.dataset.animationSystem = options.animationSystem;+ hero.dataset.motion = options.motion ? "on" : "off";+ glow.style.setProperty("--atmosphere-strength", String(amount));+ glow.style.setProperty("--atmosphere-low", String(Math.min(1, amount * 0.66)));+ glow.style.setProperty("--atmosphere-high", String(Math.min(1, amount)));+ motionHint.textContent = animationHints[options.animationSystem] || animationHints.none;+ }++ if (geometryParameterIds.some((id) => query.has(id))) setActiveGenerationPreset(null);+ const animationIsCustom = animationParameterIds.some((id) => query.has(id)) || query.has("motion");+ setActiveAnimationPreset(animationIsCustom ? null : initialAnimationPreset);+ applyAtmosphere(animationOptions);++ function optionsFromControls() {+ const options = {+ ...animationOptions,+ seed: seed.value.trim() || "nitrogen",+ traceColor: "#1d2938",+ };+ for (const id of parameterIds) options[id] = Number(parameters[id].value);+ return options;+ }++ function updateOutput(id) {+ const value = Number(parameters[id].value);+ document.querySelector(`#${id}Value`).value = formats[id](value);+ }+ parameterIds.forEach(updateOutput);++ const circuit = createCircuitBackground(mount, optionsFromControls());+ let regenerationTimer;++ function updateTraceCount() {+ traceCount.value = `${circuit.field.traces.length} traces`;+ }+ updateTraceCount();++ function regenerate() {+ window.clearTimeout(regenerationTimer);+ circuit.regenerate(optionsFromControls());+ updateTraceCount();+ }++ for (const id of parameterIds) {+ parameters[id].addEventListener("input", () => {+ if (geometryParameterIds.includes(id)) setActiveGenerationPreset(null);+ else setActiveAnimationPreset(null);+ updateOutput(id);+ window.clearTimeout(regenerationTimer);+ regenerationTimer = window.setTimeout(regenerate, 140);+ });+ }+ for (const button of generationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.preset;+ const values = presets[name];+ for (const [id, value] of Object.entries(values)) {+ parameters[id].value = String(value);+ updateOutput(id);+ }+ setActiveGenerationPreset(name);+ regenerate();+ });+ }+ parameterToggle.addEventListener("click", () => {+ const expanded = parameterToggle.getAttribute("aria-expanded") === "true";+ parameterToggle.setAttribute("aria-expanded", String(!expanded));+ parameterPanel.hidden = expanded;+ });+ for (const button of animationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.animationPreset;+ animationOptions = { ...ANIMATION_PRESETS[name] };+ parameters.liveliness.value = String(animationOptions.liveliness);+ updateOutput("liveliness");+ applyAtmosphere(animationOptions);+ setActiveAnimationPreset(name);+ regenerate();+ });+ }+ seed.addEventListener("change", regenerate);++ controls.addEventListener("submit", (event) => {+ event.preventDefault();+ regenerate();+ });++ function saveBlob(text, name) {+ const blob = new Blob([text], { type: "image/svg+xml" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ URL.revokeObjectURL(url);+ }++ const slug = () => (seed.value || "seed").replace(/[^a-z0-9_-]+/gi, "-");++ download.addEventListener("click", () => {+ saveBlob(circuit.exportSvg(), `circuit-${slug()}.svg`);+ });++ </script>+ </body>+</html>
src/index-v7.htmladded+1053@@ -0,0 +1,1053 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Procedural Circuit Background</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0d1117;+ --surface: #161b22;+ --border: #30363d;+ --text: #e6edf3;+ --muted: #8b949e;+ --accent: #00b8b0;+ --accent-bright: #00e6dc;+ }++ * { box-sizing: border-box; }+ html, body { min-height: 100%; margin: 0; }+ body {+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ }++ .hero {+ --circuit-hole: var(--bg);+ position: relative;+ min-height: 100svh;+ overflow: hidden;+ display: grid;+ place-items: center;+ isolation: isolate;+ }++ .hero[data-reveal-system="scroll"] {+ min-height: 300svh;+ place-items: start center;+ }++ .hero[data-reveal-system="scroll"] main {+ position: relative;+ top: auto;+ min-height: 100svh;+ display: grid;+ place-items: center;+ }++ .circuit-layer {+ position: absolute;+ inset: 0;+ z-index: 0;+ }++ .glow {+ --atmosphere-strength: 1;+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background:+ radial-gradient(ellipse 46% 34% at 50% 45%, rgba(13, 17, 23, .64), rgba(13, 17, 23, .34) 48%, transparent 100%),+ linear-gradient(to top, var(--bg) 0, transparent 13rem);+ }++ .glow::before {+ content: "";+ position: absolute;+ inset: -12%;+ background:+ radial-gradient(ellipse 28% 38% at 22% 48%, rgba(0, 230, 220, .06), transparent 72%),+ radial-gradient(ellipse 34% 42% at 58% 46%, rgba(57, 184, 255, .045), transparent 72%),+ radial-gradient(ellipse 30% 38% at 84% 52%, rgba(140, 107, 247, .045), transparent 72%);+ mix-blend-mode: screen;+ opacity: calc(var(--atmosphere-strength) * .72);+ filter: blur(34px);+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow {+ background:+ radial-gradient(circle at 52% 44%, rgba(0, 230, 220, .06), transparent 34%),+ linear-gradient(to top, var(--bg) 0, transparent 12rem);+ animation: atmosphere-breathe 8s ease-in-out infinite alternate;+ will-change: opacity, filter;+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow::before {+ inset: -18%;+ background:+ radial-gradient(circle at 28% 38%, rgba(0, 230, 220, .075), transparent 20%),+ radial-gradient(circle at 72% 58%, rgba(100, 171, 255, .055), transparent 24%),+ radial-gradient(circle at 52% 82%, rgba(197, 179, 255, .04), transparent 18%);+ opacity: 1;+ filter: none;+ animation: atmosphere-drift 19s cubic-bezier(.45,.05,.55,.95) infinite alternate;+ will-change: transform;+ }++ @keyframes atmosphere-breathe {+ from { opacity: var(--atmosphere-low, .66); filter: saturate(.82); }+ to { opacity: var(--atmosphere-high, 1); filter: saturate(1.18); }+ }++ @keyframes atmosphere-drift {+ 0% { transform: translate3d(-3%, -2%, 0) scale(1); }+ 45% { transform: translate3d(4%, 1%, 0) scale(1.08); }+ 100% { transform: translate3d(-1%, 5%, 0) scale(1.03); }+ }++ main {+ position: relative;+ z-index: 2;+ width: min(760px, calc(100% - 40px));+ text-align: center;+ padding: 80px 0 180px;+ }++ .hero-copy { position: relative; }++ .eyebrow {+ margin: 0 0 20px;+ color: var(--accent-bright);+ font: 600 12px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .18em;+ text-transform: uppercase;+ }++ h1 {+ margin: 0;+ font-size: clamp(3.2rem, 10vw, 7.5rem);+ line-height: .9;+ letter-spacing: -.055em;+ color: transparent;+ background: linear-gradient(100deg, #e6edf3 4%, #00e6dc 38%, #39b8ff 66%, #8c6bf7 96%);+ background-clip: text;+ filter: drop-shadow(0 0 .4em rgba(255,255,255,.18));+ }++ .lede {+ max-width: 570px;+ margin: 28px auto 0;+ color: #bac6d3;+ font-size: clamp(1rem, 2vw, 1.25rem);+ line-height: 1.6;+ }++ .hint {+ margin-top: 24px;+ color: var(--muted);+ font: 500 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }++ .controls {+ position: fixed;+ left: 50%;+ bottom: 12px;+ z-index: 5;+ width: min(1180px, calc(100% - 24px));+ transform: translateX(-50%);+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ padding: 10px;+ border: 1px solid rgba(48, 54, 61, .9);+ border-radius: 12px;+ background: rgba(22, 27, 34, .88);+ box-shadow: 0 18px 70px rgba(0,0,0,.38);+ backdrop-filter: blur(18px);+ }++ label { min-width: 0; display: grid; gap: 4px; color: var(--muted); font-size: 10px; }+ label > span { display: flex; justify-content: space-between; gap: 3px; white-space: nowrap; }+ input[type="text"] {+ width: 100%;+ height: 32px;+ padding: 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 500 11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ input[type="text"]:focus { border-color: var(--accent); }+ input[type="range"] { width: 100%; accent-color: var(--accent); }+ select {+ width: 100%;+ height: 32px;+ padding: 0 28px 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 600 11px system-ui, sans-serif;+ }+ select:focus { border-color: var(--accent); }++ button {+ height: 32px;+ padding: 0 11px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ background: #21262d;+ font: 700 12px system-ui, sans-serif;+ cursor: pointer;+ }+ button:hover { border-color: #59636e; background: #282e36; }+ button:disabled { opacity: .48; cursor: default; }+ button:disabled:hover { border-color: var(--border); background: #21262d; }+ button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); }+ button.primary:hover { background: var(--accent-bright); }++ .preset-bar {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .preset-title {+ margin-right: 3px;+ color: var(--muted);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .12em;+ text-transform: uppercase;+ }+ .preset-bar button {+ height: 28px;+ padding: 0 10px;+ color: #aab5c1;+ font-size: 11px;+ }+ .preset-bar button[aria-pressed="true"] {+ color: #082f2d;+ border-color: var(--accent);+ background: var(--accent);+ }+ .parameter-panel {+ grid-column: 1 / -1;+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ }+ .parameter-panel[hidden] { display: none; }+ .reveal-options-panel {+ position: absolute;+ right: 10px;+ bottom: calc(100% + 8px);+ width: min(760px, calc(100vw - 44px));+ max-height: calc(100svh - 116px);+ overflow-y: auto;+ padding: 12px;+ border: 1px solid rgba(48, 54, 61, .96);+ border-radius: 12px;+ background: rgba(18, 23, 30, .97);+ box-shadow: 0 18px 70px rgba(0,0,0,.48);+ backdrop-filter: blur(20px);+ }+ .reveal-options-panel[hidden] { display: none; }+ .reveal-options-heading {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 10px;+ }+ .reveal-options-heading strong {+ color: var(--text);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .1em;+ text-transform: uppercase;+ }+ .reveal-options-heading span { color: var(--muted); font-size: 10px; }+ .reveal-options-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 10px 12px;+ }+ .reveal-option[hidden] { display: none; }+ .reveal-option output { color: #c4d0dc; }+ /* A quiet text toggle, not a button: it opens a drawer, it does not pick a preset. */+ .preset-bar .panel-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ width: auto;+ height: 28px;+ padding: 0 2px;+ margin-left: 4px;+ color: var(--muted);+ border: 0;+ border-radius: 0;+ background: none;+ font: 600 11px system-ui, sans-serif;+ }+ .preset-bar .panel-toggle:hover { color: var(--text); border: 0; background: none; }+ .preset-bar .panel-toggle:focus-visible { outline: 1px solid var(--accent); outline-offset: 3px; }+ .preset-bar .panel-toggle[aria-expanded="true"] { color: var(--accent-bright); }+ .panel-toggle .chevron { display: inline-block; font-size: 9px; line-height: 1; transition: transform .15s ease; }+ .panel-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }++ .motion-bar {+ padding-top: 8px;+ border-top: 1px solid rgba(48, 54, 61, .72);+ }+ .preset-group {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .group-divider {+ align-self: stretch;+ width: 1px;+ min-height: 22px;+ margin: 0 2px;+ background: rgba(48, 54, 61, .8);+ }+ .reveal-group[data-disabled="true"] { opacity: .48; }+ .reveal-group[data-disabled="true"] button { pointer-events: none; }+ .preset-bar .replay-button {+ padding-inline: 7px;+ color: var(--muted);+ border-style: dashed;+ }+ .movement-power {+ flex: 1 1 150px;+ max-width: 180px;+ margin-left: 6px;+ }+ .movement-power input { margin: 0; }+ .trace-count {+ margin-left: auto;+ color: var(--accent-bright);+ font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: nowrap;+ }++ @media (max-width: 1180px) {+ .controls {+ grid-template-columns: repeat(6, minmax(0, 1fr));+ max-height: calc(100svh - 24px);+ overflow-y: auto;+ }+ .parameter-panel { grid-template-columns: repeat(6, minmax(0, 1fr)); }+ .controls:has(.reveal-options-panel:not([hidden])) { overflow: visible; }+ .preset-bar { flex-wrap: wrap; }+ .preset-group { flex-wrap: wrap; }+ }++ @media (max-width: 760px) {+ .controls { grid-template-columns: 1fr 1fr; bottom: 12px; }+ .parameter-panel { grid-template-columns: 1fr 1fr; }+ .controls button { width: 100%; }+ .preset-title { width: 100%; }+ .trace-count { margin-left: 0; }+ main { padding-bottom: 360px; }+ .reveal-options-panel {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 8px);+ width: auto;+ max-height: calc(100svh - 156px);+ overflow-y: auto;+ border-radius: 16px 16px 10px 10px;+ }+ .reveal-options-grid { grid-template-columns: 1fr 1fr; }+ }++ @media (max-width: 460px) {+ .reveal-options-grid { grid-template-columns: 1fr; }+ }++ @media (prefers-reduced-motion: reduce) {+ .glow, .glow::before { animation: none; }+ .panel-toggle .chevron { transition: none; }+ }+ </style>+ </head>+ <body>+ <section class="hero" id="hero">+ <div class="circuit-layer" id="circuit"></div>+ <div class="glow" aria-hidden="true"></div>+ <main>+ <div class="hero-copy" data-circuit-reading-zone>+ <p class="eyebrow">Seeded SVG generator</p>+ <h1>Live circuitry</h1>+ <p class="lede">+ A procedural version of the Nitrogen hero pattern: dense routed traces, 45° chamfers,+ annular vias, continuous trace packing, and separate reveal and ambient animation systems.+ </p>+ <p class="hint" id="motionHint">All traces arrive fully routed · no ambient movement</p>+ </div>+ </main>+ </section>++ <form class="controls" id="controls">+ <div class="preset-bar" aria-label="Generator presets">+ <span class="preset-title">Generation</span>+ <button type="button" data-preset="original" aria-pressed="true">Original match</button>+ <button type="button" data-preset="dense" aria-pressed="false">Dense</button>+ <button type="button" data-preset="diagonal" aria-pressed="false">Diagonal sweep</button>+ <button type="button" data-preset="swirl" aria-pressed="false">Broad swirl</button>+ <button type="button" data-preset="sparse" aria-pressed="false">Sparse</button>+ <button type="button" class="panel-toggle" id="parameterToggle" aria-expanded="false" aria-controls="parameterPanel">+ Parameters<span class="chevron" aria-hidden="true">▾</span>+ </button>+ <output class="trace-count" id="traceCount">235 traces</output>+ </div>+ <div class="parameter-panel" id="parameterPanel" hidden>+ <label>+ Seed+ <input id="seed" type="text" value="nitrogen" autocomplete="off" spellcheck="false" />+ </label>+ <label>+ <span>Density <output id="fillValue">74.4%</output></span>+ <input id="fill" type="range" min="0.35" max="0.76" step="0.001" value="0.744" />+ </label>+ <label>+ <span>Avg length <output id="routeLengthValue">1.14×</output></span>+ <input id="routeLength" type="range" min="0.55" max="2.25" step="0.01" value="1.14" />+ </label>+ <label>+ <span>Primary flow <output id="horizontalFlowValue">90%</output></span>+ <input id="horizontalFlow" type="range" min="0.3" max="0.98" step="0.01" value="0.9" />+ </label>+ <label>+ <span>Angle <output id="flowAngleValue">153°</output></span>+ <input id="flowAngle" type="range" min="0" max="180" step="1" value="153" />+ </label>+ <label>+ <span>Diagonal <output id="diagonalFlowValue">100%</output></span>+ <input id="diagonalFlow" type="range" min="0" max="1" step="0.01" value="1" />+ </label>+ <label>+ <span>Long flow <output id="longFlowValue">31%</output></span>+ <input id="longFlow" type="range" min="0" max="0.36" step="0.01" value="0.31" />+ </label>+ <label>+ <span>Swirl <output id="swirlValue">82%</output></span>+ <input id="swirl" type="range" min="0" max="1.4" step="0.01" value="0.82" />+ </label>+ <label>+ <span>Swirl scale <output id="swirlScaleValue">0.72×</output></span>+ <input id="swirlScale" type="range" min="0.25" max="1.4" step="0.01" value="0.72" />+ </label>+ <label>+ <span>Jog size <output id="jogLengthValue">0.42×</output></span>+ <input id="jogLength" type="range" min="0.3" max="1.8" step="0.01" value="0.42" />+ </label>+ <label>+ <span>Channel pull <output id="channelAttractionValue">150%</output></span>+ <input id="channelAttraction" type="range" min="0" max="1.5" step="0.01" value="1.5" />+ </label>+ <label>+ <span>Scale <output id="featureScaleValue">1.37×</output></span>+ <input id="featureScale" type="range" min="0.55" max="2" step="0.01" value="1.37" />+ </label>+ </div>+ <div class="preset-bar motion-bar" aria-label="Trace reveal and animation presets">+ <div class="preset-group reveal-group" id="revealGroup" aria-label="Trace reveal presets">+ <span class="preset-title">Reveal</span>+ <button type="button" data-reveal-preset="instant" aria-pressed="true">Instant</button>+ <button type="button" data-reveal-preset="flow" aria-pressed="false">Flow sweep</button>+ <button type="button" data-reveal-preset="scroll" aria-pressed="false">Scroll weave</button>+ <button class="replay-button" id="replayReveal" type="button">Replay</button>+ <button type="button" class="panel-toggle" id="revealOptionsToggle" aria-expanded="false" aria-controls="revealOptionsPanel">+ Options<span class="chevron" aria-hidden="true">▾</span>+ </button>+ </div>+ <span class="group-divider" aria-hidden="true"></span>+ <div class="preset-group animation-group" aria-label="Ambient animation presets">+ <span class="preset-title">Animation</span>+ <button type="button" data-animation-preset="none" aria-pressed="true">None</button>+ <button type="button" data-animation-preset="reflection" aria-pressed="false">Reflection</button>+ <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>+ <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>+ <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ </div>+ <label class="movement-power">+ <span>Movement power <output id="livelinessValue">0%</output></span>+ <input id="liveliness" type="range" min="0" max="1.5" step="0.01" value="0" />+ </label>+ <button class="primary" type="submit">Generate</button>+ <button id="download" type="button">Export SVG</button>+ </div>+ <section class="reveal-options-panel" id="revealOptionsPanel" aria-label="Reveal options" hidden>+ <div class="reveal-options-heading">+ <strong id="revealOptionsTitle">Flow sweep options</strong>+ <span>Changes apply to this reveal preset</span>+ </div>+ <div class="reveal-options-grid">+ <label class="reveal-option" data-reveal-for="flow scroll">+ Spawn pattern+ <select id="spawnMode">+ <option value="flow">Directional flow</option>+ <option value="radial">Radial</option>+ <option value="edges">From edges</option>+ <option value="scatter">Scatter</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn angle <output id="spawnAngleValue">90°</output></span>+ <input id="spawnAngle" type="range" min="0" max="359" step="1" value="90" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn swirl <output id="spawnSwirlValue">7.5%</output></span>+ <input id="spawnSwirl" type="range" min="0" max="0.35" step="0.005" value="0.075" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Trace glow <output id="revealGlowValue">88%</output></span>+ <input id="revealGlow" type="range" min="0" max="1" step="0.01" value="0.88" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Sweep duration <output id="revealDurationValue">7.6 s</output></span>+ <input id="revealDuration" type="range" min="2600" max="18000" step="100" value="7600" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Active traces <output id="revealMaxActiveTracesValue">48</output></span>+ <input id="revealMaxActiveTraces" type="range" min="12" max="96" step="1" value="48" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Trace duration <output id="traceDurationValue">0.95 s</output></span>+ <input id="traceDuration" type="range" min="350" max="2000" step="25" value="950" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Launch rate <output id="revealLaunchRateValue">24/s</output></span>+ <input id="revealLaunchRate" type="range" min="6" max="80" step="1" value="24" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Active traces <output id="maxActiveTracesValue">72</output></span>+ <input id="maxActiveTraces" type="range" min="12" max="160" step="1" value="72" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Speed response <output id="scrollSpeedResponseValue">60%</output></span>+ <input id="scrollSpeedResponse" type="range" min="0" max="1" step="0.01" value="0.6" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Reveal lead <output id="unlockLeadValue">2.5%</output></span>+ <input id="unlockLead" type="range" min="0" max="0.2" step="0.005" value="0.025" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ Continue generation+ <select id="continuousGeneration">+ <option value="true">On</option>+ <option value="false">Off</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Generate ahead <output id="generationAheadScreensValue">2 screens</output></span>+ <input id="generationAheadScreens" type="range" min="1" max="4" step="0.25" value="2" />+ </label>+ </div>+ </section>+ </form>++ <script type="module">+ import { ANIMATION_PRESETS, REVEAL_PRESETS, createCircuitBackground } from "./circuit-background-v7.js?v=1";++ const mount = document.querySelector("#circuit");+ const controls = document.querySelector("#controls");+ const generationPresetButtons = [...document.querySelectorAll("[data-preset]")];+ const revealPresetButtons = [...document.querySelectorAll("[data-reveal-preset]")];+ const animationPresetButtons = [...document.querySelectorAll("[data-animation-preset]")];+ const traceCount = document.querySelector("#traceCount");+ const hero = document.querySelector("#hero");+ const glow = document.querySelector(".glow");+ const seed = document.querySelector("#seed");+ const parameterToggle = document.querySelector("#parameterToggle");+ const parameterPanel = document.querySelector("#parameterPanel");+ const motionHint = document.querySelector("#motionHint");+ const revealGroup = document.querySelector("#revealGroup");+ const replayReveal = document.querySelector("#replayReveal");+ const revealOptionsToggle = document.querySelector("#revealOptionsToggle");+ const revealOptionsPanel = document.querySelector("#revealOptionsPanel");+ const revealOptionsTitle = document.querySelector("#revealOptionsTitle");+ const revealOptionElements = [...document.querySelectorAll("[data-reveal-for]")];+ const revealOptionIds = [+ "spawnMode", "spawnAngle", "spawnSwirl", "revealGlow", "revealDuration",+ "revealMaxActiveTraces", "traceDuration", "revealLaunchRate", "maxActiveTraces",+ "scrollSpeedResponse", "unlockLead", "continuousGeneration", "generationAheadScreens",+ ];+ const revealControls = Object.fromEntries(revealOptionIds.map((id) => [id, document.querySelector("#" + id)]));+ const download = document.querySelector("#download");++ const geometryParameterIds = ["fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow", "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale"];+ const animationParameterIds = ["liveliness"];+ const parameterIds = [...geometryParameterIds, ...animationParameterIds];+ const parameters = Object.fromEntries(parameterIds.map((id) => [id, document.querySelector(`#${id}`)]));+ const presets = {+ original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37 },+ dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65 },+ diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28 },+ swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1 },+ sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88 },+ };+ const revealHints = {+ instant: "All traces arrive fully routed",+ flow: "A curved front grows every route from via to via",+ scroll: "Scroll unlocks routes; each one grows on its own timeline",+ };+ const animationHints = {+ none: "no ambient movement",+ conductor: "move to shape the current · click to activate the network",+ adom: "move to steer the routed field · click to launch a local bloom",+ handshake: "move to bias the next handshake · click to request a local exchange",+ reflection: "move to catch the light · click to send a quiet reflection",+ };+ const formats = {+ fill: (value) => `${Number((value * 100).toFixed(1))}%`,+ routeLength: (value) => `${value.toFixed(2)}×`,+ horizontalFlow: (value) => `${Math.round(value * 100)}%`,+ flowAngle: (value) => `${Math.round(value)}°`,+ diagonalFlow: (value) => `${Math.round(value * 100)}%`,+ longFlow: (value) => `${Math.round(value * 100)}%`,+ swirl: (value) => `${Math.round(value * 100)}%`,+ swirlScale: (value) => `${value.toFixed(2)}×`,+ jogLength: (value) => `${value.toFixed(2)}×`,+ channelAttraction: (value) => `${Math.round(value * 100)}%`,+ featureScale: (value) => `${value.toFixed(2)}×`,+ liveliness: (value) => `${Math.round(value * 100)}%`,+ };+ const revealFormats = {+ spawnAngle: (value) => Math.round(value) + "°",+ spawnSwirl: (value) => Number((value * 100).toFixed(1)) + "%",+ revealGlow: (value) => Math.round(value * 100) + "%",+ revealDuration: (value) => (value / 1000).toFixed(1) + " s",+ revealMaxActiveTraces: (value) => String(Math.round(value)),+ traceDuration: (value) => (value / 1000).toFixed(2) + " s",+ revealLaunchRate: (value) => Math.round(value) + "/s",+ maxActiveTraces: (value) => String(Math.round(value)),+ scrollSpeedResponse: (value) => Math.round(value * 100) + "%",+ unlockLead: (value) => Number((value * 100).toFixed(1)) + "%",+ generationAheadScreens: (value) => Number(value.toFixed(2)) + (value === 1 ? " screen" : " screens"),+ };++ function updateRevealOptionOutput(id) {+ if (!revealFormats[id]) return;+ const output = document.querySelector("#" + id + "Value");+ if (output) output.value = revealFormats[id](Number(revealControls[id].value));+ }++ function closeRevealOptions() {+ revealOptionsToggle.setAttribute("aria-expanded", "false");+ revealOptionsPanel.hidden = true;+ }++ function syncRevealOptionAvailability(name) {+ const state = revealOptionState[name];+ if (!state) return;+ const directional = state.spawnMode === "flow";+ revealControls.spawnAngle.disabled = !directional;+ revealControls.spawnSwirl.disabled = !directional;+ revealControls.generationAheadScreens.disabled = name === "scroll"+ && !state.continuousGeneration;+ }++ function syncRevealOptionControls(name) {+ if (name !== "flow" && name !== "scroll") return;+ const state = revealOptionState[name];+ for (const element of revealOptionElements) {+ element.hidden = !element.dataset.revealFor.split(" ").includes(name);+ }+ for (const id of revealOptionIds) {+ if (!(id in state)) continue;+ const control = revealControls[id];+ control.value = id === "continuousGeneration"+ ? String(Boolean(state[id]))+ : String(state[id]);+ if (id === "continuousGeneration") state[id] = control.value === "true";+ else if (id === "spawnMode") state[id] = control.value;+ else state[id] = Number(control.value);+ updateRevealOptionOutput(id);+ }+ revealOptionsTitle.textContent = name === "flow" ? "Flow sweep options" : "Scroll weave options";+ syncRevealOptionAvailability(name);+ }+++ const query = new URLSearchParams(location.search);+ const requestedAnimationPreset = query.get("animationPreset");+ const requestedRevealPreset = query.get("revealPreset");+ const legacyGrowthLink = requestedAnimationPreset === "growth";+ const initialAnimationPreset = !legacyGrowthLink && ANIMATION_PRESETS[requestedAnimationPreset]+ ? requestedAnimationPreset+ : "none";+ const initialRevealPreset = legacyGrowthLink+ ? "flow"+ : REVEAL_PRESETS[requestedRevealPreset]+ ? requestedRevealPreset+ : "instant";+ let animationOptions = { ...ANIMATION_PRESETS[initialAnimationPreset] };+ const revealOptionState = {+ flow: {+ ...REVEAL_PRESETS.flow,+ spawnMode: REVEAL_PRESETS.flow.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.flow.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.flow.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.flow.revealGlow ?? 0.88,+ revealDuration: REVEAL_PRESETS.flow.revealDuration ?? 7600,+ revealMaxActiveTraces: REVEAL_PRESETS.flow.revealMaxActiveTraces ?? 48,+ },+ scroll: {+ ...REVEAL_PRESETS.scroll,+ spawnMode: REVEAL_PRESETS.scroll.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.scroll.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.scroll.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.scroll.revealGlow ?? 0.82,+ traceDuration: REVEAL_PRESETS.scroll.traceDuration ?? 950,+ revealLaunchRate: REVEAL_PRESETS.scroll.revealLaunchRate ?? 24,+ maxActiveTraces: REVEAL_PRESETS.scroll.maxActiveTraces ?? 72,+ scrollSpeedResponse: REVEAL_PRESETS.scroll.scrollSpeedResponse ?? 0.6,+ unlockLead: REVEAL_PRESETS.scroll.unlockLead ?? 0.025,+ continuousGeneration: REVEAL_PRESETS.scroll.continuousGeneration ?? true,+ generationAheadScreens: REVEAL_PRESETS.scroll.generationAheadScreens ?? 2,+ },+ };+ let activeRevealPreset = initialRevealPreset;+ const validSpawnModes = new Set(["flow", "radial", "edges", "scatter"]);+ if (activeRevealPreset === "flow" || activeRevealPreset === "scroll") {+ for (const id of revealOptionIds) {+ if (!query.has(id) || !(id in revealOptionState[activeRevealPreset])) continue;+ if (id === "spawnMode") {+ const value = query.get(id);+ if (validSpawnModes.has(value)) revealOptionState[activeRevealPreset][id] = value;+ } else if (id === "continuousGeneration") {+ revealOptionState[activeRevealPreset][id] = !["0", "false", "off"].includes(query.get(id).toLowerCase());+ } else {+ const value = Number(query.get(id));+ if (Number.isFinite(value)) revealOptionState[activeRevealPreset][id] = value;+ }+ }+ }+ if (activeRevealPreset !== "instant" && query.has("revealMotion")) {+ revealOptionState[activeRevealPreset].revealMotion = !["0", "false", "off"].includes(+ query.get("revealMotion").toLowerCase(),+ );+ }+ let revealOptions = activeRevealPreset === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[activeRevealPreset] };+ const revealQueryPresent = revealOptionIds.some((id) => query.has(id));+ if (activeRevealPreset !== "instant") syncRevealOptionControls(activeRevealPreset);+ if (activeRevealPreset !== "instant" && revealQueryPresent) {+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ }+ if (query.has("seed")) seed.value = query.get("seed").slice(0, 80);+ for (const id of parameterIds) {+ if (!query.has(id)) continue;+ const value = Number(query.get(id));+ if (Number.isFinite(value)) parameters[id].value = String(value);+ }+ // A deep link that tunes parameters should show them, not hide the reason the render differs.+ if (geometryParameterIds.some((id) => query.has(id))) {+ parameterToggle.setAttribute("aria-expanded", "true");+ parameterPanel.hidden = false;+ }+ if (!query.has("liveliness")) parameters.liveliness.value = String(animationOptions.liveliness);+ if (query.has("motion")) {+ animationOptions.motion = !["0", "false", "off"].includes(query.get("motion").toLowerCase());+ }++ function setActiveGenerationPreset(name) {+ for (const button of generationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.preset === name));+ }+ }++ function setActiveRevealPreset(name) {+ for (const button of revealPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.revealPreset === name));+ }+ }++ function setActiveAnimationPreset(name) {+ for (const button of animationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.animationPreset === name));+ }+ }++ function updatePresentation() {+ const routed = animationOptions.animationSystem === "adom";+ const revealSystem = routed ? "instant" : revealOptions.revealSystem;+ hero.dataset.revealSystem = revealSystem;+ revealGroup.dataset.disabled = String(routed);+ revealGroup.setAttribute("aria-disabled", String(routed));+ setActiveRevealPreset(routed ? "instant" : activeRevealPreset);+ for (const button of revealPresetButtons) button.disabled = routed;+ replayReveal.disabled = routed || !(+ revealSystem === "flow"+ || (revealSystem === "scroll" && revealOptions.continuousGeneration)+ );+ revealOptionsToggle.disabled = routed || revealSystem === "instant";+ if (revealOptionsToggle.disabled) closeRevealOptions();+ const revealHint = revealSystem === "scroll" && revealOptions.continuousGeneration+ ? "Scroll queues trace growth and generates new field sections ahead"+ : revealHints[revealSystem] || revealHints.instant;+ motionHint.textContent = routed+ ? "Routed field owns its trace lifecycle · move to steer it and click for a local bloom"+ : [+ revealHint,+ animationHints[animationOptions.animationSystem] || animationHints.none,+ ].join(" · ");+ }++ function applyAtmosphere(options) {+ const amount = Math.max(0, Math.min(1.25, options.atmosphereStrength));+ hero.dataset.animationSystem = options.animationSystem;+ hero.dataset.motion = options.motion ? "on" : "off";+ glow.style.setProperty("--atmosphere-strength", String(amount));+ glow.style.setProperty("--atmosphere-low", String(Math.min(1, amount * 0.66)));+ glow.style.setProperty("--atmosphere-high", String(Math.min(1, amount)));+ updatePresentation();+ }++ function applyReveal() {+ updatePresentation();+ }++ if (geometryParameterIds.some((id) => query.has(id))) setActiveGenerationPreset(null);+ const animationIsCustom = animationParameterIds.some((id) => query.has(id)) || query.has("motion");+ setActiveRevealPreset(initialRevealPreset);+ setActiveAnimationPreset(animationIsCustom ? null : initialAnimationPreset);+ applyReveal();+ applyAtmosphere(animationOptions);++ function optionsFromControls() {+ const options = {+ ...revealOptions,+ ...animationOptions,+ seed: seed.value.trim() || "nitrogen",+ traceColor: "#1d2938",+ };+ for (const id of parameterIds) options[id] = Number(parameters[id].value);+ return options;+ }++ function updateOutput(id) {+ const value = Number(parameters[id].value);+ document.querySelector(`#${id}Value`).value = formats[id](value);+ }+ parameterIds.forEach(updateOutput);++ const circuit = createCircuitBackground(mount, optionsFromControls());+ let regenerationTimer;+ let animationTimer;+ let revealUpdateTimer;++ function commitRevealOptions() {+ window.clearTimeout(revealUpdateTimer);+ if (typeof circuit.setReveal === "function") {+ circuit.setReveal(revealOptions);+ } else {+ circuit.regenerate(optionsFromControls());+ }+ queueTraceCount();+ }++ function scheduleRevealUpdate() {+ window.clearTimeout(revealUpdateTimer);+ revealUpdateTimer = window.setTimeout(commitRevealOptions, 120);+ }++ let lastTraceCountText = "";+ function updateTraceCount(stats) {+ const total = circuit.field.traces.length;+ const text = stats?.system === "scroll-trace-reveal"+ ? Math.min(total, stats.completedTraces) + " / " + total + " routed"+ : total + " traces";+ if (text === lastTraceCountText) return;+ lastTraceCountText = text;+ traceCount.value = text;+ }+ let traceCountFrame = 0;+ function tickTraceCount() {+ traceCountFrame = 0;+ const stats = circuit.revealStats;+ updateTraceCount(stats);+ if (+ stats?.continuous+ || (+ stats?.system === "scroll-trace-reveal"+ && (stats.queuedTraces > 0 || stats.activeTraces > 0)+ )+ ) {+ traceCountFrame = window.setTimeout(tickTraceCount, 200);+ }+ }+ function queueTraceCount() {+ if (traceCountFrame) return;+ traceCountFrame = window.requestAnimationFrame(tickTraceCount);+ }+ window.addEventListener("scroll", queueTraceCount, { passive: true });+ window.addEventListener("resize", queueTraceCount, { passive: true });+ queueTraceCount();+ const requestedScrollProgress = Number(query.get("scrollProgress"));+ const requestedScrollScreens = Number(query.get("scrollScreens"));+ if (+ initialRevealPreset === "scroll"+ && revealOptions.continuousGeneration+ && Number.isFinite(requestedScrollScreens)+ && requestedScrollScreens > 0+ ) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const target = requestedScrollScreens * window.innerHeight;+ const startedAt = performance.now();+ const advance = () => {+ const remaining = target - window.scrollY;+ if (remaining <= 2 || performance.now() - startedAt > 15000) return;+ window.scrollBy(0, Math.min(window.innerHeight * 0.42, remaining));+ window.setTimeout(advance, 180);+ };+ advance();+ }));+ } else if (initialRevealPreset === "scroll" && Number.isFinite(requestedScrollProgress)) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const travel = Math.max(0, hero.scrollHeight - window.innerHeight);+ window.scrollTo(0, travel * Math.max(0, Math.min(1, requestedScrollProgress)));+ }));+ }+++ function regenerate() {+ window.clearTimeout(regenerationTimer);+ circuit.regenerate(optionsFromControls());+ queueTraceCount();+ }++ for (const id of parameterIds) {+ parameters[id].addEventListener("input", () => {+ updateOutput(id);+ if (!geometryParameterIds.includes(id)) {+ setActiveAnimationPreset(null);+ animationOptions = { ...animationOptions, [id]: Number(parameters[id].value) };+ applyAtmosphere(animationOptions);+ window.clearTimeout(animationTimer);+ if (animationOptions.animationSystem === "adom") {+ animationTimer = window.setTimeout(() => circuit.setAnimation(animationOptions), 140);+ } else {+ circuit.setAnimation(animationOptions);+ }+ return;+ }+ setActiveGenerationPreset(null);+ window.clearTimeout(regenerationTimer);+ regenerationTimer = window.setTimeout(regenerate, 140);+ });+ }+ for (const button of generationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.preset;+ const values = presets[name];+ for (const [id, value] of Object.entries(values)) {+ parameters[id].value = String(value);+ updateOutput(id);+ }+ setActiveGenerationPreset(name);+ regenerate();+ });+ }+ parameterToggle.addEventListener("click", () => {+ const expanded = parameterToggle.getAttribute("aria-expanded") === "true";+ parameterToggle.setAttribute("aria-expanded", String(!expanded));+ parameterPanel.hidden = expanded;+ });+ revealOptionsToggle.addEventListener("click", () => {+ if (revealOptionsToggle.disabled) return;+ const expanded = revealOptionsToggle.getAttribute("aria-expanded") === "true";+ if (expanded) {+ closeRevealOptions();+ return;+ }+ syncRevealOptionControls(activeRevealPreset);+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ });+ for (const id of revealOptionIds) {+ revealControls[id].addEventListener("input", () => {+ if (activeRevealPreset !== "flow" && activeRevealPreset !== "scroll") return;+ let value;+ if (id === "spawnMode") value = revealControls[id].value;+ else if (id === "continuousGeneration") value = revealControls[id].value === "true";+ else value = Number(revealControls[id].value);+ revealOptionState[activeRevealPreset][id] = value;+ revealOptions = { ...revealOptionState[activeRevealPreset] };+ updateRevealOptionOutput(id);+ syncRevealOptionAvailability(activeRevealPreset);+ applyReveal();+ scheduleRevealUpdate();+ });+ }+ for (const button of revealPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.revealPreset;+ activeRevealPreset = name;+ revealOptions = name === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[name] };+ if (name !== "instant") syncRevealOptionControls(name);+ setActiveRevealPreset(name);+ applyReveal();+ commitRevealOptions();+ });+ }+ replayReveal.addEventListener("click", () => {+ circuit.triggerReveal();+ });+ for (const button of animationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.animationPreset;+ animationOptions = { ...ANIMATION_PRESETS[name] };+ parameters.liveliness.value = String(animationOptions.liveliness);+ updateOutput("liveliness");+ applyAtmosphere(animationOptions);+ setActiveAnimationPreset(name);+ window.clearTimeout(animationTimer);+ circuit.setAnimation(animationOptions);+ updateTraceCount();+ });+ }+ seed.addEventListener("change", regenerate);++ controls.addEventListener("submit", (event) => {+ event.preventDefault();+ regenerate();+ });++ function saveBlob(text, name) {+ const blob = new Blob([text], { type: "image/svg+xml" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ URL.revokeObjectURL(url);+ }++ const slug = () => (seed.value || "seed").replace(/[^a-z0-9_-]+/gi, "-");++ download.addEventListener("click", () => {+ saveBlob(circuit.exportSvg(), `circuit-${slug()}.svg`);+ });++ </script>+ </body>+</html>
src/index-v8.htmladded+1061@@ -0,0 +1,1061 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Procedural Circuit Background</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0d1117;+ --surface: #161b22;+ --border: #30363d;+ --text: #e6edf3;+ --muted: #8b949e;+ --accent: #00b8b0;+ --accent-bright: #00e6dc;+ }++ * { box-sizing: border-box; }+ html, body { min-height: 100%; margin: 0; }+ body {+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ overflow-x: hidden;+ }++ .hero {+ --circuit-hole: var(--bg);+ position: relative;+ width: 100vw;+ min-height: 100svh;+ overflow: hidden;+ display: grid;+ place-items: center;+ isolation: isolate;+ }++ .hero[data-reveal-system="scroll"] {+ min-height: 300svh;+ place-items: start center;+ }++ .hero[data-reveal-system="scroll"] main {+ position: relative;+ top: auto;+ min-height: 100svh;+ display: grid;+ place-items: center;+ }++ .circuit-layer {+ position: absolute;+ inset: 0;+ z-index: 0;+ }++ .glow {+ --atmosphere-strength: 1;+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background:+ radial-gradient(ellipse 46% 34% at 50% 45%, rgba(13, 17, 23, .64), rgba(13, 17, 23, .34) 48%, transparent 100%),+ linear-gradient(to top, var(--bg) 0, transparent 13rem);+ }++ .glow::before {+ content: "";+ position: absolute;+ inset: -12%;+ background:+ radial-gradient(ellipse 28% 38% at 22% 48%, rgba(0, 230, 220, .06), transparent 72%),+ radial-gradient(ellipse 34% 42% at 58% 46%, rgba(57, 184, 255, .045), transparent 72%),+ radial-gradient(ellipse 30% 38% at 84% 52%, rgba(140, 107, 247, .045), transparent 72%);+ mix-blend-mode: screen;+ opacity: calc(var(--atmosphere-strength) * .72);+ filter: blur(34px);+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow {+ background:+ radial-gradient(circle at 52% 44%, rgba(0, 230, 220, .06), transparent 34%),+ linear-gradient(to top, var(--bg) 0, transparent 12rem);+ animation: atmosphere-breathe 8s ease-in-out infinite alternate;+ will-change: opacity, filter;+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow::before {+ inset: -18%;+ background:+ radial-gradient(circle at 28% 38%, rgba(0, 230, 220, .075), transparent 20%),+ radial-gradient(circle at 72% 58%, rgba(100, 171, 255, .055), transparent 24%),+ radial-gradient(circle at 52% 82%, rgba(197, 179, 255, .04), transparent 18%);+ opacity: 1;+ filter: none;+ animation: atmosphere-drift 19s cubic-bezier(.45,.05,.55,.95) infinite alternate;+ will-change: transform;+ }++ @keyframes atmosphere-breathe {+ from { opacity: var(--atmosphere-low, .66); filter: saturate(.82); }+ to { opacity: var(--atmosphere-high, 1); filter: saturate(1.18); }+ }++ @keyframes atmosphere-drift {+ 0% { transform: translate3d(-3%, -2%, 0) scale(1); }+ 45% { transform: translate3d(4%, 1%, 0) scale(1.08); }+ 100% { transform: translate3d(-1%, 5%, 0) scale(1.03); }+ }++ main {+ position: relative;+ z-index: 2;+ width: min(760px, calc(100% - 40px));+ text-align: center;+ padding: 80px 0 180px;+ }++ .hero-copy { position: relative; }++ .eyebrow {+ margin: 0 0 20px;+ color: var(--accent-bright);+ font: 600 12px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .18em;+ text-transform: uppercase;+ }++ h1 {+ margin: 0;+ font-size: clamp(3.2rem, 10vw, 7.5rem);+ line-height: .9;+ letter-spacing: -.055em;+ color: transparent;+ background: linear-gradient(100deg, #e6edf3 4%, #00e6dc 38%, #39b8ff 66%, #8c6bf7 96%);+ background-clip: text;+ filter: drop-shadow(0 0 .4em rgba(255,255,255,.18));+ }++ .lede {+ max-width: 570px;+ margin: 28px auto 0;+ color: #bac6d3;+ font-size: clamp(1rem, 2vw, 1.25rem);+ line-height: 1.6;+ }++ .hint {+ margin-top: 24px;+ color: var(--muted);+ font: 500 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }++ .controls {+ position: fixed;+ left: 50%;+ bottom: 12px;+ z-index: 5;+ width: min(1180px, calc(100% - 24px));+ transform: translateX(-50%);+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ padding: 10px;+ border: 1px solid rgba(48, 54, 61, .9);+ border-radius: 12px;+ background: rgba(22, 27, 34, .88);+ box-shadow: 0 18px 70px rgba(0,0,0,.38);+ backdrop-filter: blur(18px);+ }++ label { min-width: 0; display: grid; gap: 4px; color: var(--muted); font-size: 10px; }+ label > span { display: flex; justify-content: space-between; gap: 3px; white-space: nowrap; }+ input[type="text"] {+ width: 100%;+ height: 32px;+ padding: 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 500 11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ input[type="text"]:focus { border-color: var(--accent); }+ input[type="range"] { width: 100%; accent-color: var(--accent); }+ select {+ width: 100%;+ height: 32px;+ padding: 0 28px 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 600 11px system-ui, sans-serif;+ }+ select:focus { border-color: var(--accent); }++ button {+ height: 32px;+ padding: 0 11px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ background: #21262d;+ font: 700 12px system-ui, sans-serif;+ cursor: pointer;+ }+ button:hover { border-color: #59636e; background: #282e36; }+ button:disabled { opacity: .48; cursor: default; }+ button:disabled:hover { border-color: var(--border); background: #21262d; }+ button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); }+ button.primary:hover { background: var(--accent-bright); }++ .preset-bar {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .preset-title {+ margin-right: 3px;+ color: var(--muted);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .12em;+ text-transform: uppercase;+ }+ .preset-bar button {+ height: 28px;+ padding: 0 10px;+ color: #aab5c1;+ font-size: 11px;+ }+ .preset-bar button[aria-pressed="true"] {+ color: #082f2d;+ border-color: var(--accent);+ background: var(--accent);+ }+ .parameter-panel {+ grid-column: 1 / -1;+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ }+ .parameter-panel[hidden] { display: none; }+ .reveal-options-panel {+ position: absolute;+ right: 10px;+ bottom: calc(100% + 8px);+ width: min(760px, calc(100vw - 44px));+ max-height: calc(100svh - 116px);+ overflow-y: auto;+ padding: 12px;+ border: 1px solid rgba(48, 54, 61, .96);+ border-radius: 12px;+ background: rgba(18, 23, 30, .97);+ box-shadow: 0 18px 70px rgba(0,0,0,.48);+ backdrop-filter: blur(20px);+ }+ .reveal-options-panel[hidden] { display: none; }+ .reveal-options-heading {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 10px;+ }+ .reveal-options-heading strong {+ color: var(--text);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .1em;+ text-transform: uppercase;+ }+ .reveal-options-heading span { color: var(--muted); font-size: 10px; }+ .reveal-options-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 10px 12px;+ }+ .reveal-option[hidden] { display: none; }+ .reveal-option output { color: #c4d0dc; }+ /* A quiet text toggle, not a button: it opens a drawer, it does not pick a preset. */+ .preset-bar .panel-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ width: auto;+ height: 28px;+ padding: 0 2px;+ margin-left: 4px;+ color: var(--muted);+ border: 0;+ border-radius: 0;+ background: none;+ font: 600 11px system-ui, sans-serif;+ }+ .preset-bar .panel-toggle:hover { color: var(--text); border: 0; background: none; }+ .preset-bar .panel-toggle:focus-visible { outline: 1px solid var(--accent); outline-offset: 3px; }+ .preset-bar .panel-toggle[aria-expanded="true"] { color: var(--accent-bright); }+ .panel-toggle .chevron { display: inline-block; font-size: 9px; line-height: 1; transition: transform .15s ease; }+ .panel-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }++ .motion-bar {+ padding-top: 8px;+ border-top: 1px solid rgba(48, 54, 61, .72);+ }+ .preset-group {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .group-divider {+ align-self: stretch;+ width: 1px;+ min-height: 22px;+ margin: 0 2px;+ background: rgba(48, 54, 61, .8);+ }+ .reveal-group[data-disabled="true"] { opacity: .48; }+ .reveal-group[data-disabled="true"] button { pointer-events: none; }+ .preset-bar .replay-button {+ padding-inline: 7px;+ color: var(--muted);+ border-style: dashed;+ }+ .movement-power {+ flex: 1 1 150px;+ max-width: 180px;+ margin-left: 6px;+ }+ .movement-power input { margin: 0; }+ .trace-count {+ margin-left: auto;+ color: var(--accent-bright);+ font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: nowrap;+ }++ @media (max-width: 1180px) {+ .controls {+ grid-template-columns: repeat(6, minmax(0, 1fr));+ max-height: calc(100svh - 24px);+ overflow-y: auto;+ }+ .parameter-panel { grid-template-columns: repeat(6, minmax(0, 1fr)); }+ .controls:has(.reveal-options-panel:not([hidden])) { overflow: visible; }+ .preset-bar { flex-wrap: wrap; }+ .preset-group { flex-wrap: wrap; }+ }++ @media (max-width: 760px) {+ .controls { grid-template-columns: 1fr 1fr; bottom: 12px; }+ .parameter-panel { grid-template-columns: 1fr 1fr; }+ .controls button { width: 100%; }+ .preset-title { width: 100%; }+ .trace-count { margin-left: 0; }+ main { padding-bottom: 360px; }+ .reveal-options-panel {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 8px);+ width: auto;+ max-height: calc(100svh - 156px);+ overflow-y: auto;+ border-radius: 16px 16px 10px 10px;+ }+ .reveal-options-grid { grid-template-columns: 1fr 1fr; }+ }++ @media (max-width: 460px) {+ .reveal-options-grid { grid-template-columns: 1fr; }+ }++ @media (prefers-reduced-motion: reduce) {+ .glow, .glow::before { animation: none; }+ .panel-toggle .chevron { transition: none; }+ }+ </style>+ </head>+ <body>+ <section class="hero" id="hero">+ <div class="circuit-layer" id="circuit"></div>+ <div class="glow" aria-hidden="true"></div>+ <main>+ <div class="hero-copy" data-circuit-reading-zone>+ <p class="eyebrow">Seeded SVG generator</p>+ <h1>Live circuitry</h1>+ <p class="lede">+ A procedural version of the Nitrogen hero pattern: dense routed traces, 45° chamfers,+ annular vias, continuous trace packing, and separate reveal and ambient animation systems.+ </p>+ <p class="hint" id="motionHint">All traces arrive fully routed · no ambient movement</p>+ </div>+ </main>+ </section>++ <form class="controls" id="controls">+ <div class="preset-bar" aria-label="Generator presets">+ <span class="preset-title">Generation</span>+ <button type="button" data-preset="original" aria-pressed="true">Original match</button>+ <button type="button" data-preset="dense" aria-pressed="false">Dense</button>+ <button type="button" data-preset="diagonal" aria-pressed="false">Diagonal sweep</button>+ <button type="button" data-preset="swirl" aria-pressed="false">Broad swirl</button>+ <button type="button" data-preset="sparse" aria-pressed="false">Sparse</button>+ <button type="button" class="panel-toggle" id="parameterToggle" aria-expanded="false" aria-controls="parameterPanel">+ Parameters<span class="chevron" aria-hidden="true">▾</span>+ </button>+ <output class="trace-count" id="traceCount">235 traces</output>+ </div>+ <div class="parameter-panel" id="parameterPanel" hidden>+ <label>+ Seed+ <input id="seed" type="text" value="nitrogen" autocomplete="off" spellcheck="false" />+ </label>+ <label>+ <span>Density <output id="fillValue">74.4%</output></span>+ <input id="fill" type="range" min="0.35" max="0.76" step="0.001" value="0.744" />+ </label>+ <label>+ <span>Avg length <output id="routeLengthValue">1.14×</output></span>+ <input id="routeLength" type="range" min="0.55" max="2.25" step="0.01" value="1.14" />+ </label>+ <label>+ <span>Primary flow <output id="horizontalFlowValue">90%</output></span>+ <input id="horizontalFlow" type="range" min="0.3" max="0.98" step="0.01" value="0.9" />+ </label>+ <label>+ <span>Angle <output id="flowAngleValue">153°</output></span>+ <input id="flowAngle" type="range" min="0" max="180" step="1" value="153" />+ </label>+ <label>+ <span>Diagonal <output id="diagonalFlowValue">100%</output></span>+ <input id="diagonalFlow" type="range" min="0" max="1" step="0.01" value="1" />+ </label>+ <label>+ <span>Long flow <output id="longFlowValue">31%</output></span>+ <input id="longFlow" type="range" min="0" max="0.36" step="0.01" value="0.31" />+ </label>+ <label>+ <span>Swirl <output id="swirlValue">82%</output></span>+ <input id="swirl" type="range" min="0" max="1.4" step="0.01" value="0.82" />+ </label>+ <label>+ <span>Swirl scale <output id="swirlScaleValue">0.72×</output></span>+ <input id="swirlScale" type="range" min="0.25" max="1.4" step="0.01" value="0.72" />+ </label>+ <label>+ <span>Jog size <output id="jogLengthValue">0.42×</output></span>+ <input id="jogLength" type="range" min="0.3" max="1.8" step="0.01" value="0.42" />+ </label>+ <label>+ <span>Channel pull <output id="channelAttractionValue">150%</output></span>+ <input id="channelAttraction" type="range" min="0" max="1.5" step="0.01" value="1.5" />+ </label>+ <label>+ <span>Scale <output id="featureScaleValue">1.37×</output></span>+ <input id="featureScale" type="range" min="0.55" max="2" step="0.01" value="1.37" />+ </label>+ </div>+ <div class="preset-bar motion-bar" aria-label="Trace reveal and animation presets">+ <div class="preset-group reveal-group" id="revealGroup" aria-label="Trace reveal presets">+ <span class="preset-title">Reveal</span>+ <button type="button" data-reveal-preset="instant" aria-pressed="true">Instant</button>+ <button type="button" data-reveal-preset="flow" aria-pressed="false">Flow sweep</button>+ <button type="button" data-reveal-preset="scroll" aria-pressed="false">Scroll weave</button>+ <button class="replay-button" id="replayReveal" type="button">Replay</button>+ <button type="button" class="panel-toggle" id="revealOptionsToggle" aria-expanded="false" aria-controls="revealOptionsPanel">+ Options<span class="chevron" aria-hidden="true">▾</span>+ </button>+ </div>+ <span class="group-divider" aria-hidden="true"></span>+ <div class="preset-group animation-group" aria-label="Ambient animation presets">+ <span class="preset-title">Animation</span>+ <button type="button" data-animation-preset="none" aria-pressed="true">None</button>+ <button type="button" data-animation-preset="reflection" aria-pressed="false">Reflection</button>+ <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>+ <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>+ <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ </div>+ <label class="movement-power">+ <span>Movement power <output id="livelinessValue">0%</output></span>+ <input id="liveliness" type="range" min="0" max="1.5" step="0.01" value="0" />+ </label>+ <button class="primary" type="submit">Generate</button>+ <button id="download" type="button">Export SVG</button>+ </div>+ <section class="reveal-options-panel" id="revealOptionsPanel" aria-label="Reveal options" hidden>+ <div class="reveal-options-heading">+ <strong id="revealOptionsTitle">Flow sweep options</strong>+ <span>Changes apply to this reveal preset</span>+ </div>+ <div class="reveal-options-grid">+ <label class="reveal-option" data-reveal-for="flow scroll">+ Spawn pattern+ <select id="spawnMode">+ <option value="flow">Directional flow</option>+ <option value="radial">Radial</option>+ <option value="edges">From edges</option>+ <option value="scatter">Scatter</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn angle <output id="spawnAngleValue">90°</output></span>+ <input id="spawnAngle" type="range" min="0" max="359" step="1" value="90" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn swirl <output id="spawnSwirlValue">7.5%</output></span>+ <input id="spawnSwirl" type="range" min="0" max="0.35" step="0.005" value="0.075" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Trace glow <output id="revealGlowValue">88%</output></span>+ <input id="revealGlow" type="range" min="0" max="1" step="0.01" value="0.88" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Sweep duration <output id="revealDurationValue">7.6 s</output></span>+ <input id="revealDuration" type="range" min="2600" max="18000" step="100" value="7600" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Active traces <output id="revealMaxActiveTracesValue">48</output></span>+ <input id="revealMaxActiveTraces" type="range" min="12" max="96" step="1" value="48" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Trace duration <output id="traceDurationValue">0.95 s</output></span>+ <input id="traceDuration" type="range" min="350" max="2000" step="25" value="950" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Launch rate <output id="revealLaunchRateValue">24/s</output></span>+ <input id="revealLaunchRate" type="range" min="6" max="80" step="1" value="24" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Active traces <output id="maxActiveTracesValue">72</output></span>+ <input id="maxActiveTraces" type="range" min="12" max="160" step="1" value="72" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Speed response <output id="scrollSpeedResponseValue">60%</output></span>+ <input id="scrollSpeedResponse" type="range" min="0" max="1" step="0.01" value="0.6" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Reveal lead <output id="unlockLeadValue">2.5%</output></span>+ <input id="unlockLead" type="range" min="0" max="0.2" step="0.005" value="0.025" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ Continue generation+ <select id="continuousGeneration">+ <option value="true">On</option>+ <option value="false">Off</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Generate ahead <output id="generationAheadScreensValue">2 screens</output></span>+ <input id="generationAheadScreens" type="range" min="1" max="4" step="0.25" value="2" />+ </label>+ </div>+ </section>+ </form>++ <script type="module">+ import { ANIMATION_PRESETS, REVEAL_PRESETS, createCircuitBackground } from "./circuit-background-v8.js?v=1";++ const mount = document.querySelector("#circuit");+ const controls = document.querySelector("#controls");+ const generationPresetButtons = [...document.querySelectorAll("[data-preset]")];+ const revealPresetButtons = [...document.querySelectorAll("[data-reveal-preset]")];+ const animationPresetButtons = [...document.querySelectorAll("[data-animation-preset]")];+ const traceCount = document.querySelector("#traceCount");+ const hero = document.querySelector("#hero");+ const canonicalPageSize = Object.freeze({+ width: Math.max(1, mount.clientWidth),+ height: Math.max(1, mount.clientHeight),+ });+ const glow = document.querySelector(".glow");+ const seed = document.querySelector("#seed");+ const parameterToggle = document.querySelector("#parameterToggle");+ const parameterPanel = document.querySelector("#parameterPanel");+ const motionHint = document.querySelector("#motionHint");+ const revealGroup = document.querySelector("#revealGroup");+ const replayReveal = document.querySelector("#replayReveal");+ const revealOptionsToggle = document.querySelector("#revealOptionsToggle");+ const revealOptionsPanel = document.querySelector("#revealOptionsPanel");+ const revealOptionsTitle = document.querySelector("#revealOptionsTitle");+ const revealOptionElements = [...document.querySelectorAll("[data-reveal-for]")];+ const revealOptionIds = [+ "spawnMode", "spawnAngle", "spawnSwirl", "revealGlow", "revealDuration",+ "revealMaxActiveTraces", "traceDuration", "revealLaunchRate", "maxActiveTraces",+ "scrollSpeedResponse", "unlockLead", "continuousGeneration", "generationAheadScreens",+ ];+ const revealControls = Object.fromEntries(revealOptionIds.map((id) => [id, document.querySelector("#" + id)]));+ const download = document.querySelector("#download");++ const geometryParameterIds = ["fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow", "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale"];+ const animationParameterIds = ["liveliness"];+ const parameterIds = [...geometryParameterIds, ...animationParameterIds];+ const parameters = Object.fromEntries(parameterIds.map((id) => [id, document.querySelector(`#${id}`)]));+ const presets = {+ original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37 },+ dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65 },+ diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28 },+ swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1 },+ sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88 },+ };+ const revealHints = {+ instant: "All traces arrive fully routed",+ flow: "A curved front grows every route from via to via",+ scroll: "Scroll unlocks routes; each one grows on its own timeline",+ };+ const animationHints = {+ none: "no ambient movement",+ conductor: "move to shape the current · click to activate the network",+ adom: "move to steer the routed field · click to launch a local bloom",+ handshake: "move to bias the next handshake · click to request a local exchange",+ reflection: "move to catch the light · click to send a quiet reflection",+ };+ const formats = {+ fill: (value) => `${Number((value * 100).toFixed(1))}%`,+ routeLength: (value) => `${value.toFixed(2)}×`,+ horizontalFlow: (value) => `${Math.round(value * 100)}%`,+ flowAngle: (value) => `${Math.round(value)}°`,+ diagonalFlow: (value) => `${Math.round(value * 100)}%`,+ longFlow: (value) => `${Math.round(value * 100)}%`,+ swirl: (value) => `${Math.round(value * 100)}%`,+ swirlScale: (value) => `${value.toFixed(2)}×`,+ jogLength: (value) => `${value.toFixed(2)}×`,+ channelAttraction: (value) => `${Math.round(value * 100)}%`,+ featureScale: (value) => `${value.toFixed(2)}×`,+ liveliness: (value) => `${Math.round(value * 100)}%`,+ };+ const revealFormats = {+ spawnAngle: (value) => Math.round(value) + "°",+ spawnSwirl: (value) => Number((value * 100).toFixed(1)) + "%",+ revealGlow: (value) => Math.round(value * 100) + "%",+ revealDuration: (value) => (value / 1000).toFixed(1) + " s",+ revealMaxActiveTraces: (value) => String(Math.round(value)),+ traceDuration: (value) => (value / 1000).toFixed(2) + " s",+ revealLaunchRate: (value) => Math.round(value) + "/s",+ maxActiveTraces: (value) => String(Math.round(value)),+ scrollSpeedResponse: (value) => Math.round(value * 100) + "%",+ unlockLead: (value) => Number((value * 100).toFixed(1)) + "%",+ generationAheadScreens: (value) => Number(value.toFixed(2)) + (value === 1 ? " screen" : " screens"),+ };++ function updateRevealOptionOutput(id) {+ if (!revealFormats[id]) return;+ const output = document.querySelector("#" + id + "Value");+ if (output) output.value = revealFormats[id](Number(revealControls[id].value));+ }++ function closeRevealOptions() {+ revealOptionsToggle.setAttribute("aria-expanded", "false");+ revealOptionsPanel.hidden = true;+ }++ function syncRevealOptionAvailability(name) {+ const state = revealOptionState[name];+ if (!state) return;+ const directional = state.spawnMode === "flow";+ revealControls.spawnAngle.disabled = !directional;+ revealControls.spawnSwirl.disabled = !directional;+ revealControls.generationAheadScreens.disabled = name === "scroll"+ && !state.continuousGeneration;+ }++ function syncRevealOptionControls(name) {+ if (name !== "flow" && name !== "scroll") return;+ const state = revealOptionState[name];+ for (const element of revealOptionElements) {+ element.hidden = !element.dataset.revealFor.split(" ").includes(name);+ }+ for (const id of revealOptionIds) {+ if (!(id in state)) continue;+ const control = revealControls[id];+ control.value = id === "continuousGeneration"+ ? String(Boolean(state[id]))+ : String(state[id]);+ if (id === "continuousGeneration") state[id] = control.value === "true";+ else if (id === "spawnMode") state[id] = control.value;+ else state[id] = Number(control.value);+ updateRevealOptionOutput(id);+ }+ revealOptionsTitle.textContent = name === "flow" ? "Flow sweep options" : "Scroll weave options";+ syncRevealOptionAvailability(name);+ }+++ const query = new URLSearchParams(location.search);+ const requestedAnimationPreset = query.get("animationPreset");+ const requestedRevealPreset = query.get("revealPreset");+ const legacyGrowthLink = requestedAnimationPreset === "growth";+ const initialAnimationPreset = !legacyGrowthLink && ANIMATION_PRESETS[requestedAnimationPreset]+ ? requestedAnimationPreset+ : "none";+ const initialRevealPreset = legacyGrowthLink+ ? "flow"+ : REVEAL_PRESETS[requestedRevealPreset]+ ? requestedRevealPreset+ : "instant";+ let animationOptions = { ...ANIMATION_PRESETS[initialAnimationPreset] };+ const revealOptionState = {+ flow: {+ ...REVEAL_PRESETS.flow,+ spawnMode: REVEAL_PRESETS.flow.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.flow.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.flow.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.flow.revealGlow ?? 0.88,+ revealDuration: REVEAL_PRESETS.flow.revealDuration ?? 7600,+ revealMaxActiveTraces: REVEAL_PRESETS.flow.revealMaxActiveTraces ?? 48,+ },+ scroll: {+ ...REVEAL_PRESETS.scroll,+ spawnMode: REVEAL_PRESETS.scroll.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.scroll.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.scroll.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.scroll.revealGlow ?? 0.82,+ traceDuration: REVEAL_PRESETS.scroll.traceDuration ?? 950,+ revealLaunchRate: REVEAL_PRESETS.scroll.revealLaunchRate ?? 24,+ maxActiveTraces: REVEAL_PRESETS.scroll.maxActiveTraces ?? 72,+ scrollSpeedResponse: REVEAL_PRESETS.scroll.scrollSpeedResponse ?? 0.6,+ unlockLead: REVEAL_PRESETS.scroll.unlockLead ?? 0.025,+ continuousGeneration: REVEAL_PRESETS.scroll.continuousGeneration ?? true,+ generationAheadScreens: REVEAL_PRESETS.scroll.generationAheadScreens ?? 2,+ },+ };+ let activeRevealPreset = initialRevealPreset;+ const validSpawnModes = new Set(["flow", "radial", "edges", "scatter"]);+ if (activeRevealPreset === "flow" || activeRevealPreset === "scroll") {+ for (const id of revealOptionIds) {+ if (!query.has(id) || !(id in revealOptionState[activeRevealPreset])) continue;+ if (id === "spawnMode") {+ const value = query.get(id);+ if (validSpawnModes.has(value)) revealOptionState[activeRevealPreset][id] = value;+ } else if (id === "continuousGeneration") {+ revealOptionState[activeRevealPreset][id] = !["0", "false", "off"].includes(query.get(id).toLowerCase());+ } else {+ const value = Number(query.get(id));+ if (Number.isFinite(value)) revealOptionState[activeRevealPreset][id] = value;+ }+ }+ }+ if (activeRevealPreset !== "instant" && query.has("revealMotion")) {+ revealOptionState[activeRevealPreset].revealMotion = !["0", "false", "off"].includes(+ query.get("revealMotion").toLowerCase(),+ );+ }+ let revealOptions = activeRevealPreset === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[activeRevealPreset] };+ const revealQueryPresent = revealOptionIds.some((id) => query.has(id));+ if (activeRevealPreset !== "instant") syncRevealOptionControls(activeRevealPreset);+ if (activeRevealPreset !== "instant" && revealQueryPresent) {+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ }+ if (query.has("seed")) seed.value = query.get("seed").slice(0, 80);+ for (const id of parameterIds) {+ if (!query.has(id)) continue;+ const value = Number(query.get(id));+ if (Number.isFinite(value)) parameters[id].value = String(value);+ }+ // A deep link that tunes parameters should show them, not hide the reason the render differs.+ if (geometryParameterIds.some((id) => query.has(id))) {+ parameterToggle.setAttribute("aria-expanded", "true");+ parameterPanel.hidden = false;+ }+ if (!query.has("liveliness")) parameters.liveliness.value = String(animationOptions.liveliness);+ if (query.has("motion")) {+ animationOptions.motion = !["0", "false", "off"].includes(query.get("motion").toLowerCase());+ }++ function setActiveGenerationPreset(name) {+ for (const button of generationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.preset === name));+ }+ }++ function setActiveRevealPreset(name) {+ for (const button of revealPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.revealPreset === name));+ }+ }++ function setActiveAnimationPreset(name) {+ for (const button of animationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.animationPreset === name));+ }+ }++ function updatePresentation() {+ const routed = animationOptions.animationSystem === "adom";+ const revealSystem = routed ? "instant" : revealOptions.revealSystem;+ hero.dataset.revealSystem = revealSystem;+ revealGroup.dataset.disabled = String(routed);+ revealGroup.setAttribute("aria-disabled", String(routed));+ setActiveRevealPreset(routed ? "instant" : activeRevealPreset);+ for (const button of revealPresetButtons) button.disabled = routed;+ replayReveal.disabled = routed || !(+ revealSystem === "flow"+ || (revealSystem === "scroll" && revealOptions.continuousGeneration)+ );+ revealOptionsToggle.disabled = routed || revealSystem === "instant";+ if (revealOptionsToggle.disabled) closeRevealOptions();+ const revealHint = revealSystem === "scroll" && revealOptions.continuousGeneration+ ? "Scroll queues trace growth and pre-generates page-sized field sections ahead"+ : revealHints[revealSystem] || revealHints.instant;+ motionHint.textContent = routed+ ? "Routed field owns its trace lifecycle · move to steer it and click for a local bloom"+ : [+ revealHint,+ animationHints[animationOptions.animationSystem] || animationHints.none,+ ].join(" · ");+ }++ function applyAtmosphere(options) {+ const amount = Math.max(0, Math.min(1.25, options.atmosphereStrength));+ hero.dataset.animationSystem = options.animationSystem;+ hero.dataset.motion = options.motion ? "on" : "off";+ glow.style.setProperty("--atmosphere-strength", String(amount));+ glow.style.setProperty("--atmosphere-low", String(Math.min(1, amount * 0.66)));+ glow.style.setProperty("--atmosphere-high", String(Math.min(1, amount)));+ updatePresentation();+ }++ function applyReveal() {+ updatePresentation();+ }++ if (geometryParameterIds.some((id) => query.has(id))) setActiveGenerationPreset(null);+ const animationIsCustom = animationParameterIds.some((id) => query.has(id)) || query.has("motion");+ setActiveRevealPreset(initialRevealPreset);+ setActiveAnimationPreset(animationIsCustom ? null : initialAnimationPreset);+ applyReveal();+ applyAtmosphere(animationOptions);++ function optionsFromControls() {+ const options = {+ ...revealOptions,+ ...animationOptions,+ seed: seed.value.trim() || "nitrogen",+ traceColor: "#1d2938",+ canonicalPageWidth: canonicalPageSize.width,+ canonicalPageHeight: canonicalPageSize.height,+ };+ for (const id of parameterIds) options[id] = Number(parameters[id].value);+ return options;+ }++ function updateOutput(id) {+ const value = Number(parameters[id].value);+ document.querySelector(`#${id}Value`).value = formats[id](value);+ }+ parameterIds.forEach(updateOutput);++ const circuit = createCircuitBackground(mount, optionsFromControls());+ let regenerationTimer;+ let animationTimer;+ let revealUpdateTimer;++ function commitRevealOptions() {+ window.clearTimeout(revealUpdateTimer);+ if (typeof circuit.setReveal === "function") {+ circuit.setReveal(revealOptions);+ } else {+ circuit.regenerate(optionsFromControls());+ }+ queueTraceCount();+ }++ function scheduleRevealUpdate() {+ window.clearTimeout(revealUpdateTimer);+ revealUpdateTimer = window.setTimeout(commitRevealOptions, 120);+ }++ let lastTraceCountText = "";+ function updateTraceCount(stats) {+ const total = circuit.field.traces.length;+ const text = stats?.system === "scroll-trace-reveal"+ ? Math.min(total, stats.completedTraces) + " / " + total + " routed"+ : total + " traces";+ if (text === lastTraceCountText) return;+ lastTraceCountText = text;+ traceCount.value = text;+ }+ let traceCountFrame = 0;+ function tickTraceCount() {+ traceCountFrame = 0;+ const stats = circuit.revealStats;+ updateTraceCount(stats);+ if (+ stats?.continuous+ || (+ stats?.system === "scroll-trace-reveal"+ && (stats.queuedTraces > 0 || stats.activeTraces > 0)+ )+ ) {+ traceCountFrame = window.setTimeout(tickTraceCount, 200);+ }+ }+ function queueTraceCount() {+ if (traceCountFrame) return;+ traceCountFrame = window.requestAnimationFrame(tickTraceCount);+ }+ window.addEventListener("scroll", queueTraceCount, { passive: true });+ window.addEventListener("resize", queueTraceCount, { passive: true });+ queueTraceCount();+ const requestedScrollProgress = Number(query.get("scrollProgress"));+ const requestedScrollScreens = Number(query.get("scrollScreens"));+ if (+ initialRevealPreset === "scroll"+ && revealOptions.continuousGeneration+ && Number.isFinite(requestedScrollScreens)+ && requestedScrollScreens > 0+ ) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const target = requestedScrollScreens * window.innerHeight;+ const startedAt = performance.now();+ const advance = () => {+ const remaining = target - window.scrollY;+ if (remaining <= 2 || performance.now() - startedAt > 15000) return;+ window.scrollBy(0, Math.min(window.innerHeight * 0.42, remaining));+ window.setTimeout(advance, 180);+ };+ advance();+ }));+ } else if (initialRevealPreset === "scroll" && Number.isFinite(requestedScrollProgress)) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const travel = Math.max(0, hero.scrollHeight - window.innerHeight);+ window.scrollTo(0, travel * Math.max(0, Math.min(1, requestedScrollProgress)));+ }));+ }+++ function regenerate() {+ window.clearTimeout(regenerationTimer);+ circuit.regenerate(optionsFromControls());+ queueTraceCount();+ }++ for (const id of parameterIds) {+ parameters[id].addEventListener("input", () => {+ updateOutput(id);+ if (!geometryParameterIds.includes(id)) {+ setActiveAnimationPreset(null);+ animationOptions = { ...animationOptions, [id]: Number(parameters[id].value) };+ applyAtmosphere(animationOptions);+ window.clearTimeout(animationTimer);+ if (animationOptions.animationSystem === "adom") {+ animationTimer = window.setTimeout(() => circuit.setAnimation(animationOptions), 140);+ } else {+ circuit.setAnimation(animationOptions);+ }+ return;+ }+ setActiveGenerationPreset(null);+ window.clearTimeout(regenerationTimer);+ regenerationTimer = window.setTimeout(regenerate, 140);+ });+ }+ for (const button of generationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.preset;+ const values = presets[name];+ for (const [id, value] of Object.entries(values)) {+ parameters[id].value = String(value);+ updateOutput(id);+ }+ setActiveGenerationPreset(name);+ regenerate();+ });+ }+ parameterToggle.addEventListener("click", () => {+ const expanded = parameterToggle.getAttribute("aria-expanded") === "true";+ parameterToggle.setAttribute("aria-expanded", String(!expanded));+ parameterPanel.hidden = expanded;+ });+ revealOptionsToggle.addEventListener("click", () => {+ if (revealOptionsToggle.disabled) return;+ const expanded = revealOptionsToggle.getAttribute("aria-expanded") === "true";+ if (expanded) {+ closeRevealOptions();+ return;+ }+ syncRevealOptionControls(activeRevealPreset);+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ });+ for (const id of revealOptionIds) {+ revealControls[id].addEventListener("input", () => {+ if (activeRevealPreset !== "flow" && activeRevealPreset !== "scroll") return;+ let value;+ if (id === "spawnMode") value = revealControls[id].value;+ else if (id === "continuousGeneration") value = revealControls[id].value === "true";+ else value = Number(revealControls[id].value);+ revealOptionState[activeRevealPreset][id] = value;+ revealOptions = { ...revealOptionState[activeRevealPreset] };+ updateRevealOptionOutput(id);+ syncRevealOptionAvailability(activeRevealPreset);+ applyReveal();+ scheduleRevealUpdate();+ });+ }+ for (const button of revealPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.revealPreset;+ activeRevealPreset = name;+ revealOptions = name === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[name] };+ if (name !== "instant") syncRevealOptionControls(name);+ setActiveRevealPreset(name);+ applyReveal();+ commitRevealOptions();+ });+ }+ replayReveal.addEventListener("click", () => {+ circuit.triggerReveal();+ });+ for (const button of animationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.animationPreset;+ animationOptions = { ...ANIMATION_PRESETS[name] };+ parameters.liveliness.value = String(animationOptions.liveliness);+ updateOutput("liveliness");+ applyAtmosphere(animationOptions);+ setActiveAnimationPreset(name);+ window.clearTimeout(animationTimer);+ circuit.setAnimation(animationOptions);+ updateTraceCount();+ });+ }+ seed.addEventListener("change", regenerate);++ controls.addEventListener("submit", (event) => {+ event.preventDefault();+ regenerate();+ });++ function saveBlob(text, name) {+ const blob = new Blob([text], { type: "image/svg+xml" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ URL.revokeObjectURL(url);+ }++ const slug = () => (seed.value || "seed").replace(/[^a-z0-9_-]+/gi, "-");++ download.addEventListener("click", () => {+ saveBlob(circuit.exportSvg(), `circuit-${slug()}.svg`);+ });++ </script>+ </body>+</html>
src/index-v9.htmladded+1138@@ -0,0 +1,1138 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Procedural Circuit Background</title>+ <style>+ :root {+ color-scheme: dark;+ --bg: #0d1117;+ --surface: #161b22;+ --border: #30363d;+ --text: #e6edf3;+ --muted: #8b949e;+ --accent: #00b8b0;+ --accent-bright: #00e6dc;+ }++ * { box-sizing: border-box; }+ html, body { min-height: 100%; margin: 0; }+ body {+ background: var(--bg);+ color: var(--text);+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ overflow-x: hidden;+ }++ .hero {+ --circuit-hole: var(--bg);+ position: relative;+ width: 100vw;+ min-height: 100svh;+ overflow: hidden;+ display: grid;+ place-items: center;+ isolation: isolate;+ }++ .hero[data-reveal-system="scroll"] {+ min-height: 300svh;+ place-items: start center;+ }++ .hero[data-reveal-system="scroll"] main {+ position: relative;+ top: auto;+ min-height: 100svh;+ display: grid;+ place-items: center;+ }++ .circuit-layer {+ position: absolute;+ inset: 0;+ z-index: 0;+ }++ .glow {+ --atmosphere-strength: 1;+ position: absolute;+ inset: 0;+ z-index: 1;+ pointer-events: none;+ background:+ radial-gradient(ellipse 46% 34% at 50% 45%, rgba(13, 17, 23, .64), rgba(13, 17, 23, .34) 48%, transparent 100%),+ linear-gradient(to top, var(--bg) 0, transparent 13rem);+ }++ .glow::before {+ content: "";+ position: absolute;+ inset: -12%;+ background:+ radial-gradient(ellipse 28% 38% at 22% 48%, rgba(0, 230, 220, .06), transparent 72%),+ radial-gradient(ellipse 34% 42% at 58% 46%, rgba(57, 184, 255, .045), transparent 72%),+ radial-gradient(ellipse 30% 38% at 84% 52%, rgba(140, 107, 247, .045), transparent 72%);+ mix-blend-mode: screen;+ opacity: calc(var(--atmosphere-strength) * .72);+ filter: blur(34px);+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow {+ background:+ radial-gradient(circle at 52% 44%, rgba(0, 230, 220, .06), transparent 34%),+ linear-gradient(to top, var(--bg) 0, transparent 12rem);+ animation: atmosphere-breathe 8s ease-in-out infinite alternate;+ will-change: opacity, filter;+ }++ .hero[data-motion="on"][data-animation-system="conductor"] .glow::before {+ inset: -18%;+ background:+ radial-gradient(circle at 28% 38%, rgba(0, 230, 220, .075), transparent 20%),+ radial-gradient(circle at 72% 58%, rgba(100, 171, 255, .055), transparent 24%),+ radial-gradient(circle at 52% 82%, rgba(197, 179, 255, .04), transparent 18%);+ opacity: 1;+ filter: none;+ animation: atmosphere-drift 19s cubic-bezier(.45,.05,.55,.95) infinite alternate;+ will-change: transform;+ }++ @keyframes atmosphere-breathe {+ from { opacity: var(--atmosphere-low, .66); filter: saturate(.82); }+ to { opacity: var(--atmosphere-high, 1); filter: saturate(1.18); }+ }++ @keyframes atmosphere-drift {+ 0% { transform: translate3d(-3%, -2%, 0) scale(1); }+ 45% { transform: translate3d(4%, 1%, 0) scale(1.08); }+ 100% { transform: translate3d(-1%, 5%, 0) scale(1.03); }+ }++ main {+ position: relative;+ z-index: 2;+ width: min(760px, calc(100% - 40px));+ text-align: center;+ padding: 80px 0 180px;+ }++ .hero-copy { position: relative; }++ .eyebrow {+ margin: 0 0 20px;+ color: var(--accent-bright);+ font: 600 12px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .18em;+ text-transform: uppercase;+ }++ h1 {+ margin: 0;+ font-size: clamp(3.2rem, 10vw, 7.5rem);+ line-height: .9;+ letter-spacing: -.055em;+ color: transparent;+ background: linear-gradient(100deg, #e6edf3 4%, #00e6dc 38%, #39b8ff 66%, #8c6bf7 96%);+ background-clip: text;+ filter: drop-shadow(0 0 .4em rgba(255,255,255,.18));+ }++ .lede {+ max-width: 570px;+ margin: 28px auto 0;+ color: #bac6d3;+ font-size: clamp(1rem, 2vw, 1.25rem);+ line-height: 1.6;+ }++ .hint {+ margin-top: 24px;+ color: var(--muted);+ font: 500 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }++ .controls {+ position: fixed;+ left: 50%;+ bottom: 12px;+ z-index: 5;+ width: min(1180px, calc(100% - 24px));+ transform: translateX(-50%);+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ padding: 10px;+ border: 1px solid rgba(48, 54, 61, .9);+ border-radius: 12px;+ background: rgba(22, 27, 34, .88);+ box-shadow: 0 18px 70px rgba(0,0,0,.38);+ backdrop-filter: blur(18px);+ }++ label { min-width: 0; display: grid; gap: 4px; color: var(--muted); font-size: 10px; }+ label > span { display: flex; justify-content: space-between; gap: 3px; white-space: nowrap; }+ input[type="text"] {+ width: 100%;+ height: 32px;+ padding: 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 500 11px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ }+ input[type="text"]:focus { border-color: var(--accent); }+ input[type="range"] { width: 100%; accent-color: var(--accent); }+ select {+ width: 100%;+ height: 32px;+ padding: 0 28px 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 600 11px system-ui, sans-serif;+ }+ select:focus { border-color: var(--accent); }+ label:has(input:disabled), label:has(select:disabled) { opacity: .42; }++ button {+ height: 32px;+ padding: 0 11px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ background: #21262d;+ font: 700 12px system-ui, sans-serif;+ cursor: pointer;+ }+ button:hover { border-color: #59636e; background: #282e36; }+ button:disabled { opacity: .48; cursor: default; }+ button:disabled:hover { border-color: var(--border); background: #21262d; }+ button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); }+ button.primary:hover { background: var(--accent-bright); }++ .preset-bar {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .preset-title {+ margin-right: 3px;+ color: var(--muted);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .12em;+ text-transform: uppercase;+ }+ .preset-bar button {+ height: 28px;+ padding: 0 10px;+ color: #aab5c1;+ font-size: 11px;+ }+ .preset-bar button[aria-pressed="true"] {+ color: #082f2d;+ border-color: var(--accent);+ background: var(--accent);+ }+ .parameter-panel {+ grid-column: 1 / -1;+ display: grid;+ grid-template-columns: repeat(12, minmax(0, 1fr));+ align-items: end;+ gap: 8px;+ }+ .parameter-panel[hidden] { display: none; }+ .reveal-options-panel {+ position: absolute;+ right: 10px;+ bottom: calc(100% + 8px);+ width: min(760px, calc(100vw - 44px));+ max-height: calc(100svh - 116px);+ overflow-y: auto;+ padding: 12px;+ border: 1px solid rgba(48, 54, 61, .96);+ border-radius: 12px;+ background: rgba(18, 23, 30, .97);+ box-shadow: 0 18px 70px rgba(0,0,0,.48);+ backdrop-filter: blur(20px);+ }+ .reveal-options-panel[hidden] { display: none; }+ .reveal-options-heading {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 10px;+ }+ .reveal-options-heading strong {+ color: var(--text);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .1em;+ text-transform: uppercase;+ }+ .reveal-options-heading span { color: var(--muted); font-size: 10px; }+ .reveal-options-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 10px 12px;+ }+ .reveal-option[hidden] { display: none; }+ .reveal-option output { color: #c4d0dc; }+ /* A quiet text toggle, not a button: it opens a drawer, it does not pick a preset. */+ .preset-bar .panel-toggle {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ width: auto;+ height: 28px;+ padding: 0 2px;+ margin-left: 4px;+ color: var(--muted);+ border: 0;+ border-radius: 0;+ background: none;+ font: 600 11px system-ui, sans-serif;+ }+ .preset-bar .panel-toggle:hover { color: var(--text); border: 0; background: none; }+ .preset-bar .panel-toggle:focus-visible { outline: 1px solid var(--accent); outline-offset: 3px; }+ .preset-bar .panel-toggle[aria-expanded="true"] { color: var(--accent-bright); }+ .panel-toggle .chevron { display: inline-block; font-size: 9px; line-height: 1; transition: transform .15s ease; }+ .panel-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }++ .motion-bar {+ padding-top: 8px;+ border-top: 1px solid rgba(48, 54, 61, .72);+ }+ .preset-group {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .group-divider {+ align-self: stretch;+ width: 1px;+ min-height: 22px;+ margin: 0 2px;+ background: rgba(48, 54, 61, .8);+ }+ .reveal-group[data-disabled="true"] { opacity: .48; }+ .reveal-group[data-disabled="true"] button { pointer-events: none; }+ .preset-bar .replay-button {+ padding-inline: 7px;+ color: var(--muted);+ border-style: dashed;+ }+ .movement-power {+ flex: 1 1 150px;+ max-width: 180px;+ margin-left: 6px;+ }+ .movement-power input { margin: 0; }+ .trace-count {+ margin-left: auto;+ color: var(--accent-bright);+ font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: nowrap;+ }++ @media (max-width: 1180px) {+ .controls {+ grid-template-columns: repeat(6, minmax(0, 1fr));+ max-height: calc(100svh - 24px);+ overflow-y: auto;+ }+ .parameter-panel { grid-template-columns: repeat(6, minmax(0, 1fr)); }+ .controls:has(.reveal-options-panel:not([hidden])) { overflow: visible; }+ .preset-bar { flex-wrap: wrap; }+ .preset-group { flex-wrap: wrap; }+ }++ @media (max-width: 760px) {+ .controls { grid-template-columns: 1fr 1fr; bottom: 12px; }+ .parameter-panel { grid-template-columns: 1fr 1fr; }+ .controls button { width: 100%; }+ .preset-title { width: 100%; }+ .trace-count { margin-left: 0; }+ main { padding-bottom: 360px; }+ .reveal-options-panel {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 8px);+ width: auto;+ max-height: calc(100svh - 156px);+ overflow-y: auto;+ border-radius: 16px 16px 10px 10px;+ }+ .reveal-options-grid { grid-template-columns: 1fr 1fr; }+ }++ @media (max-width: 460px) {+ .reveal-options-grid { grid-template-columns: 1fr; }+ }++ @media (prefers-reduced-motion: reduce) {+ .glow, .glow::before { animation: none; }+ .panel-toggle .chevron { transition: none; }+ }+ </style>+ </head>+ <body>+ <section class="hero" id="hero">+ <div class="circuit-layer" id="circuit"></div>+ <div class="glow" aria-hidden="true"></div>+ <main>+ <div class="hero-copy" data-circuit-reading-zone>+ <p class="eyebrow">Seeded SVG generator</p>+ <h1>Live circuitry</h1>+ <p class="lede">+ A procedural version of the Nitrogen hero pattern: dense routed traces, 45° chamfers,+ annular vias, continuous trace packing, and separate reveal and ambient animation systems.+ </p>+ <p class="hint" id="motionHint">All traces arrive fully routed · no ambient movement</p>+ </div>+ </main>+ </section>++ <form class="controls" id="controls">+ <div class="preset-bar" aria-label="Generator presets">+ <span class="preset-title">Generation</span>+ <button type="button" data-preset="original" aria-pressed="true">Original match</button>+ <button type="button" data-preset="dense" aria-pressed="false">Dense</button>+ <button type="button" data-preset="diagonal" aria-pressed="false">Diagonal sweep</button>+ <button type="button" data-preset="swirl" aria-pressed="false">Broad swirl</button>+ <button type="button" data-preset="sparse" aria-pressed="false">Sparse</button>+ <button type="button" data-preset="adom" aria-pressed="false">ADOM embed</button>+ <button type="button" class="panel-toggle" id="parameterToggle" aria-expanded="false" aria-controls="parameterPanel">+ Parameters<span class="chevron" aria-hidden="true">▾</span>+ </button>+ <output class="trace-count" id="traceCount">235 traces</output>+ </div>+ <div class="parameter-panel" id="parameterPanel" hidden>+ <label>+ Seed+ <input id="seed" type="text" value="nitrogen" autocomplete="off" spellcheck="false" />+ </label>+ <label>+ <span>Density <output id="fillValue">74.4%</output></span>+ <input id="fill" type="range" min="0.35" max="0.76" step="0.001" value="0.744" />+ </label>+ <label>+ <span>Avg length <output id="routeLengthValue">1.14×</output></span>+ <input id="routeLength" type="range" min="0.55" max="2.25" step="0.01" value="1.14" />+ </label>+ <label>+ <span>Primary flow <output id="horizontalFlowValue">90%</output></span>+ <input id="horizontalFlow" type="range" min="0.3" max="0.98" step="0.01" value="0.9" />+ </label>+ <label>+ <span>Angle <output id="flowAngleValue">153°</output></span>+ <input id="flowAngle" type="range" min="0" max="180" step="1" value="153" />+ </label>+ <label>+ <span>Diagonal <output id="diagonalFlowValue">100%</output></span>+ <input id="diagonalFlow" type="range" min="0" max="1" step="0.01" value="1" />+ </label>+ <label>+ <span>Long flow <output id="longFlowValue">31%</output></span>+ <input id="longFlow" type="range" min="0" max="0.36" step="0.01" value="0.31" />+ </label>+ <label>+ <span>Swirl <output id="swirlValue">82%</output></span>+ <input id="swirl" type="range" min="0" max="1.4" step="0.01" value="0.82" />+ </label>+ <label>+ <span>Swirl scale <output id="swirlScaleValue">0.72×</output></span>+ <input id="swirlScale" type="range" min="0.25" max="1.4" step="0.01" value="0.72" />+ </label>+ <label>+ <span>Jog size <output id="jogLengthValue">0.42×</output></span>+ <input id="jogLength" type="range" min="0.3" max="1.8" step="0.01" value="0.42" />+ </label>+ <label>+ <span>Channel pull <output id="channelAttractionValue">150%</output></span>+ <input id="channelAttraction" type="range" min="0" max="1.5" step="0.01" value="1.5" />+ </label>+ <label>+ <span>Scale <output id="featureScaleValue">1.37×</output></span>+ <input id="featureScale" type="range" min="0.55" max="2" step="0.01" value="1.37" />+ </label>+ <label>+ Embedded mark+ <select id="obstaclePreset">+ <option value="none" selected>None</option>+ <option value="adom">ADOM wordmark</option>+ </select>+ </label>+ <label data-obstacle-control>+ Routing mode+ <select id="obstacleMode">+ <option value="avoid" selected>Avoid</option>+ <option value="outline">Outline</option>+ <option value="outline-wrap">Outline + wrap</option>+ </select>+ </label>+ <label data-obstacle-control>+ <span>Mark size <output id="obstacleScaleValue">68%</output></span>+ <input id="obstacleScale" type="range" min="0.34" max="0.86" step="0.01" value="0.68" />+ </label>+ <label data-obstacle-control>+ <span>Horizontal <output id="obstacleXValue">50%</output></span>+ <input id="obstacleX" type="range" min="0.18" max="0.82" step="0.01" value="0.5" />+ </label>+ <label data-obstacle-control>+ <span>Vertical <output id="obstacleYValue">66%</output></span>+ <input id="obstacleY" type="range" min="0.2" max="0.82" step="0.01" value="0.66" />+ </label>+ <label data-obstacle-control>+ <span>Clearance <output id="obstacleClearanceValue">1.1 lanes</output></span>+ <input id="obstacleClearance" type="range" min="0" max="3" step="0.1" value="1.1" />+ </label>+ <label data-obstacle-control>+ <span>Edge pull <output id="obstaclePullValue">82%</output></span>+ <input id="obstaclePull" type="range" min="0" max="1.5" step="0.01" value="0.82" />+ </label>+ </div>+ <div class="preset-bar motion-bar" aria-label="Trace reveal and animation presets">+ <div class="preset-group reveal-group" id="revealGroup" aria-label="Trace reveal presets">+ <span class="preset-title">Reveal</span>+ <button type="button" data-reveal-preset="instant" aria-pressed="true">Instant</button>+ <button type="button" data-reveal-preset="flow" aria-pressed="false">Flow sweep</button>+ <button type="button" data-reveal-preset="scroll" aria-pressed="false">Scroll weave</button>+ <button class="replay-button" id="replayReveal" type="button">Replay</button>+ <button type="button" class="panel-toggle" id="revealOptionsToggle" aria-expanded="false" aria-controls="revealOptionsPanel">+ Options<span class="chevron" aria-hidden="true">▾</span>+ </button>+ </div>+ <span class="group-divider" aria-hidden="true"></span>+ <div class="preset-group animation-group" aria-label="Ambient animation presets">+ <span class="preset-title">Animation</span>+ <button type="button" data-animation-preset="none" aria-pressed="true">None</button>+ <button type="button" data-animation-preset="reflection" aria-pressed="false">Reflection</button>+ <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>+ <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>+ <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ </div>+ <label class="movement-power">+ <span>Movement power <output id="livelinessValue">0%</output></span>+ <input id="liveliness" type="range" min="0" max="1.5" step="0.01" value="0" />+ </label>+ <button class="primary" type="submit">Generate</button>+ <button id="download" type="button">Export SVG</button>+ </div>+ <section class="reveal-options-panel" id="revealOptionsPanel" aria-label="Reveal options" hidden>+ <div class="reveal-options-heading">+ <strong id="revealOptionsTitle">Flow sweep options</strong>+ <span>Changes apply to this reveal preset</span>+ </div>+ <div class="reveal-options-grid">+ <label class="reveal-option" data-reveal-for="flow scroll">+ Spawn pattern+ <select id="spawnMode">+ <option value="flow">Directional flow</option>+ <option value="radial">Radial</option>+ <option value="edges">From edges</option>+ <option value="scatter">Scatter</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn angle <output id="spawnAngleValue">90°</output></span>+ <input id="spawnAngle" type="range" min="0" max="359" step="1" value="90" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn swirl <output id="spawnSwirlValue">7.5%</output></span>+ <input id="spawnSwirl" type="range" min="0" max="0.35" step="0.005" value="0.075" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Trace glow <output id="revealGlowValue">88%</output></span>+ <input id="revealGlow" type="range" min="0" max="1" step="0.01" value="0.88" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Sweep duration <output id="revealDurationValue">7.6 s</output></span>+ <input id="revealDuration" type="range" min="2600" max="18000" step="100" value="7600" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Active traces <output id="revealMaxActiveTracesValue">48</output></span>+ <input id="revealMaxActiveTraces" type="range" min="12" max="96" step="1" value="48" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Trace duration <output id="traceDurationValue">0.95 s</output></span>+ <input id="traceDuration" type="range" min="350" max="2000" step="25" value="950" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Launch rate <output id="revealLaunchRateValue">24/s</output></span>+ <input id="revealLaunchRate" type="range" min="6" max="80" step="1" value="24" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Active traces <output id="maxActiveTracesValue">72</output></span>+ <input id="maxActiveTraces" type="range" min="12" max="160" step="1" value="72" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Speed response <output id="scrollSpeedResponseValue">60%</output></span>+ <input id="scrollSpeedResponse" type="range" min="0" max="1" step="0.01" value="0.6" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Reveal lead <output id="unlockLeadValue">2.5%</output></span>+ <input id="unlockLead" type="range" min="0" max="0.2" step="0.005" value="0.025" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ Continue generation+ <select id="continuousGeneration">+ <option value="true">On</option>+ <option value="false">Off</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Generate ahead <output id="generationAheadScreensValue">2 screens</output></span>+ <input id="generationAheadScreens" type="range" min="1" max="4" step="0.25" value="2" />+ </label>+ </div>+ </section>+ </form>++ <script type="module">+ import { ANIMATION_PRESETS, REVEAL_PRESETS, createCircuitBackground } from "./circuit-background-v9.js?v=1";++ const mount = document.querySelector("#circuit");+ const controls = document.querySelector("#controls");+ const generationPresetButtons = [...document.querySelectorAll("[data-preset]")];+ const revealPresetButtons = [...document.querySelectorAll("[data-reveal-preset]")];+ const animationPresetButtons = [...document.querySelectorAll("[data-animation-preset]")];+ const traceCount = document.querySelector("#traceCount");+ const hero = document.querySelector("#hero");+ const canonicalPageSize = Object.freeze({+ width: Math.max(1, mount.clientWidth),+ height: Math.max(1, mount.clientHeight),+ });+ const glow = document.querySelector(".glow");+ const seed = document.querySelector("#seed");+ const parameterToggle = document.querySelector("#parameterToggle");+ const parameterPanel = document.querySelector("#parameterPanel");+ const motionHint = document.querySelector("#motionHint");+ const revealGroup = document.querySelector("#revealGroup");+ const replayReveal = document.querySelector("#replayReveal");+ const revealOptionsToggle = document.querySelector("#revealOptionsToggle");+ const revealOptionsPanel = document.querySelector("#revealOptionsPanel");+ const revealOptionsTitle = document.querySelector("#revealOptionsTitle");+ const revealOptionElements = [...document.querySelectorAll("[data-reveal-for]")];+ const revealOptionIds = [+ "spawnMode", "spawnAngle", "spawnSwirl", "revealGlow", "revealDuration",+ "revealMaxActiveTraces", "traceDuration", "revealLaunchRate", "maxActiveTraces",+ "scrollSpeedResponse", "unlockLead", "continuousGeneration", "generationAheadScreens",+ ];+ const revealControls = Object.fromEntries(revealOptionIds.map((id) => [id, document.querySelector("#" + id)]));+ const download = document.querySelector("#download");++ const numericGeometryParameterIds = [+ "fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow",+ "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale",+ "obstacleScale", "obstacleX", "obstacleY", "obstacleClearance", "obstaclePull",+ ];+ const enumGeometryParameterIds = ["obstaclePreset", "obstacleMode"];+ const geometryParameterIds = [...numericGeometryParameterIds, ...enumGeometryParameterIds];+ const animationParameterIds = ["liveliness"];+ const numericParameterIds = [...numericGeometryParameterIds, ...animationParameterIds];+ const parameterIds = [...geometryParameterIds, ...animationParameterIds];+ const parameters = Object.fromEntries(parameterIds.map((id) => [id, document.querySelector(`#${id}`)]));+ const obstacleOff = {+ obstaclePreset: "none", obstacleMode: "avoid", obstacleScale: 0.68,+ obstacleX: 0.5, obstacleY: 0.66, obstacleClearance: 1.1, obstaclePull: 0.82,+ };+ const presets = {+ adom: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37, obstaclePreset: "adom", obstacleMode: "outline-wrap", obstacleScale: 0.68, obstacleX: 0.5, obstacleY: 0.66, obstacleClearance: 1.1, obstaclePull: 0.82 },+ original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37, ...obstacleOff },+ dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65, ...obstacleOff },+ diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28, ...obstacleOff },+ swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1, ...obstacleOff },+ sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88, ...obstacleOff },+ };+ const revealHints = {+ instant: "All traces arrive fully routed",+ flow: "A curved front grows every route from via to via",+ scroll: "Scroll unlocks routes; each one grows on its own timeline",+ };+ const animationHints = {+ none: "no ambient movement",+ conductor: "move to shape the current · click to activate the network",+ adom: "move to steer the routed field · click to launch a local bloom",+ handshake: "move to bias the next handshake · click to request a local exchange",+ reflection: "move to catch the light · click to send a quiet reflection",+ };+ const formats = {+ fill: (value) => `${Number((value * 100).toFixed(1))}%`,+ routeLength: (value) => `${value.toFixed(2)}×`,+ horizontalFlow: (value) => `${Math.round(value * 100)}%`,+ flowAngle: (value) => `${Math.round(value)}°`,+ diagonalFlow: (value) => `${Math.round(value * 100)}%`,+ longFlow: (value) => `${Math.round(value * 100)}%`,+ swirl: (value) => `${Math.round(value * 100)}%`,+ swirlScale: (value) => `${value.toFixed(2)}×`,+ jogLength: (value) => `${value.toFixed(2)}×`,+ channelAttraction: (value) => `${Math.round(value * 100)}%`,+ featureScale: (value) => `${value.toFixed(2)}×`,+ obstacleScale: (value) => `${Math.round(value * 100)}%`,+ obstacleX: (value) => `${Math.round(value * 100)}%`,+ obstacleY: (value) => `${Math.round(value * 100)}%`,+ obstacleClearance: (value) => `${value.toFixed(1)} lanes`,+ obstaclePull: (value) => `${Math.round(value * 100)}%`,+ liveliness: (value) => `${Math.round(value * 100)}%`,+ };+ const revealFormats = {+ spawnAngle: (value) => Math.round(value) + "°",+ spawnSwirl: (value) => Number((value * 100).toFixed(1)) + "%",+ revealGlow: (value) => Math.round(value * 100) + "%",+ revealDuration: (value) => (value / 1000).toFixed(1) + " s",+ revealMaxActiveTraces: (value) => String(Math.round(value)),+ traceDuration: (value) => (value / 1000).toFixed(2) + " s",+ revealLaunchRate: (value) => Math.round(value) + "/s",+ maxActiveTraces: (value) => String(Math.round(value)),+ scrollSpeedResponse: (value) => Math.round(value * 100) + "%",+ unlockLead: (value) => Number((value * 100).toFixed(1)) + "%",+ generationAheadScreens: (value) => Number(value.toFixed(2)) + (value === 1 ? " screen" : " screens"),+ };++ function syncObstacleControls() {+ const enabled = parameters.obstaclePreset.value !== "none";+ for (const label of document.querySelectorAll("[data-obstacle-control]")) {+ for (const control of label.querySelectorAll("input, select")) control.disabled = !enabled;+ }+ if (enabled) parameters.obstaclePull.disabled = parameters.obstacleMode.value !== "outline-wrap";+ }++ function updateRevealOptionOutput(id) {+ if (!revealFormats[id]) return;+ const output = document.querySelector("#" + id + "Value");+ if (output) output.value = revealFormats[id](Number(revealControls[id].value));+ }++ function closeRevealOptions() {+ revealOptionsToggle.setAttribute("aria-expanded", "false");+ revealOptionsPanel.hidden = true;+ }++ function syncRevealOptionAvailability(name) {+ const state = revealOptionState[name];+ if (!state) return;+ const directional = state.spawnMode === "flow";+ revealControls.spawnAngle.disabled = !directional;+ revealControls.spawnSwirl.disabled = !directional;+ revealControls.generationAheadScreens.disabled = name === "scroll"+ && !state.continuousGeneration;+ }++ function syncRevealOptionControls(name) {+ if (name !== "flow" && name !== "scroll") return;+ const state = revealOptionState[name];+ for (const element of revealOptionElements) {+ element.hidden = !element.dataset.revealFor.split(" ").includes(name);+ }+ for (const id of revealOptionIds) {+ if (!(id in state)) continue;+ const control = revealControls[id];+ control.value = id === "continuousGeneration"+ ? String(Boolean(state[id]))+ : String(state[id]);+ if (id === "continuousGeneration") state[id] = control.value === "true";+ else if (id === "spawnMode") state[id] = control.value;+ else state[id] = Number(control.value);+ updateRevealOptionOutput(id);+ }+ revealOptionsTitle.textContent = name === "flow" ? "Flow sweep options" : "Scroll weave options";+ syncRevealOptionAvailability(name);+ }+++ const query = new URLSearchParams(location.search);+ const requestedAnimationPreset = query.get("animationPreset");+ const requestedRevealPreset = query.get("revealPreset");+ const legacyGrowthLink = requestedAnimationPreset === "growth";+ const initialAnimationPreset = !legacyGrowthLink && ANIMATION_PRESETS[requestedAnimationPreset]+ ? requestedAnimationPreset+ : "none";+ const initialRevealPreset = legacyGrowthLink+ ? "flow"+ : REVEAL_PRESETS[requestedRevealPreset]+ ? requestedRevealPreset+ : "instant";+ let animationOptions = { ...ANIMATION_PRESETS[initialAnimationPreset] };+ const revealOptionState = {+ flow: {+ ...REVEAL_PRESETS.flow,+ spawnMode: REVEAL_PRESETS.flow.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.flow.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.flow.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.flow.revealGlow ?? 0.88,+ revealDuration: REVEAL_PRESETS.flow.revealDuration ?? 7600,+ revealMaxActiveTraces: REVEAL_PRESETS.flow.revealMaxActiveTraces ?? 48,+ },+ scroll: {+ ...REVEAL_PRESETS.scroll,+ spawnMode: REVEAL_PRESETS.scroll.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.scroll.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.scroll.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.scroll.revealGlow ?? 0.82,+ traceDuration: REVEAL_PRESETS.scroll.traceDuration ?? 950,+ revealLaunchRate: REVEAL_PRESETS.scroll.revealLaunchRate ?? 24,+ maxActiveTraces: REVEAL_PRESETS.scroll.maxActiveTraces ?? 72,+ scrollSpeedResponse: REVEAL_PRESETS.scroll.scrollSpeedResponse ?? 0.6,+ unlockLead: REVEAL_PRESETS.scroll.unlockLead ?? 0.025,+ continuousGeneration: REVEAL_PRESETS.scroll.continuousGeneration ?? true,+ generationAheadScreens: REVEAL_PRESETS.scroll.generationAheadScreens ?? 2,+ },+ };+ let activeRevealPreset = initialRevealPreset;+ const validSpawnModes = new Set(["flow", "radial", "edges", "scatter"]);+ if (activeRevealPreset === "flow" || activeRevealPreset === "scroll") {+ for (const id of revealOptionIds) {+ if (!query.has(id) || !(id in revealOptionState[activeRevealPreset])) continue;+ if (id === "spawnMode") {+ const value = query.get(id);+ if (validSpawnModes.has(value)) revealOptionState[activeRevealPreset][id] = value;+ } else if (id === "continuousGeneration") {+ revealOptionState[activeRevealPreset][id] = !["0", "false", "off"].includes(query.get(id).toLowerCase());+ } else {+ const value = Number(query.get(id));+ if (Number.isFinite(value)) revealOptionState[activeRevealPreset][id] = value;+ }+ }+ }+ if (activeRevealPreset !== "instant" && query.has("revealMotion")) {+ revealOptionState[activeRevealPreset].revealMotion = !["0", "false", "off"].includes(+ query.get("revealMotion").toLowerCase(),+ );+ }+ let revealOptions = activeRevealPreset === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[activeRevealPreset] };+ const revealQueryPresent = revealOptionIds.some((id) => query.has(id));+ if (activeRevealPreset !== "instant") syncRevealOptionControls(activeRevealPreset);+ if (activeRevealPreset !== "instant" && revealQueryPresent) {+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ }+ if (query.has("seed")) seed.value = query.get("seed").slice(0, 80);+ const obstaclePresetValues = new Set(["none", "adom"]);+ const obstacleModeValues = new Set(["avoid", "outline", "outline-wrap"]);+ for (const id of parameterIds) {+ if (!query.has(id)) continue;+ if (id === "obstaclePreset") {+ if (obstaclePresetValues.has(query.get(id))) parameters[id].value = query.get(id);+ continue;+ }+ if (id === "obstacleMode") {+ if (obstacleModeValues.has(query.get(id))) parameters[id].value = query.get(id);+ continue;+ }+ const value = Number(query.get(id));+ if (Number.isFinite(value)) parameters[id].value = String(value);+ }+ syncObstacleControls();+ // A deep link that tunes parameters should show them, not hide the reason the render differs.+ if (geometryParameterIds.some((id) => query.has(id))) {+ parameterToggle.setAttribute("aria-expanded", "true");+ parameterPanel.hidden = false;+ }+ if (!query.has("liveliness")) parameters.liveliness.value = String(animationOptions.liveliness);+ if (query.has("motion")) {+ animationOptions.motion = !["0", "false", "off"].includes(query.get("motion").toLowerCase());+ }++ function setActiveGenerationPreset(name) {+ for (const button of generationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.preset === name));+ }+ }++ function setActiveRevealPreset(name) {+ for (const button of revealPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.revealPreset === name));+ }+ }++ function setActiveAnimationPreset(name) {+ for (const button of animationPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.animationPreset === name));+ }+ }++ function updatePresentation() {+ const routed = animationOptions.animationSystem === "adom";+ const revealSystem = routed ? "instant" : revealOptions.revealSystem;+ hero.dataset.revealSystem = revealSystem;+ revealGroup.dataset.disabled = String(routed);+ revealGroup.setAttribute("aria-disabled", String(routed));+ setActiveRevealPreset(routed ? "instant" : activeRevealPreset);+ for (const button of revealPresetButtons) button.disabled = routed;+ replayReveal.disabled = routed || !(+ revealSystem === "flow"+ || (revealSystem === "scroll" && revealOptions.continuousGeneration)+ );+ revealOptionsToggle.disabled = routed || revealSystem === "instant";+ if (revealOptionsToggle.disabled) closeRevealOptions();+ const revealHint = revealSystem === "scroll" && revealOptions.continuousGeneration+ ? "Scroll queues trace growth and pre-generates page-sized field sections ahead"+ : revealHints[revealSystem] || revealHints.instant;+ motionHint.textContent = routed+ ? "Routed field owns its trace lifecycle · move to steer it and click for a local bloom"+ : [+ revealHint,+ animationHints[animationOptions.animationSystem] || animationHints.none,+ ].join(" · ");+ }++ function applyAtmosphere(options) {+ const amount = Math.max(0, Math.min(1.25, options.atmosphereStrength));+ hero.dataset.animationSystem = options.animationSystem;+ hero.dataset.motion = options.motion ? "on" : "off";+ glow.style.setProperty("--atmosphere-strength", String(amount));+ glow.style.setProperty("--atmosphere-low", String(Math.min(1, amount * 0.66)));+ glow.style.setProperty("--atmosphere-high", String(Math.min(1, amount)));+ updatePresentation();+ }++ function applyReveal() {+ updatePresentation();+ }++ if (geometryParameterIds.some((id) => query.has(id))) setActiveGenerationPreset(null);+ const animationIsCustom = animationParameterIds.some((id) => query.has(id)) || query.has("motion");+ setActiveRevealPreset(initialRevealPreset);+ setActiveAnimationPreset(animationIsCustom ? null : initialAnimationPreset);+ applyReveal();+ applyAtmosphere(animationOptions);++ function optionsFromControls() {+ const options = {+ ...revealOptions,+ ...animationOptions,+ seed: seed.value.trim() || "nitrogen",+ traceColor: "#1d2938",+ canonicalPageWidth: canonicalPageSize.width,+ canonicalPageHeight: canonicalPageSize.height,+ };+ for (const id of numericParameterIds) options[id] = Number(parameters[id].value);+ for (const id of enumGeometryParameterIds) options[id] = parameters[id].value;+ return options;+ }++ function updateOutput(id) {+ if (!formats[id]) return;+ const value = Number(parameters[id].value);+ document.querySelector(`#${id}Value`).value = formats[id](value);+ }+ numericParameterIds.forEach(updateOutput);++ const circuit = createCircuitBackground(mount, optionsFromControls());+ let regenerationTimer;+ let animationTimer;+ let revealUpdateTimer;++ function commitRevealOptions() {+ window.clearTimeout(revealUpdateTimer);+ if (typeof circuit.setReveal === "function") {+ circuit.setReveal(revealOptions);+ } else {+ circuit.regenerate(optionsFromControls());+ }+ queueTraceCount();+ }++ function scheduleRevealUpdate() {+ window.clearTimeout(revealUpdateTimer);+ revealUpdateTimer = window.setTimeout(commitRevealOptions, 120);+ }++ let lastTraceCountText = "";+ function updateTraceCount(stats) {+ const total = circuit.field.traces.length;+ const text = stats?.system === "scroll-trace-reveal"+ ? Math.min(total, stats.completedTraces) + " / " + total + " routed"+ : total + " traces";+ if (text === lastTraceCountText) return;+ lastTraceCountText = text;+ traceCount.value = text;+ }+ let traceCountFrame = 0;+ function tickTraceCount() {+ traceCountFrame = 0;+ const stats = circuit.revealStats;+ updateTraceCount(stats);+ if (+ stats?.continuous+ || (+ stats?.system === "scroll-trace-reveal"+ && (stats.queuedTraces > 0 || stats.activeTraces > 0)+ )+ ) {+ traceCountFrame = window.setTimeout(tickTraceCount, 200);+ }+ }+ function queueTraceCount() {+ if (traceCountFrame) return;+ traceCountFrame = window.requestAnimationFrame(tickTraceCount);+ }+ window.addEventListener("scroll", queueTraceCount, { passive: true });+ window.addEventListener("resize", queueTraceCount, { passive: true });+ queueTraceCount();+ const requestedScrollProgress = Number(query.get("scrollProgress"));+ const requestedScrollScreens = Number(query.get("scrollScreens"));+ if (+ initialRevealPreset === "scroll"+ && revealOptions.continuousGeneration+ && Number.isFinite(requestedScrollScreens)+ && requestedScrollScreens > 0+ ) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const target = requestedScrollScreens * window.innerHeight;+ const startedAt = performance.now();+ const advance = () => {+ const remaining = target - window.scrollY;+ if (remaining <= 2 || performance.now() - startedAt > 15000) return;+ window.scrollBy(0, Math.min(window.innerHeight * 0.42, remaining));+ window.setTimeout(advance, 180);+ };+ advance();+ }));+ } else if (initialRevealPreset === "scroll" && Number.isFinite(requestedScrollProgress)) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const travel = Math.max(0, hero.scrollHeight - window.innerHeight);+ window.scrollTo(0, travel * Math.max(0, Math.min(1, requestedScrollProgress)));+ }));+ }+++ function regenerate() {+ window.clearTimeout(regenerationTimer);+ circuit.regenerate(optionsFromControls());+ queueTraceCount();+ }++ for (const id of parameterIds) {+ parameters[id].addEventListener("input", () => {+ updateOutput(id);+ if (id === "obstaclePreset" || id === "obstacleMode") syncObstacleControls();+ if (!geometryParameterIds.includes(id)) {+ setActiveAnimationPreset(null);+ animationOptions = { ...animationOptions, [id]: Number(parameters[id].value) };+ applyAtmosphere(animationOptions);+ window.clearTimeout(animationTimer);+ if (animationOptions.animationSystem === "adom") {+ animationTimer = window.setTimeout(() => circuit.setAnimation(animationOptions), 140);+ } else {+ circuit.setAnimation(animationOptions);+ }+ return;+ }+ setActiveGenerationPreset(null);+ window.clearTimeout(regenerationTimer);+ regenerationTimer = window.setTimeout(regenerate, 140);+ });+ }+ for (const button of generationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.preset;+ const values = presets[name];+ for (const [id, value] of Object.entries(values)) {+ parameters[id].value = String(value);+ updateOutput(id);+ }+ syncObstacleControls();+ setActiveGenerationPreset(name);+ regenerate();+ });+ }+ parameterToggle.addEventListener("click", () => {+ const expanded = parameterToggle.getAttribute("aria-expanded") === "true";+ parameterToggle.setAttribute("aria-expanded", String(!expanded));+ parameterPanel.hidden = expanded;+ });+ revealOptionsToggle.addEventListener("click", () => {+ if (revealOptionsToggle.disabled) return;+ const expanded = revealOptionsToggle.getAttribute("aria-expanded") === "true";+ if (expanded) {+ closeRevealOptions();+ return;+ }+ syncRevealOptionControls(activeRevealPreset);+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ });+ for (const id of revealOptionIds) {+ revealControls[id].addEventListener("input", () => {+ if (activeRevealPreset !== "flow" && activeRevealPreset !== "scroll") return;+ let value;+ if (id === "spawnMode") value = revealControls[id].value;+ else if (id === "continuousGeneration") value = revealControls[id].value === "true";+ else value = Number(revealControls[id].value);+ revealOptionState[activeRevealPreset][id] = value;+ revealOptions = { ...revealOptionState[activeRevealPreset] };+ updateRevealOptionOutput(id);+ syncRevealOptionAvailability(activeRevealPreset);+ applyReveal();+ scheduleRevealUpdate();+ });+ }+ for (const button of revealPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.revealPreset;+ activeRevealPreset = name;+ revealOptions = name === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[name] };+ if (name !== "instant") syncRevealOptionControls(name);+ setActiveRevealPreset(name);+ applyReveal();+ commitRevealOptions();+ });+ }+ replayReveal.addEventListener("click", () => {+ circuit.triggerReveal();+ });+ for (const button of animationPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.animationPreset;+ animationOptions = { ...ANIMATION_PRESETS[name] };+ parameters.liveliness.value = String(animationOptions.liveliness);+ updateOutput("liveliness");+ applyAtmosphere(animationOptions);+ setActiveAnimationPreset(name);+ window.clearTimeout(animationTimer);+ circuit.setAnimation(animationOptions);+ updateTraceCount();+ });+ }+ seed.addEventListener("change", regenerate);++ controls.addEventListener("submit", (event) => {+ event.preventDefault();+ regenerate();+ });++ function saveBlob(text, name) {+ const blob = new Blob([text], { type: "image/svg+xml" });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ URL.revokeObjectURL(url);+ }++ const slug = () => (seed.value || "seed").replace(/[^a-z0-9_-]+/gi, "-");++ download.addEventListener("click", () => {+ saveBlob(circuit.exportSvg(), `circuit-${slug()}.svg`);+ });++ </script>+ </body>+</html>
src/index.html+599−31@@ -22,11 +22,13 @@ background: var(--bg); color: var(--text); font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ overflow-x: hidden; } .hero { --circuit-hole: var(--bg); position: relative;+ width: 100vw; min-height: 100svh; overflow: hidden; display: grid;@@ -34,6 +36,19 @@ isolation: isolate; } + .hero[data-reveal-system="scroll"] {+ min-height: 300svh;+ place-items: start center;+ }++ .hero[data-reveal-system="scroll"] main {+ position: relative;+ top: auto;+ min-height: 100svh;+ display: grid;+ place-items: center;+ }+ .circuit-layer { position: absolute; inset: 0;@@ -172,6 +187,19 @@ } input[type="text"]:focus { border-color: var(--accent); } input[type="range"] { width: 100%; accent-color: var(--accent); }+ select {+ width: 100%;+ height: 32px;+ padding: 0 28px 0 8px;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 8px;+ outline: none;+ background: #0d1117;+ font: 600 11px system-ui, sans-serif;+ }+ select:focus { border-color: var(--accent); }+ label:has(input:disabled), label:has(select:disabled) { opacity: .42; } button { height: 32px;@@ -184,6 +212,8 @@ cursor: pointer; } button:hover { border-color: #59636e; background: #282e36; }+ button:disabled { opacity: .48; cursor: default; }+ button:disabled:hover { border-color: var(--border); background: #21262d; } button.primary { color: #062d2b; border-color: var(--accent); background: var(--accent); } button.primary:hover { background: var(--accent-bright); } @@ -220,6 +250,42 @@ gap: 8px; } .parameter-panel[hidden] { display: none; }+ .reveal-options-panel {+ position: absolute;+ right: 10px;+ bottom: calc(100% + 8px);+ width: min(760px, calc(100vw - 44px));+ max-height: calc(100svh - 116px);+ overflow-y: auto;+ padding: 12px;+ border: 1px solid rgba(48, 54, 61, .96);+ border-radius: 12px;+ background: rgba(18, 23, 30, .97);+ box-shadow: 0 18px 70px rgba(0,0,0,.48);+ backdrop-filter: blur(20px);+ }+ .reveal-options-panel[hidden] { display: none; }+ .reveal-options-heading {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 10px;+ }+ .reveal-options-heading strong {+ color: var(--text);+ font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ letter-spacing: .1em;+ text-transform: uppercase;+ }+ .reveal-options-heading span { color: var(--muted); font-size: 10px; }+ .reveal-options-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 10px 12px;+ }+ .reveal-option[hidden] { display: none; }+ .reveal-option output { color: #c4d0dc; } /* A quiet text toggle, not a button: it opens a drawer, it does not pick a preset. */ .preset-bar .panel-toggle { display: inline-flex;@@ -241,10 +307,30 @@ .panel-toggle .chevron { display: inline-block; font-size: 9px; line-height: 1; transition: transform .15s ease; } .panel-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); } - .animation-bar {+ .motion-bar { padding-top: 8px; border-top: 1px solid rgba(48, 54, 61, .72); }+ .preset-group {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }+ .group-divider {+ align-self: stretch;+ width: 1px;+ min-height: 22px;+ margin: 0 2px;+ background: rgba(48, 54, 61, .8);+ }+ .reveal-group[data-disabled="true"] { opacity: .48; }+ .reveal-group[data-disabled="true"] button { pointer-events: none; }+ .preset-bar .replay-button {+ padding-inline: 7px;+ color: var(--muted);+ border-style: dashed;+ } .movement-power { flex: 1 1 150px; max-width: 180px;@@ -265,7 +351,9 @@ overflow-y: auto; } .parameter-panel { grid-template-columns: repeat(6, minmax(0, 1fr)); }+ .controls:has(.reveal-options-panel:not([hidden])) { overflow: visible; } .preset-bar { flex-wrap: wrap; }+ .preset-group { flex-wrap: wrap; } } @media (max-width: 760px) {@@ -275,6 +363,21 @@ .preset-title { width: 100%; } .trace-count { margin-left: 0; } main { padding-bottom: 360px; }+ .reveal-options-panel {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 8px);+ width: auto;+ max-height: calc(100svh - 156px);+ overflow-y: auto;+ border-radius: 16px 16px 10px 10px;+ }+ .reveal-options-grid { grid-template-columns: 1fr 1fr; }+ }++ @media (max-width: 460px) {+ .reveal-options-grid { grid-template-columns: 1fr; } } @media (prefers-reduced-motion: reduce) {@@ -293,9 +396,9 @@ <h1>Live circuitry</h1> <p class="lede"> A procedural version of the Nitrogen hero pattern: dense routed traces, 45° chamfers,- annular vias, continuous trace packing, and three complete animation systems for the generated topology.+ annular vias, continuous trace packing, and separate reveal and ambient animation systems. </p>- <p class="hint" id="motionHint">Static circuit · no animation layers</p>+ <p class="hint" id="motionHint">All traces arrive fully routed · no ambient movement</p> </div> </main> </section>@@ -308,6 +411,7 @@ <button type="button" data-preset="diagonal" aria-pressed="false">Diagonal sweep</button> <button type="button" data-preset="swirl" aria-pressed="false">Broad swirl</button> <button type="button" data-preset="sparse" aria-pressed="false">Sparse</button>+ <button type="button" data-preset="adom" aria-pressed="false">ADOM embed</button> <button type="button" class="panel-toggle" id="parameterToggle" aria-expanded="false" aria-controls="parameterPanel"> Parameters<span class="chevron" aria-hidden="true">▾</span> </button>@@ -362,13 +466,62 @@ <span>Scale <output id="featureScaleValue">1.37×</output></span> <input id="featureScale" type="range" min="0.55" max="2" step="0.01" value="1.37" /> </label>+ <label>+ Embedded mark+ <select id="obstaclePreset">+ <option value="none" selected>None</option>+ <option value="adom">ADOM wordmark</option>+ </select>+ </label>+ <label data-obstacle-control>+ Routing mode+ <select id="obstacleMode">+ <option value="avoid" selected>Avoid</option>+ <option value="outline">Outline</option>+ <option value="outline-wrap">Outline + wrap</option>+ </select>+ </label>+ <label data-obstacle-control>+ <span>Mark size <output id="obstacleScaleValue">68%</output></span>+ <input id="obstacleScale" type="range" min="0.34" max="0.86" step="0.01" value="0.68" />+ </label>+ <label data-obstacle-control>+ <span>Horizontal <output id="obstacleXValue">50%</output></span>+ <input id="obstacleX" type="range" min="0.18" max="0.82" step="0.01" value="0.5" />+ </label>+ <label data-obstacle-control>+ <span>Vertical <output id="obstacleYValue">66%</output></span>+ <input id="obstacleY" type="range" min="0.2" max="0.82" step="0.01" value="0.66" />+ </label>+ <label data-obstacle-control>+ <span>Clearance <output id="obstacleClearanceValue">1.1 lanes</output></span>+ <input id="obstacleClearance" type="range" min="0" max="3" step="0.1" value="1.1" />+ </label>+ <label data-obstacle-control>+ <span>Edge pull <output id="obstaclePullValue">82%</output></span>+ <input id="obstaclePull" type="range" min="0" max="1.5" step="0.01" value="0.82" />+ </label> </div>- <div class="preset-bar animation-bar" aria-label="Animation presets">- <span class="preset-title">Animation</span>- <button type="button" data-animation-preset="none" aria-pressed="true">None</button>- <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>- <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>- <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ <div class="preset-bar motion-bar" aria-label="Trace reveal and animation presets">+ <div class="preset-group reveal-group" id="revealGroup" aria-label="Trace reveal presets">+ <span class="preset-title">Reveal</span>+ <button type="button" data-reveal-preset="instant" aria-pressed="true">Instant</button>+ <button type="button" data-reveal-preset="flow" aria-pressed="false">Flow sweep</button>+ <button type="button" data-reveal-preset="scroll" aria-pressed="false">Scroll weave</button>+ <button class="replay-button" id="replayReveal" type="button">Replay</button>+ <button type="button" class="panel-toggle" id="revealOptionsToggle" aria-expanded="false" aria-controls="revealOptionsPanel">+ Options<span class="chevron" aria-hidden="true">▾</span>+ </button>+ </div>+ <span class="group-divider" aria-hidden="true"></span>+ <div class="preset-group animation-group" aria-label="Ambient animation presets">+ <span class="preset-title">Animation</span>+ <button type="button" data-animation-preset="none" aria-pressed="true">None</button>+ <button type="button" data-animation-preset="reflection" aria-pressed="false">Reflection</button>+ <button type="button" data-animation-preset="conductor" aria-pressed="false">Conductor</button>+ <button type="button" data-animation-preset="routed" aria-pressed="false">Routed field</button>+ <button type="button" data-animation-preset="handshake" aria-pressed="false">Handshake</button>+ </div> <label class="movement-power"> <span>Movement power <output id="livelinessValue">0%</output></span> <input id="liveliness" type="range" min="0" max="1.5" step="0.01" value="0" />@@ -376,40 +529,143 @@ <button class="primary" type="submit">Generate</button> <button id="download" type="button">Export SVG</button> </div>+ <section class="reveal-options-panel" id="revealOptionsPanel" aria-label="Reveal options" hidden>+ <div class="reveal-options-heading">+ <strong id="revealOptionsTitle">Flow sweep options</strong>+ <span>Changes apply to this reveal preset</span>+ </div>+ <div class="reveal-options-grid">+ <label class="reveal-option" data-reveal-for="flow scroll">+ Spawn pattern+ <select id="spawnMode">+ <option value="flow">Directional flow</option>+ <option value="radial">Radial</option>+ <option value="edges">From edges</option>+ <option value="scatter">Scatter</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn angle <output id="spawnAngleValue">90°</output></span>+ <input id="spawnAngle" type="range" min="0" max="359" step="1" value="90" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Spawn swirl <output id="spawnSwirlValue">7.5%</output></span>+ <input id="spawnSwirl" type="range" min="0" max="0.35" step="0.005" value="0.075" />+ </label>+ <label class="reveal-option" data-reveal-for="flow scroll">+ <span>Trace glow <output id="revealGlowValue">88%</output></span>+ <input id="revealGlow" type="range" min="0" max="1" step="0.01" value="0.88" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Sweep duration <output id="revealDurationValue">7.6 s</output></span>+ <input id="revealDuration" type="range" min="2600" max="18000" step="100" value="7600" />+ </label>+ <label class="reveal-option" data-reveal-for="flow">+ <span>Active traces <output id="revealMaxActiveTracesValue">48</output></span>+ <input id="revealMaxActiveTraces" type="range" min="12" max="96" step="1" value="48" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Trace duration <output id="traceDurationValue">0.95 s</output></span>+ <input id="traceDuration" type="range" min="350" max="2000" step="25" value="950" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Launch rate <output id="revealLaunchRateValue">24/s</output></span>+ <input id="revealLaunchRate" type="range" min="6" max="80" step="1" value="24" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Active traces <output id="maxActiveTracesValue">72</output></span>+ <input id="maxActiveTraces" type="range" min="12" max="160" step="1" value="72" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Speed response <output id="scrollSpeedResponseValue">60%</output></span>+ <input id="scrollSpeedResponse" type="range" min="0" max="1" step="0.01" value="0.6" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Reveal lead <output id="unlockLeadValue">2.5%</output></span>+ <input id="unlockLead" type="range" min="0" max="0.2" step="0.005" value="0.025" />+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ Continue generation+ <select id="continuousGeneration">+ <option value="true">On</option>+ <option value="false">Off</option>+ </select>+ </label>+ <label class="reveal-option" data-reveal-for="scroll">+ <span>Generate ahead <output id="generationAheadScreensValue">2 screens</output></span>+ <input id="generationAheadScreens" type="range" min="1" max="4" step="0.25" value="2" />+ </label>+ </div>+ </section> </form> <script type="module">- import { ANIMATION_PRESETS, createCircuitBackground } from "./circuit-background-v5.js?v=3";+ import { ANIMATION_PRESETS, REVEAL_PRESETS, createCircuitBackground } from "./circuit-background-v9.js?v=1"; const mount = document.querySelector("#circuit"); const controls = document.querySelector("#controls"); const generationPresetButtons = [...document.querySelectorAll("[data-preset]")];+ const revealPresetButtons = [...document.querySelectorAll("[data-reveal-preset]")]; const animationPresetButtons = [...document.querySelectorAll("[data-animation-preset]")]; const traceCount = document.querySelector("#traceCount"); const hero = document.querySelector("#hero");+ const canonicalPageSize = Object.freeze({+ width: Math.max(1, mount.clientWidth),+ height: Math.max(1, mount.clientHeight),+ }); const glow = document.querySelector(".glow"); const seed = document.querySelector("#seed"); const parameterToggle = document.querySelector("#parameterToggle"); const parameterPanel = document.querySelector("#parameterPanel"); const motionHint = document.querySelector("#motionHint");+ const revealGroup = document.querySelector("#revealGroup");+ const replayReveal = document.querySelector("#replayReveal");+ const revealOptionsToggle = document.querySelector("#revealOptionsToggle");+ const revealOptionsPanel = document.querySelector("#revealOptionsPanel");+ const revealOptionsTitle = document.querySelector("#revealOptionsTitle");+ const revealOptionElements = [...document.querySelectorAll("[data-reveal-for]")];+ const revealOptionIds = [+ "spawnMode", "spawnAngle", "spawnSwirl", "revealGlow", "revealDuration",+ "revealMaxActiveTraces", "traceDuration", "revealLaunchRate", "maxActiveTraces",+ "scrollSpeedResponse", "unlockLead", "continuousGeneration", "generationAheadScreens",+ ];+ const revealControls = Object.fromEntries(revealOptionIds.map((id) => [id, document.querySelector("#" + id)])); const download = document.querySelector("#download"); - const geometryParameterIds = ["fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow", "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale"];+ const numericGeometryParameterIds = [+ "fill", "routeLength", "horizontalFlow", "flowAngle", "diagonalFlow", "longFlow",+ "swirl", "swirlScale", "jogLength", "channelAttraction", "featureScale",+ "obstacleScale", "obstacleX", "obstacleY", "obstacleClearance", "obstaclePull",+ ];+ const enumGeometryParameterIds = ["obstaclePreset", "obstacleMode"];+ const geometryParameterIds = [...numericGeometryParameterIds, ...enumGeometryParameterIds]; const animationParameterIds = ["liveliness"];+ const numericParameterIds = [...numericGeometryParameterIds, ...animationParameterIds]; const parameterIds = [...geometryParameterIds, ...animationParameterIds]; const parameters = Object.fromEntries(parameterIds.map((id) => [id, document.querySelector(`#${id}`)]));+ const obstacleOff = {+ obstaclePreset: "none", obstacleMode: "avoid", obstacleScale: 0.68,+ obstacleX: 0.5, obstacleY: 0.66, obstacleClearance: 1.1, obstaclePull: 0.82,+ }; const presets = {- original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37 },- dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65 },- diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28 },- swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1 },- sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88 },+ adom: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37, obstaclePreset: "adom", obstacleMode: "outline-wrap", obstacleScale: 0.68, obstacleX: 0.5, obstacleY: 0.66, obstacleClearance: 1.1, obstaclePull: 0.82 },+ original: { fill: 0.744, routeLength: 1.14, horizontalFlow: 0.9, flowAngle: 153, diagonalFlow: 1, longFlow: 0.31, swirl: 0.82, swirlScale: 0.72, jogLength: 0.42, channelAttraction: 1.5, featureScale: 1.37, ...obstacleOff },+ dense: { fill: 0.76, routeLength: 1.29, horizontalFlow: 0.57, flowAngle: 138, diagonalFlow: 0.26, longFlow: 0.3, swirl: 0.43, swirlScale: 0.52, jogLength: 0.85, channelAttraction: 0.69, featureScale: 0.65, ...obstacleOff },+ diagonal: { fill: 0.591, routeLength: 1.51, horizontalFlow: 0.98, flowAngle: 45, diagonalFlow: 1, longFlow: 0, swirl: 0, swirlScale: 0.75, jogLength: 0.65, channelAttraction: 0.86, featureScale: 1.28, ...obstacleOff },+ swirl: { fill: 0.58, routeLength: 1.1, horizontalFlow: 0.82, flowAngle: 15, diagonalFlow: 0.72, longFlow: 0.2, swirl: 0.9, swirlScale: 0.9, jogLength: 0.75, channelAttraction: 0.8, featureScale: 1, ...obstacleOff },+ sparse: { fill: 0.35, routeLength: 1.9, horizontalFlow: 0.45, flowAngle: 0, diagonalFlow: 0.3, longFlow: 0.32, swirl: 0.08, swirlScale: 0.93, jogLength: 0.57, channelAttraction: 0.6, featureScale: 0.88, ...obstacleOff },+ };+ const revealHints = {+ instant: "All traces arrive fully routed",+ flow: "A curved front grows every route from via to via",+ scroll: "Scroll unlocks routes; each one grows on its own timeline", }; const animationHints = {- none: "Static circuit · no animation layers",- conductor: "Move to shape the current · click anywhere to activate the network",- adom: "Move to steer the routed field · click to launch a local bloom",- handshake: "Move to bias the next handshake · click to request a local exchange",+ none: "no ambient movement",+ conductor: "move to shape the current · click to activate the network",+ adom: "move to steer the routed field · click to launch a local bloom",+ handshake: "move to bias the next handshake · click to request a local exchange",+ reflection: "move to catch the light · click to send a quiet reflection", }; const formats = { fill: (value) => `${Number((value * 100).toFixed(1))}%`,@@ -423,21 +679,163 @@ jogLength: (value) => `${value.toFixed(2)}×`, channelAttraction: (value) => `${Math.round(value * 100)}%`, featureScale: (value) => `${value.toFixed(2)}×`,+ obstacleScale: (value) => `${Math.round(value * 100)}%`,+ obstacleX: (value) => `${Math.round(value * 100)}%`,+ obstacleY: (value) => `${Math.round(value * 100)}%`,+ obstacleClearance: (value) => `${value.toFixed(1)} lanes`,+ obstaclePull: (value) => `${Math.round(value * 100)}%`, liveliness: (value) => `${Math.round(value * 100)}%`, };+ const revealFormats = {+ spawnAngle: (value) => Math.round(value) + "°",+ spawnSwirl: (value) => Number((value * 100).toFixed(1)) + "%",+ revealGlow: (value) => Math.round(value * 100) + "%",+ revealDuration: (value) => (value / 1000).toFixed(1) + " s",+ revealMaxActiveTraces: (value) => String(Math.round(value)),+ traceDuration: (value) => (value / 1000).toFixed(2) + " s",+ revealLaunchRate: (value) => Math.round(value) + "/s",+ maxActiveTraces: (value) => String(Math.round(value)),+ scrollSpeedResponse: (value) => Math.round(value * 100) + "%",+ unlockLead: (value) => Number((value * 100).toFixed(1)) + "%",+ generationAheadScreens: (value) => Number(value.toFixed(2)) + (value === 1 ? " screen" : " screens"),+ };++ function syncObstacleControls() {+ const enabled = parameters.obstaclePreset.value !== "none";+ for (const label of document.querySelectorAll("[data-obstacle-control]")) {+ for (const control of label.querySelectorAll("input, select")) control.disabled = !enabled;+ }+ if (enabled) parameters.obstaclePull.disabled = parameters.obstacleMode.value !== "outline-wrap";+ }++ function updateRevealOptionOutput(id) {+ if (!revealFormats[id]) return;+ const output = document.querySelector("#" + id + "Value");+ if (output) output.value = revealFormats[id](Number(revealControls[id].value));+ }++ function closeRevealOptions() {+ revealOptionsToggle.setAttribute("aria-expanded", "false");+ revealOptionsPanel.hidden = true;+ }++ function syncRevealOptionAvailability(name) {+ const state = revealOptionState[name];+ if (!state) return;+ const directional = state.spawnMode === "flow";+ revealControls.spawnAngle.disabled = !directional;+ revealControls.spawnSwirl.disabled = !directional;+ revealControls.generationAheadScreens.disabled = name === "scroll"+ && !state.continuousGeneration;+ }++ function syncRevealOptionControls(name) {+ if (name !== "flow" && name !== "scroll") return;+ const state = revealOptionState[name];+ for (const element of revealOptionElements) {+ element.hidden = !element.dataset.revealFor.split(" ").includes(name);+ }+ for (const id of revealOptionIds) {+ if (!(id in state)) continue;+ const control = revealControls[id];+ control.value = id === "continuousGeneration"+ ? String(Boolean(state[id]))+ : String(state[id]);+ if (id === "continuousGeneration") state[id] = control.value === "true";+ else if (id === "spawnMode") state[id] = control.value;+ else state[id] = Number(control.value);+ updateRevealOptionOutput(id);+ }+ revealOptionsTitle.textContent = name === "flow" ? "Flow sweep options" : "Scroll weave options";+ syncRevealOptionAvailability(name);+ }+ const query = new URLSearchParams(location.search); const requestedAnimationPreset = query.get("animationPreset");- const initialAnimationPreset = ANIMATION_PRESETS[requestedAnimationPreset]+ const requestedRevealPreset = query.get("revealPreset");+ const legacyGrowthLink = requestedAnimationPreset === "growth";+ const initialAnimationPreset = !legacyGrowthLink && ANIMATION_PRESETS[requestedAnimationPreset] ? requestedAnimationPreset : "none";+ const initialRevealPreset = legacyGrowthLink+ ? "flow"+ : REVEAL_PRESETS[requestedRevealPreset]+ ? requestedRevealPreset+ : "instant"; let animationOptions = { ...ANIMATION_PRESETS[initialAnimationPreset] };+ const revealOptionState = {+ flow: {+ ...REVEAL_PRESETS.flow,+ spawnMode: REVEAL_PRESETS.flow.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.flow.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.flow.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.flow.revealGlow ?? 0.88,+ revealDuration: REVEAL_PRESETS.flow.revealDuration ?? 7600,+ revealMaxActiveTraces: REVEAL_PRESETS.flow.revealMaxActiveTraces ?? 48,+ },+ scroll: {+ ...REVEAL_PRESETS.scroll,+ spawnMode: REVEAL_PRESETS.scroll.spawnMode || "flow",+ spawnAngle: REVEAL_PRESETS.scroll.spawnAngle ?? 90,+ spawnSwirl: REVEAL_PRESETS.scroll.spawnSwirl ?? 0.075,+ revealGlow: REVEAL_PRESETS.scroll.revealGlow ?? 0.82,+ traceDuration: REVEAL_PRESETS.scroll.traceDuration ?? 950,+ revealLaunchRate: REVEAL_PRESETS.scroll.revealLaunchRate ?? 24,+ maxActiveTraces: REVEAL_PRESETS.scroll.maxActiveTraces ?? 72,+ scrollSpeedResponse: REVEAL_PRESETS.scroll.scrollSpeedResponse ?? 0.6,+ unlockLead: REVEAL_PRESETS.scroll.unlockLead ?? 0.025,+ continuousGeneration: REVEAL_PRESETS.scroll.continuousGeneration ?? true,+ generationAheadScreens: REVEAL_PRESETS.scroll.generationAheadScreens ?? 2,+ },+ };+ let activeRevealPreset = initialRevealPreset;+ const validSpawnModes = new Set(["flow", "radial", "edges", "scatter"]);+ if (activeRevealPreset === "flow" || activeRevealPreset === "scroll") {+ for (const id of revealOptionIds) {+ if (!query.has(id) || !(id in revealOptionState[activeRevealPreset])) continue;+ if (id === "spawnMode") {+ const value = query.get(id);+ if (validSpawnModes.has(value)) revealOptionState[activeRevealPreset][id] = value;+ } else if (id === "continuousGeneration") {+ revealOptionState[activeRevealPreset][id] = !["0", "false", "off"].includes(query.get(id).toLowerCase());+ } else {+ const value = Number(query.get(id));+ if (Number.isFinite(value)) revealOptionState[activeRevealPreset][id] = value;+ }+ }+ }+ if (activeRevealPreset !== "instant" && query.has("revealMotion")) {+ revealOptionState[activeRevealPreset].revealMotion = !["0", "false", "off"].includes(+ query.get("revealMotion").toLowerCase(),+ );+ }+ let revealOptions = activeRevealPreset === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[activeRevealPreset] };+ const revealQueryPresent = revealOptionIds.some((id) => query.has(id));+ if (activeRevealPreset !== "instant") syncRevealOptionControls(activeRevealPreset);+ if (activeRevealPreset !== "instant" && revealQueryPresent) {+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ } if (query.has("seed")) seed.value = query.get("seed").slice(0, 80);+ const obstaclePresetValues = new Set(["none", "adom"]);+ const obstacleModeValues = new Set(["avoid", "outline", "outline-wrap"]); for (const id of parameterIds) { if (!query.has(id)) continue;+ if (id === "obstaclePreset") {+ if (obstaclePresetValues.has(query.get(id))) parameters[id].value = query.get(id);+ continue;+ }+ if (id === "obstacleMode") {+ if (obstacleModeValues.has(query.get(id))) parameters[id].value = query.get(id);+ continue;+ } const value = Number(query.get(id)); if (Number.isFinite(value)) parameters[id].value = String(value); }+ syncObstacleControls(); // A deep link that tunes parameters should show them, not hide the reason the render differs. if (geometryParameterIds.some((id) => query.has(id))) { parameterToggle.setAttribute("aria-expanded", "true");@@ -454,12 +852,43 @@ } } + function setActiveRevealPreset(name) {+ for (const button of revealPresetButtons) {+ button.setAttribute("aria-pressed", String(button.dataset.revealPreset === name));+ }+ }+ function setActiveAnimationPreset(name) { for (const button of animationPresetButtons) { button.setAttribute("aria-pressed", String(button.dataset.animationPreset === name)); } } + function updatePresentation() {+ const routed = animationOptions.animationSystem === "adom";+ const revealSystem = routed ? "instant" : revealOptions.revealSystem;+ hero.dataset.revealSystem = revealSystem;+ revealGroup.dataset.disabled = String(routed);+ revealGroup.setAttribute("aria-disabled", String(routed));+ setActiveRevealPreset(routed ? "instant" : activeRevealPreset);+ for (const button of revealPresetButtons) button.disabled = routed;+ replayReveal.disabled = routed || !(+ revealSystem === "flow"+ || (revealSystem === "scroll" && revealOptions.continuousGeneration)+ );+ revealOptionsToggle.disabled = routed || revealSystem === "instant";+ if (revealOptionsToggle.disabled) closeRevealOptions();+ const revealHint = revealSystem === "scroll" && revealOptions.continuousGeneration+ ? "Scroll queues trace growth and pre-generates page-sized field sections ahead"+ : revealHints[revealSystem] || revealHints.instant;+ motionHint.textContent = routed+ ? "Routed field owns its trace lifecycle · move to steer it and click for a local bloom"+ : [+ revealHint,+ animationHints[animationOptions.animationSystem] || animationHints.none,+ ].join(" · ");+ }+ function applyAtmosphere(options) { const amount = Math.max(0, Math.min(1.25, options.atmosphereStrength)); hero.dataset.animationSystem = options.animationSystem;@@ -467,49 +896,143 @@ glow.style.setProperty("--atmosphere-strength", String(amount)); glow.style.setProperty("--atmosphere-low", String(Math.min(1, amount * 0.66))); glow.style.setProperty("--atmosphere-high", String(Math.min(1, amount)));- motionHint.textContent = animationHints[options.animationSystem] || animationHints.none;+ updatePresentation();+ }++ function applyReveal() {+ updatePresentation(); } if (geometryParameterIds.some((id) => query.has(id))) setActiveGenerationPreset(null); const animationIsCustom = animationParameterIds.some((id) => query.has(id)) || query.has("motion");+ setActiveRevealPreset(initialRevealPreset); setActiveAnimationPreset(animationIsCustom ? null : initialAnimationPreset);+ applyReveal(); applyAtmosphere(animationOptions); function optionsFromControls() { const options = {+ ...revealOptions, ...animationOptions, seed: seed.value.trim() || "nitrogen", traceColor: "#1d2938",+ canonicalPageWidth: canonicalPageSize.width,+ canonicalPageHeight: canonicalPageSize.height, };- for (const id of parameterIds) options[id] = Number(parameters[id].value);+ for (const id of numericParameterIds) options[id] = Number(parameters[id].value);+ for (const id of enumGeometryParameterIds) options[id] = parameters[id].value; return options; } function updateOutput(id) {+ if (!formats[id]) return; const value = Number(parameters[id].value); document.querySelector(`#${id}Value`).value = formats[id](value); }- parameterIds.forEach(updateOutput);+ numericParameterIds.forEach(updateOutput); const circuit = createCircuitBackground(mount, optionsFromControls()); let regenerationTimer;+ let animationTimer;+ let revealUpdateTimer; - function updateTraceCount() {- traceCount.value = `${circuit.field.traces.length} traces`;+ function commitRevealOptions() {+ window.clearTimeout(revealUpdateTimer);+ if (typeof circuit.setReveal === "function") {+ circuit.setReveal(revealOptions);+ } else {+ circuit.regenerate(optionsFromControls());+ }+ queueTraceCount();+ }++ function scheduleRevealUpdate() {+ window.clearTimeout(revealUpdateTimer);+ revealUpdateTimer = window.setTimeout(commitRevealOptions, 120);+ }++ let lastTraceCountText = "";+ function updateTraceCount(stats) {+ const total = circuit.field.traces.length;+ const text = stats?.system === "scroll-trace-reveal"+ ? Math.min(total, stats.completedTraces) + " / " + total + " routed"+ : total + " traces";+ if (text === lastTraceCountText) return;+ lastTraceCountText = text;+ traceCount.value = text;+ }+ let traceCountFrame = 0;+ function tickTraceCount() {+ traceCountFrame = 0;+ const stats = circuit.revealStats;+ updateTraceCount(stats);+ if (+ stats?.continuous+ || (+ stats?.system === "scroll-trace-reveal"+ && (stats.queuedTraces > 0 || stats.activeTraces > 0)+ )+ ) {+ traceCountFrame = window.setTimeout(tickTraceCount, 200);+ }+ }+ function queueTraceCount() {+ if (traceCountFrame) return;+ traceCountFrame = window.requestAnimationFrame(tickTraceCount);+ }+ window.addEventListener("scroll", queueTraceCount, { passive: true });+ window.addEventListener("resize", queueTraceCount, { passive: true });+ queueTraceCount();+ const requestedScrollProgress = Number(query.get("scrollProgress"));+ const requestedScrollScreens = Number(query.get("scrollScreens"));+ if (+ initialRevealPreset === "scroll"+ && revealOptions.continuousGeneration+ && Number.isFinite(requestedScrollScreens)+ && requestedScrollScreens > 0+ ) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const target = requestedScrollScreens * window.innerHeight;+ const startedAt = performance.now();+ const advance = () => {+ const remaining = target - window.scrollY;+ if (remaining <= 2 || performance.now() - startedAt > 15000) return;+ window.scrollBy(0, Math.min(window.innerHeight * 0.42, remaining));+ window.setTimeout(advance, 180);+ };+ advance();+ }));+ } else if (initialRevealPreset === "scroll" && Number.isFinite(requestedScrollProgress)) {+ window.requestAnimationFrame(() => window.requestAnimationFrame(() => {+ const travel = Math.max(0, hero.scrollHeight - window.innerHeight);+ window.scrollTo(0, travel * Math.max(0, Math.min(1, requestedScrollProgress)));+ })); }- updateTraceCount();+ function regenerate() { window.clearTimeout(regenerationTimer); circuit.regenerate(optionsFromControls());- updateTraceCount();+ queueTraceCount(); } for (const id of parameterIds) { parameters[id].addEventListener("input", () => {- if (geometryParameterIds.includes(id)) setActiveGenerationPreset(null);- else setActiveAnimationPreset(null); updateOutput(id);+ if (id === "obstaclePreset" || id === "obstacleMode") syncObstacleControls();+ if (!geometryParameterIds.includes(id)) {+ setActiveAnimationPreset(null);+ animationOptions = { ...animationOptions, [id]: Number(parameters[id].value) };+ applyAtmosphere(animationOptions);+ window.clearTimeout(animationTimer);+ if (animationOptions.animationSystem === "adom") {+ animationTimer = window.setTimeout(() => circuit.setAnimation(animationOptions), 140);+ } else {+ circuit.setAnimation(animationOptions);+ }+ return;+ }+ setActiveGenerationPreset(null); window.clearTimeout(regenerationTimer); regenerationTimer = window.setTimeout(regenerate, 140); });@@ -522,6 +1045,7 @@ parameters[id].value = String(value); updateOutput(id); }+ syncObstacleControls(); setActiveGenerationPreset(name); regenerate(); });@@ -531,6 +1055,48 @@ parameterToggle.setAttribute("aria-expanded", String(!expanded)); parameterPanel.hidden = expanded; });+ revealOptionsToggle.addEventListener("click", () => {+ if (revealOptionsToggle.disabled) return;+ const expanded = revealOptionsToggle.getAttribute("aria-expanded") === "true";+ if (expanded) {+ closeRevealOptions();+ return;+ }+ syncRevealOptionControls(activeRevealPreset);+ revealOptionsToggle.setAttribute("aria-expanded", "true");+ revealOptionsPanel.hidden = false;+ });+ for (const id of revealOptionIds) {+ revealControls[id].addEventListener("input", () => {+ if (activeRevealPreset !== "flow" && activeRevealPreset !== "scroll") return;+ let value;+ if (id === "spawnMode") value = revealControls[id].value;+ else if (id === "continuousGeneration") value = revealControls[id].value === "true";+ else value = Number(revealControls[id].value);+ revealOptionState[activeRevealPreset][id] = value;+ revealOptions = { ...revealOptionState[activeRevealPreset] };+ updateRevealOptionOutput(id);+ syncRevealOptionAvailability(activeRevealPreset);+ applyReveal();+ scheduleRevealUpdate();+ });+ }+ for (const button of revealPresetButtons) {+ button.addEventListener("click", () => {+ const name = button.dataset.revealPreset;+ activeRevealPreset = name;+ revealOptions = name === "instant"+ ? { ...REVEAL_PRESETS.instant }+ : { ...revealOptionState[name] };+ if (name !== "instant") syncRevealOptionControls(name);+ setActiveRevealPreset(name);+ applyReveal();+ commitRevealOptions();+ });+ }+ replayReveal.addEventListener("click", () => {+ circuit.triggerReveal();+ }); for (const button of animationPresetButtons) { button.addEventListener("click", () => { const name = button.dataset.animationPreset;@@ -539,7 +1105,9 @@ updateOutput("liveliness"); applyAtmosphere(animationOptions); setActiveAnimationPreset(name);- regenerate();+ window.clearTimeout(animationTimer);+ circuit.setAnimation(animationOptions);+ updateTraceCount(); }); } seed.addEventListener("change", regenerate);
src/playground.html+12−5@@ -3,7 +3,7 @@ <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" />-<title>Circuit Trace Generators — interactive playground</title>+<title>Circuit Trace Generators: interactive playground</title> <style> :root { color-scheme: dark; } * { box-sizing: border-box; }@@ -40,21 +40,28 @@ <div class="wrap"> <header> <h1>Circuit Trace Generators <span class="accent">·</span> interactive playground</h1>- <p>Both routers, live and embedded below. These are the real engines from this+ <p>Both routers and the tiling reveal, live and embedded below. These are the real engines from this page's <code>src/</code>, served by the wiki, so they need no container and stay up.</p> <p>Drag the sliders, switch presets, and move the pointer over each board.</p> </header> <section class="demo">- <h2>1 · Tiling router <span class="accent">·</span> seamless torus tile</h2>+ <h2>1 · Tiling router <span class="accent">·</span> repeating torus tile</h2> <p class="meta">Occupancy-grid A* router on a torus. Twelve generation knobs, a cursor-fed signal fountain, and five animation presets. Engine: <code>circuit-background.js</code>.</p> <iframe class="frame" src="./index-classic.html" title="Tiling router, live interactive demo" loading="lazy"></iframe> <p class="open">▶ <a href="./index-classic.html" target="_blank" rel="noopener">Open this demo full screen</a></p> </section> <section class="demo">- <h2>2 · Field router <span class="accent">·</span> continuous packed field</h2>- <p class="meta">Flow-field and vortex trace packing, sized to the mount. Five geometry presets and four animation systems (none, conductor, routed field, handshake). Entry: <code>circuit-background-v5.js</code>.</p>+ <h2>2 · Tiling reveal <span class="accent">·</span> progressive route growth</h2>+ <p class="meta">Etch, Flood, Sweep, Bloom, and Scatter grow the same torus tile before an exact static-SVG handoff. Entry: <code>circuit-background-reveal.js</code>.</p>+ <iframe class="frame" src="./index-reveal.html" title="Tiling reveal, live interactive demo" loading="lazy"></iframe>+ <p class="open">▶ <a href="./index-reveal.html" target="_blank" rel="noopener">Open this demo full screen</a></p>+ </section>++ <section class="demo">+ <h2>3 · Field router <span class="accent">·</span> continuous packed field</h2>+ <p class="meta">Version 9 adds obstacles, flow or scroll reveal, append-only generation, and five ambient systems. Entry: <code>circuit-background-v9.js</code>.</p> <iframe class="frame" src="./index.html" title="Field router, live interactive demo" loading="lazy"></iframe> <p class="open">▶ <a href="./index.html" target="_blank" rel="noopener">Open this demo full screen</a></p> </section>
src/serve-classic.mjs+8@@ -15,6 +15,14 @@ const files = new Map([ ["/", ["index-classic.html", "text/html; charset=utf-8"]], ["/index.html", ["index-classic.html", "text/html; charset=utf-8"]], ["/circuit-background.js", ["circuit-background.js", "text/javascript; charset=utf-8"]],+ // Reveal demo: same board, grown in instead of appearing whole. Kept on+ // its own page + engine copy so the classic demo above stays untouched.+ ["/reveal", ["index-reveal.html", "text/html; charset=utf-8"]],+ ["/reveal.html", ["index-reveal.html", "text/html; charset=utf-8"]],+ [+ "/circuit-background-reveal.js",+ ["circuit-background-reveal.js", "text/javascript; charset=utf-8"],+ ], ]); function headers(contentType) {
src/serve.sh+4−4@@ -3,10 +3,10 @@ set -u SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PORT="${CIRCUIT_PORT:-8124}"-LOG_FILE="/tmp/circuit-generator-serve.log"+LOG_FILE="/tmp/circuit-generator-codex-serve.log" if curl -fsS --max-time 2 "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then- echo "[circuit-generator] already running on port ${PORT}"+ echo "[circuit-generator-codex] already running on port ${PORT}" exit 0 fi @@ -16,11 +16,11 @@ SERVER_PID=$! for _ in 1 2 3 4 5; do if curl -fsS --max-time 2 "http://127.0.0.1:${PORT}/health" >/dev/null 2>&1; then- echo "[circuit-generator] started PID ${SERVER_PID} on port ${PORT}"+ echo "[circuit-generator-codex] started PID ${SERVER_PID} on port ${PORT}" exit 0 fi sleep 1 done -echo "[circuit-generator] failed to start; see ${LOG_FILE}" >&2+echo "[circuit-generator-codex] failed to start; see ${LOG_FILE}" >&2 exit 1
src/server.js+34−3@@ -8,11 +8,40 @@ const port = Number.parseInt(process.env.CIRCUIT_PORT || "8124", 10); const files = new Map([ ["/", ["index.html", "text/html; charset=utf-8"]], ["/index.html", ["index.html", "text/html; charset=utf-8"]],+ ["/v9", ["index-v9.html", "text/html; charset=utf-8"]],+ ["/index-v9.html", ["index-v9.html", "text/html; charset=utf-8"]],+ ["/v8", ["index-v8.html", "text/html; charset=utf-8"]],+ ["/index-v8.html", ["index-v8.html", "text/html; charset=utf-8"]],+ ["/v7", ["index-v7.html", "text/html; charset=utf-8"]],+ ["/index-v7.html", ["index-v7.html", "text/html; charset=utf-8"]],+ ["/v6", ["index-v6.html", "text/html; charset=utf-8"]],+ ["/index-v6.html", ["index-v6.html", "text/html; charset=utf-8"]], ["/circuit-animation-conductor.js", ["circuit-animation-conductor.js", "text/javascript; charset=utf-8"]], ["/circuit-animation-handshake.js", ["circuit-animation-handshake.js", "text/javascript; charset=utf-8"]],- ["/circuit-background.js", ["circuit-background.js", "text/javascript; charset=utf-8"]],+ ["/circuit-animation-growth.js", ["circuit-animation-growth.js", "text/javascript; charset=utf-8"]],+ ["/circuit-animation-reflection.js", ["circuit-animation-reflection.js", "text/javascript; charset=utf-8"]],+ ["/circuit-reveal-flow.js", ["circuit-reveal-flow.js", "text/javascript; charset=utf-8"]],+ ["/circuit-reveal-scroll.js", ["circuit-reveal-scroll.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-stream.js", ["circuit-field-stream.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-v8.js", ["circuit-field-hybrid-v8.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-client-v8.js", ["circuit-field-hybrid-client-v8.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-worker-v8.js", ["circuit-field-hybrid-worker-v8.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-v9.js", ["circuit-field-hybrid-v9.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-client-v9.js", ["circuit-field-hybrid-client-v9.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-hybrid-worker-v9.js", ["circuit-field-hybrid-worker-v9.js", "text/javascript; charset=utf-8"]],+ ["/circuit-trace-stager-v8.js", ["circuit-trace-stager-v8.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-stream-client.js", ["circuit-field-stream-client.js", "text/javascript; charset=utf-8"]],+ ["/circuit-field-stream-worker.js", ["circuit-field-stream-worker.js", "text/javascript; charset=utf-8"]],+ ["/circuit-reveal-stream.js", ["circuit-reveal-stream.js", "text/javascript; charset=utf-8"]],+ ["/circuit-reveal-stream-v8.js", ["circuit-reveal-stream-v8.js", "text/javascript; charset=utf-8"]], ["/circuit-background-v4.js", ["circuit-background-v4.js", "text/javascript; charset=utf-8"]], ["/circuit-background-v5.js", ["circuit-background-v5.js", "text/javascript; charset=utf-8"]],+ ["/circuit-background-v6.js", ["circuit-background-v6.js", "text/javascript; charset=utf-8"]],+ ["/circuit-background-v7.js", ["circuit-background-v7.js", "text/javascript; charset=utf-8"]],+ ["/circuit-background-v8.js", ["circuit-background-v8.js", "text/javascript; charset=utf-8"]],+ ["/circuit-background-v9.js", ["circuit-background-v9.js", "text/javascript; charset=utf-8"]],+ ["/circuit-geometry-v9.js", ["circuit-geometry-v9.js", "text/javascript; charset=utf-8"]],+ ["/circuit-obstacles-v9.js", ["circuit-obstacles-v9.js", "text/javascript; charset=utf-8"]], ["/circuit-background-v3.js", ["circuit-background-v3.js", "text/javascript; charset=utf-8"]], ["/circuit-background-v2.js", ["circuit-background-v2.js", "text/javascript; charset=utf-8"]], ]);@@ -32,7 +61,9 @@ const server = createServer((request, response) => { if (url.pathname === "/health") { response.writeHead(200, headers("application/json; charset=utf-8"));- response.end(JSON.stringify({ ok: true, service: "circuit-generator", uptime: process.uptime() }));+ response.end(+ JSON.stringify({ ok: true, service: "circuit-generator-codex", uptime: process.uptime() }),+ ); return; } @@ -55,5 +86,5 @@ const server = createServer((request, response) => { }); server.listen(port, "0.0.0.0", () => {- console.log(`[circuit-generator] listening on http://0.0.0.0:${port}`);+ console.log(`[circuit-generator-codex] listening on http://0.0.0.0:${port}`); });