Skip to content
TypeScript

pxl: pixel-art DSL with live viewer, packaged as an agent skill

crsolver77f0ee76d383
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..8d7dd3f
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,3 @@
+* text=auto eol=lf
+*.png binary
+*.gif binary
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..8a60e8c
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,25 @@
+name: CI
+on: [push, pull_request]
+jobs:
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ node: ["22.18", "24"]
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node }}
+ - run: npm ci
+ - run: npm run check
+ - run: node bin/pxl.js build examples/shop.px.js --no-preview
+ - name: Installed package runs
+ shell: bash
+ run: |
+ npm pack
+ mkdir ../smoke && cd ../smoke && npm init -y > /dev/null
+ npm install ../${{ github.event.repository.name }}/pxl-pixelart-*.tgz
+ npx pxl build node_modules/pxl-pixelart/examples/basics.px.js --no-preview
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f04f58d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+node_modules/
+out/
+dist/
+*.tgz
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..c1eff8d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 crsolver
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..50a333c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,141 @@
+# pxl
+
+**Pixel art as code.** Write a compact `.px.js` file; get PNGs, sprite sheets with JSON, animated
+GIFs, and a live browser viewer that replays the painting step by step as you save.
+
+Built for AI agents (it ships as a ready-made [agent skill](#use-it-with-an-ai-agent)) and pleasant
+for people too. No runtime dependencies, no build step: just Node ≥ 22.18.
+
+<p>
+ <img src="docs/gallery/comet_repair.png" width="49%" alt="Comet Repair shop scene">
+ <img src="docs/gallery/gull_and_gill.png" width="49%" alt="Gull &amp; Gill bait shop scene">
+ <img src="docs/gallery/moon_buns_3d.png" width="49%" alt="Moon Buns bakery scene">
+ <img src="docs/gallery/neon_noodle_3d.png" width="49%" alt="Neon noodle bar scene">
+</p>
+<p>
+ <img src="docs/gallery/cave.gif" width="49%" alt="Animated glowing cave">
+ <img src="docs/gallery/cat.gif" height="96" alt="Animated cat">
+ <img src="docs/gallery/frog.gif" height="96" alt="Animated frog">
+ <img src="docs/gallery/clock.gif" height="128" alt="Animated clock">
+</p>
+
+Every image above is generated from a file in [`examples/`](examples).
+
+## Quick start
+
+```sh
+git clone https://github.com/crsolver/claude-pxl.git
+cd claude-pxl
+node bin/pxl.js serve examples/shop.px.js # live viewer at http://127.0.0.1:4321/
+```
+
+Or run it without cloning:
+
+```sh
+npx github:crsolver/claude-pxl build art.px.js
+```
+
+Write `art.px.js`:
+
+```js
+pal({ k: "#1b1630", g: "#8ccf63", G: "#4c8a44", w: "#fff6e0", r: "#e2585e", R: "#a63a4c" })
+
+// Write the left half; mirror it and outline it automatically.
+sprite("slime", { mx: true, outline: "k" }, `
+ ....ggg
+ ..ggGGg
+ .ggGwGg
+ gggkwgg
+ GGGGGGG`)
+sprite("slime_red", { base: "slime", swap: { g: "r", G: "R" } }) // a recolor in one line
+
+sheet("chars", ["slime*"], { pad: 1 })
+```
+
+```sh
+node bin/pxl.js build art.px.js
+```
+
+```
+out/sprites/slime.png out/sprites/slime_red.png the art, at 1x
+out/chars.png out/chars.json sprite sheet + TexturePacker-style JSON
+out/_preview/*.png upscaled previews with a pixel grid
+```
+
+## The live viewer
+
+`pxl serve art.px.js` opens a viewer that rebuilds on every save and replays the asset you edited
+op by op, so you (or whoever is watching an agent work) can see the art being painted. It also
+writes the same `out/` files as `build`.
+
+## Commands
+
+```
+pxl build <art.px.js> [--out DIR] [--only a,b] [--scale N] [--no-preview]
+pxl serve <art.px.js> [--port 4321] [--out DIR | --no-out] [--no-preview]
+pxl ascii <art.px.js> <name> print an asset as palette keys with x/y rulers
+pxl list <art.px.js> list assets, groups and sheets with source locations
+```
+
+`pxl` means `node bin/pxl.js` in a clone, or `npx github:crsolver/claude-pxl`. Art files can be `.js` or
+`.ts` (`types/pxl.d.ts` gives editor completion).
+
+## What's in the DSL
+
+- **Palettes and ramps**: one-character color keys, built-in palettes (pico8, sweetie16, endesga32…),
+ dark→light ramps that drive `shade()` / `light()`.
+- **Sprites**: text grids, mirroring, auto-outline, palette-swap variants, flips/rotations, reusable
+ `_parts`, `stamp`.
+- **Primitives and brushes**: rects, lines, circles, polygons, gradients, dithering, noise, a built-in
+ pixel font, `scatter` brushes, tilemaps, random groups with reproducible seeds.
+- **Scenes**: layers, cast-shadow and light layers, per-layer PNG export.
+- **Animation**: frames as patches over a base sprite → strips + JSON tags + GIF.
+- **Lighting** (optional): lamps, glow, normal-based relief (see [`lighting.md`](lighting.md)).
+- **Errors** point at `file:line:col` and the asset/layer/op path, with "did you mean…" hints.
+
+Full API: [`reference.md`](reference.md). Agent workflow and essentials: [`SKILL.md`](SKILL.md).
+
+## Use it with an AI agent
+
+This repository is an agent skill: `SKILL.md` teaches the workflow (write → build → look at the
+preview → patch), `reference.md` holds the full API, and `lighting.md` is loaded only when needed.
+
+**Claude Code**: clone it into your skills folder, then ask Claude to draw something.
+
+```sh
+# all projects
+git clone https://github.com/crsolver/claude-pxl.git ~/.claude/skills/pxl-pixel-art
+# or just one project
+git clone https://github.com/crsolver/claude-pxl.git .claude/skills/pxl-pixel-art
+```
+
+**Other agents** (Codex, Cursor, …): point them at `SKILL.md` and tell them the CLI is
+`node <path to pxl>/bin/pxl.js`.
+
+Tip: ask the agent to start `pxl serve` so you can watch it paint in your browser.
+
+## Development
+
+```sh
+npm install # dev only: typescript, @types/node
+npm run check # type check + tests
+node scripts/gallery.ts # regenerate docs/gallery
+```
+
+```
+src/core/ engine, no Node APIs: image, palette + ramps, canvas ops, build, trace, project
+src/node/ vm sandbox loader, PNG/GIF encoders, outputs, CLI, live server
+src/viewer/ browser viewer (served type-stripped; no bundler)
+types/ pxl.d.ts globals for editor support in .px.ts files
+scripts/ build.js (dist/ for npm installs), gallery.ts
+examples/ example art files
+test/ node:test suites
+```
+
+In a clone the CLI runs the TypeScript sources directly. When installed as a package it runs
+`dist/`, which `npm install` / `npm pack` generate via `scripts/build.js` (Node won't strip types
+inside `node_modules`).
+
+## License
+
+[MIT](LICENSE)
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..3a0dcdb
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,105 @@
+---
+name: pxl-pixel-art
+description: Create pixel art (game sprites, characters, items, tiles, tilesets, icons, scenes, sprite sheets) with pxl, a compact JavaScript DSL that renders PNGs and lets the user watch the painting live in a browser. Use when asked to draw, design or iterate on pixel art or game assets.
+---
+
+# pxl: pixel art as code
+
+You write a small `.px.js` file; pxl renders PNGs and upscaled previews you can look at. The DSL
+is built to avoid writing pixels twice: mirroring, auto-outline, palette-swap variants, reusable
+parts, primitives, brushes and tilemaps. Needs Node ≥ 22.18. No install step.
+
+`PXL` below means `node <this skill's directory>/bin/pxl.js`.
+
+## Workflow
+
+1. Write `art.px.js` (start from the template below; examples in `examples/`).
+2. Build only what you're working on: `PXL build art.px.js --only slime,heart`
+3. **Look at it**: read `out/_preview/<name>.png` (upscaled, checkerboard = transparent, grid every
+ pixel, darker every 8). For exact pixel fixes use `PXL ascii art.px.js <name>` (keys + x/y rulers);
+ it's cheaper than an image.
+4. Fix with small edits (a `grid(x, y, ...)` patch, one op) and rebuild. Repeat.
+5. If the user wants to watch: start `PXL serve art.px.js` in the background and give them the URL.
+ It rebuilds on every save and replays the edited asset's painting steps; it also writes the same
+ `out/` files, so keep reading previews as usual.
+
+Errors name the file:line:col, the asset/layer/op path, and suggest fixes ("did you mean 'r'?").
+One broken asset doesn't stop the others from building.
+
+## Template
+
+```js
+pal({ k: "#1b1630", g: "#8ccf63", G: "#4c8a44", t: "#2a5560", w: "#fff6e0", r: "#e2585e", R: "#a63a4c" })
+ramps("ktGg", "kRr") // dark -> light, drives shade()/light()
+
+// Symmetric: write the left half, mirror it, outline it.
+sprite("slime", { mx: true, outline: "k" }, `
+ ....ggg
+ ..ggGGg
+ .ggGwGg
+ gggkwgg
+ gggkkgg
+ tgggggg
+ .tttttt`)
+sprite("slime_red", { base: "slime", swap: { g: "r", G: "R" } }) // variant: 1 line
+
+sprite("_eye", "wk\nkk") // "_" = part, not exported
+sprite("chest", { w: 16, h: 12, outline: "k" },
+ rect(0, 3, 16, 9, "R"), rect(0, 0, 16, 4, "r"), stamp("_eye", 7, 4), shade([0, 9, 16, 3]))
+
+scene("meadow", { w: 160, h: 96, bg: "w" },
+ layer("ground", { y: 64 }, rect(0, 0, 160, 32, "G"), noise(0, 0, 160, 32, "g", 0.1, 3)),
+ layer("props", stamp("slime", 40, 54), stamp("slime_red", 70, 54, { flip: "x" })),
+ layer("shadow", { shade: true }, poly([38, 64, 88, 64, 92, 67, 34, 67], "k"))) // cast shadow
+
+sheet("chars", ["slime*", "chest"], { pad: 1 })
+```
+
+## Essentials
+
+- **Colors**: one-char keys from `pal`, `"#hex"`, `"."` skip, `"_"` erase. Default palette is pico8
+ (`0-f`); `use("sweetie16" | "db16" | "endesga32" | "gray8")` for others.
+- **Items run in order**: grid strings (drawn at 0,0), ops, `(c) => { c.rect(...) }` functions,
+ `layer(...)`s. Then mirror → swap → flip → rot → outline (grows 1px each side) → crop.
+- **Shapes**: `px rect box line(…, width) hline vline circ ring ellipse poly fill wire text`.
+- **Tone**: `dither grad noise`, `shade/light(region, steps, density)`, `recolor`, and
+ `shade:`/`light:` layers for cast shadows and glows. Regions: `[cx,cy,r]`, `[x,y,w,h]`,
+ polygon, or a function. `clip(region, ...items)` restricts any items (half shapes, slopes).
+- **Reuse**: `stamp tile pattern tilemap scatter`. Names can be groups or globs
+ (`group("rocks", ["rock_a", "rock_a", "rock_b"])`, `"tree_*"`). Each placement picks randomly but
+ reproducibly. Use `rflip`, `rswap`, `seed`, and `reseed: true` for per-copy variety.
+- **Brushes**: `scatter("_leaf*", x, y, w, h, 30, { on: "g", clip: true, rflip: "xy" })` paints
+ texture with tiny part sprites, only on the given colors.
+- **Animation**: `anim("cat", { outline: "k", fps: 10 }, grid, frame(), frame(grid(23, 0, "_K")))`:
+ frames are patches over shared items or a `base`; or `frames: 6` + `(c) => ... c.phase ...` for
+ procedural loops. Stamping an anim animates the scene (`rdelay: true` desyncs copies, `frame: n`
+ freezes one). Check `_preview/<name>.png` (all frames side by side) or `pxl ascii` per frame.
+- **Glow**: `glow("zgQ", { r: 6, strength: 0.5 })` directly in a sprite/scene body gives every pixel
+ of those keys a halo (flames, potions, moons, neon); `ramp: 2` instead stays in the palette.
+ Give glowing things their own keys so nothing else lights up, or limit it with `where`.
+
+Full API with every option: [reference.md](reference.md).
+Dynamic lighting (lamps, light blocked by solid layers, sky light, Terraria-style): read
+[lighting.md](lighting.md) only when a scene needs lights.
+
+## Habits that save tokens and give better art
+
+- Write half of anything symmetric (`mx`) and let `outline` draw outlines. Never hand-draw either.
+- Recolors are `base` + `swap`; repeated details are `_parts` + `stamp`; families are a `group` or a
+ loop: `for (let i = 1; i <= 3; i++) sprite("tree_" + i, ...)`.
+- Large areas: primitives, `grad`, `noise`, `pattern`, `tilemap`. Never big hand grids.
+- Organic texture (leaves, grass, stones, rust): 2–3 tiny brush parts + `scatter` with `on`/`clip`.
+- **No filler noise.** Don't sprinkle `noise` speckle over walls, floors or plaster to make them
+ "less flat": it reads as random dots, not material. Every mark on a surface needs a cause you
+ could name, and it should sit where that cause would put it:
+ - built structure: siding/plank lines, brick or stone courses with offset joints, tile seams;
+ - weathering: rain-stain streaks under ledges and sills, splash-back grime fading up from the
+ ground, rust runs under metal brackets, paint flaking off boards (following the board lines);
+ - clutter that tells the story: posters, pipes, vents, cracks from a corner.
+ Flat color is fine; a clean wall beats a dotted one. `noise` is OK only where the material itself
+ is granular (gravel, sand, asphalt, tar roofs, rough stone), and keep it sparse. On faces drawn
+ at an angle (3/4 views), make the marks follow the face's slant.
+- Lighting: define `ramps`, then `light`/`shade` regions; stack a `density: 0.5` pass for soft edges.
+ Use `shade: true` layers with a `poly` for cast shadows across many objects.
+- Use mnemonic keys (`g`/`G` light/dark green). Keep 2–4 shades per material for a clean pixel-art look.
+- Build with `--only` while iterating; a full build also writes every preview.
diff --git a/bin/pxl.js b/bin/pxl.js
new file mode 100644
index 0000000..2fe0b2f
--- /dev/null
+++ b/bin/pxl.js
@@ -0,0 +1,18 @@
+#!/usr/bin/env node
+// Entry point. In a checkout it runs the TypeScript sources directly (Node >= 22.18 strips types);
+// installed under node_modules, where Node refuses to strip types, it runs the dist/ build.
+// Hide Node's experimental warnings about type stripping so agent output stays clean.
+process.removeAllListeners("warning");
+process.on("warning", (w) => {
+ if (w.name !== "ExperimentalWarning") console.warn(w);
+});
+
+const [major, minor] = process.versions.node.split(".").map(Number);
+if (major < 22 || (major === 22 && minor < 18)) {
+ console.error(`pxl needs Node >= 22.18 (found ${process.versions.node})`);
+ process.exit(2);
+}
+
+const installed = /\/node_modules\//.test(decodeURIComponent(import.meta.url));
+const { main } = await import(installed ? "../dist/node/cli.js" : "../src/node/cli.ts");
+process.exitCode = await main(process.argv.slice(2));
diff --git a/docs/gallery/cat.gif b/docs/gallery/cat.gif
new file mode 100644
index 0000000..7fccee1
Binary files /dev/null and b/docs/gallery/cat.gif differ
diff --git a/docs/gallery/cave.gif b/docs/gallery/cave.gif
new file mode 100644
index 0000000..918459c
Binary files /dev/null and b/docs/gallery/cave.gif differ
diff --git a/docs/gallery/clock.gif b/docs/gallery/clock.gif
new file mode 100644
index 0000000..6879a92
Binary files /dev/null and b/docs/gallery/clock.gif differ
diff --git a/docs/gallery/comet_repair.png b/docs/gallery/comet_repair.png
new file mode 100644
index 0000000..6dea9e9
Binary files /dev/null and b/docs/gallery/comet_repair.png differ
diff --git a/docs/gallery/frog.gif b/docs/gallery/frog.gif
new file mode 100644
index 0000000..5c1d2f9
Binary files /dev/null and b/docs/gallery/frog.gif differ
diff --git a/docs/gallery/gull_and_gill.png b/docs/gallery/gull_and_gill.png
new file mode 100644
index 0000000..4d1b666
Binary files /dev/null and b/docs/gallery/gull_and_gill.png differ
diff --git a/docs/gallery/moon_buns_3d.png b/docs/gallery/moon_buns_3d.png
new file mode 100644
index 0000000..70eeaad
Binary files /dev/null and b/docs/gallery/moon_buns_3d.png differ
diff --git a/docs/gallery/neon_noodle_3d.png b/docs/gallery/neon_noodle_3d.png
new file mode 100644
index 0000000..22f26d5
Binary files /dev/null and b/docs/gallery/neon_noodle_3d.png differ
diff --git a/examples/basics.px.js b/examples/basics.px.js
new file mode 100644
index 0000000..2e88c6b
--- /dev/null
+++ b/examples/basics.px.js
@@ -0,0 +1,54 @@
+// Basics: palette, mirrored + outlined sprites, variants, parts, primitives, sheets.
+use("sweetie16")
+pal({ k: 0, p: 1, r: 2, o: 3, y: 4, G: 5, g: 6, t: 7, n: 8, b: 9, B: 10, c: 11, w: 12, l: 13, s: 14, d: 15 })
+ramps("ktgG", "kproy", "knbBc", "kdslw")
+
+// Draw the left half; mx mirrors it, outline wraps it.
+sprite("slime", { mx: true, outline: "k" }, `
+ ....ggg
+ ..ggGGg
+ .ggGwGg
+ .gggggg
+ gggkwgg
+ gggkkgg
+ tgggggg
+ .tttttt`)
+
+sprite("slime_red", { base: "slime", swap: { g: "r", G: "o", t: "p" } })
+sprite("slime_blue", { base: "slime", swap: { g: "b", G: "B", t: "n" } })
+sprite("slime_wink", { base: "slime" }, grid(10, 5, `
+ gg
+ kk`))
+
+// Odd width: the center column is shared.
+sprite("heart", { mx: "c", outline: "k" }, `
+ .rr.
+ rwrr
+ rrrr
+ rrrr
+ .rrr
+ ..rr
+ ...r`)
+
+sprite("coin", { w: 10, h: 10 },
+ circ(4, 4, 4, "o"), circ(4, 4, 3, "y"), vline(4, 2, 5, "o"), px(3, 2, "w"))
+
+sprite("_lock", `
+ yy
+ yo`)
+sprite("chest", { w: 16, h: 12, outline: "k" },
+ rect(0, 3, 16, 9, "o"), rect(0, 0, 16, 4, "r"), hline(0, 4, 16, "p"),
+ vline(3, 0, 12, "y"), vline(12, 0, 12, "y"), stamp("_lock", 7, 4),
+ shade([0, 9, 16, 3]))
+
+// A dome: clip() cuts the ellipse to its top half.
+sprite("dome", { w: 21, h: 11, outline: "k" },
+ clip([0, 0, 21, 11], ellipse(10, 10, 10, 10, "b")),
+ light([6, 4, 4], 1, 0.5), light([5, 3, 2]))
+
+// Custom drawing code: loops get the canvas.
+sprite("stripes", { w: 8, h: 8 }, (c) => {
+ for (let i = 0; i < 8; i += 2) c.hline(0, i, 8, i % 4 ? "B" : "b")
+})
+
+sheet("chars", ["slime*", "heart", "coin", "chest"], { cols: 4, pad: 1 })
diff --git a/examples/cave.px.js b/examples/cave.px.js
new file mode 100644
index 0000000..4b61828
--- /dev/null
+++ b/examples/cave.px.js
@@ -0,0 +1,139 @@
+// Glow cave: a dark cavern lit only by pulsing fungus, glowworm threads and drifting lightbugs.
+// The rock is normal-mapped (domed cobbles on the back wall, bevelled rock, lumps), so the moving
+// bugs rake light across the relief.
+pal({
+ k: "#07060c", K: "#2a2538", r: "#4a4262", R: "#6e6488", q: "#a294c4", // rock at "daylight" brightness: lighting supplies the dark
+ c: "#3fd8c8", C: "#b4fff2", e: "#1c7f8c", // cyan fungus
+ m: "#e05ad0", M: "#ffb0f4", E: "#8a2a8a", // magenta fungus
+ f: "#9aa6c2", F: "#6a7390", // stems
+ y: "#9ccf3a", Y: "#f4ffb0", // lightbugs
+ s: "#4a5878", b: "#8fd0ff", w: "#8aa0c0", // silk, glowworm bead, water
+})
+
+const W = 192, H = 108, FRAMES = 24, TAU = Math.PI * 2;
+
+// Rock outlines as polylines, so props can sit exactly on them.
+const ceil = [0, 12, 12, 16, 30, 10, 48, 18, 70, 12, 90, 22, 110, 14, 128, 20, 150, 12, 170, 18, 192, 14];
+const floor = [0, 84, 18, 80, 40, 86, 64, 82, 84, 88, 110, 84, 132, 90, 150, 82, 172, 78, 192, 82];
+const edgeY = (pts, x) => {
+ for (let i = 0; i < pts.length - 2; i += 2)
+ if (x <= pts[i + 2]) return Math.round(pts[i + 1] + (pts[i + 3] - pts[i + 1]) * (x - pts[i]) / (pts[i + 2] - pts[i]));
+ return pts[pts.length - 1];
+};
+
+// ------------------------------------------------------------------ rock parts (normal-mapped)
+for (const [i, rx, ry] of [[1, 3, 2], [2, 4, 3], [3, 5, 3], [4, 6, 4]])
+ sprite("_stone" + i, { w: 2 * rx + 1, h: 2 * ry + 1, outline: "K" }, ellipse(rx, ry, rx, ry, "r"), bump("dome"))
+for (const [i, rx, ry] of [[1, 4, 2], [2, 6, 3], [3, 3, 2]])
+ sprite("_lump" + i, { w: 2 * rx + 1, h: 2 * ry + 1, outline: "r" }, ellipse(rx, ry, rx, ry, "R"), bump("dome", { depth: 0.8 }))
+
+// ------------------------------------------------------------------ fungus
+sprite("_cap_big", { mx: "c" }, `
+ ..cC
+ .cCC
+ cCcC
+ eeee
+ ...f
+ ...F
+ ...f`)
+sprite("_cap_mid", { mx: "c" }, `
+ .cC
+ cCC
+ eee
+ ..f
+ ..F`)
+sprite("_cap_tiny", ".C.\nccc\n.f.")
+// Shelf fungus growing out of a rock face (pointing right).
+sprite("_bracket", "cCc.\ncccC\n.eee")
+
+// Clusters pulse: the lamp breathes and the bright spots fade at the dim end of the cycle.
+const clusters = {
+ a: [["_cap_big", 4, 1], ["_cap_mid", 0, 3], ["_cap_tiny", 11, 5], 7, 2],
+ b: [["_cap_mid", 0, 3], ["_cap_tiny", 5, 5], ["_cap_mid", 8, 2], 10, 3],
+};
+for (const [id, [p1, p2, p3, lx, ly]] of Object.entries(clusters))
+ for (const [tint, swap, light] of [["c", {}, "#5cf0e0"], ["m", { c: "m", C: "M", e: "E" }, "#ff7ae8"]])
+ anim(`fungus_${id}_${tint}`, { w: 14, h: 8, frames: FRAMES, fps: 8 },
+ ...[p1, p2, p3].map(([n, x, y]) => stamp(n, x, y, { swap })),
+ (c) => {
+ const k = Math.sin(c.phase * TAU);
+ if (k < -0.4) c.recolor(tint === "c" ? { C: "c" } : { M: "m" });
+ c.lamp(lx, ly, { r: 30 + 4 * k, color: light, power: 0.85 + 0.2 * k, z: 6 });
+ })
+
+// ------------------------------------------------------------------ the cave
+const stalactites = [[56, 14, 4], [76, 22, 5], [100, 10, 3], [120, 16, 4], [138, 9, 3], [182, 12, 4]];
+const stalagmites = [[70, 10, 4], [118, 7, 3], [10, 8, 3]];
+const fungi = [["fungus_a_c", 44], ["fungus_b_c", 90], ["fungus_a_m", 124], ["fungus_b_m", 60]];
+// Glowworm colonies: thread [x, length]s plus one lamp each.
+const glowworms = [
+ [[50, 6], [54, 11], [61, 7], [65, 4]],
+ [[98, 8], [104, 13], [108, 6], [113, 11]],
+ [[131, 7], [135, 12], [140, 5]],
+ [[160, 6], [165, 10], [171, 5], [176, 8]],
+];
+// Lightbugs: closed Lissajous loops (integer frequencies), so the animation repeats seamlessly.
+const bugs = [
+ [70, 50, 18, 8, 1, 2, 0.0], [110, 44, 22, 10, 1, 1, 0.3], [150, 40, 12, 9, 2, 1, 0.6],
+ [40, 56, 10, 12, 1, 2, 0.5], [88, 64, 16, 6, 2, 1, 0.8], [168, 50, 10, 6, 1, 1, 0.15],
+];
+const bugAt = ([cx, cy, ax, ay, fx, fy, p], t) =>
+ [Math.round(cx + ax * Math.sin((fx * t + p) * TAU)), Math.round(cy + ay * Math.sin((fy * t + p * 2) * TAU) + 1.5 * Math.sin((3 * t + p) * TAU))];
+
+anim("cave", { w: W, h: H, frames: FRAMES, fps: 8 },
+ // Back wall: domed cobbles, invisible in the dark, picked out by passing lights.
+ layer("backwall", { wall: true }, rect(0, 0, W, H, "K"),
+ scatter("_stone*", -6, -6, W + 12, H + 12, 260, { rflip: "xy", rswap: [{}, {}, { r: "R" }], seed: 4 })),
+
+ layer("rock", { solid: true },
+ poly([0, 0, ...ceil, W, 0], "R"),
+ poly([0, H, ...floor, W, H], "R"),
+ poly([146, 84, 150, 66, 156, 62, 186, 62, 192, 63, 192, 84], "R"), // right ledge
+ poly([22, 12, 38, 12, 34, 40, 32, 56, 36, 82, 20, 82, 25, 56, 24, 40], "R"), // column
+ ...stalactites.map(([x, len, w]) => poly([x - w, edgeY(ceil, x) - 2, x + w, edgeY(ceil, x) - 2, x, edgeY(ceil, x) + len], "R")),
+ ...stalagmites.map(([x, len, w]) => poly([x - w, edgeY(floor, x) + 2, x + w, edgeY(floor, x) + 2, x, edgeY(floor, x) - len], "R")),
+ // Upward-facing edges get a lighter lip so the floor reads where props stand on it.
+ (c) => { for (let y = 1; y < H; y++) for (let x = 0; x < W; x++) if (c.is(x, y, "R") && c.is(x, y - 1, ".")) c.px(x, y, "q"); },
+ bump("bevel", { w: 3 }),
+ scatter("_lump*", 0, 0, W, H, 70, { on: "R", clip: true, rflip: "xy", seed: 2 })),
+
+ layer("life",
+ ...fungi.map(([n, x]) => stamp(n, x, edgeY(floor, x + 7) - 7, { rdelay: true })),
+ stamp("fungus_a_c", 162, 55, { rdelay: true }), stamp("fungus_b_m", 174, 55, { rdelay: true, flip: "x" }),
+ (c) => {
+ // Glowworm threads: silk from the ceiling, a glowing bead at the end; one lamp per colony.
+ for (const colony of glowworms) {
+ for (const [x, len] of colony) {
+ const top = edgeY(ceil, x);
+ c.vline(x, top, len, "s");
+ c.px(x, top + len, (c.frame + x) % 7 === 0 ? "C" : "b"); // beads twinkle in turn
+ }
+ const mx = Math.round(colony.reduce((a, [x]) => a + x, 0) / colony.length);
+ c.lamp(mx, edgeY(ceil, mx) + 9, { r: 28, color: "#7ab8ff", power: 0.65, z: 10 });
+ }
+ // Bracket fungus on the column, with a soft cyan lamp.
+ c.stamp("_bracket", 33, 44); c.stamp("_bracket", 32, 61);
+ c.lamp(36, 52, { r: 24, color: "#5cf0e0", power: 0.6 + 0.15 * Math.sin(c.phase * TAU * 2), z: 5 });
+
+ // A drop falls from the long stalactite and splashes.
+ const tip = edgeY(ceil, 76) + 22, ground = edgeY(floor, 76) - 1, f = c.frame;
+ const y = tip + 1 + Math.round(0.35 * f * f);
+ if (y < ground) c.vline(76, y, f > 3 ? 2 : 1, "w");
+ else if (y < ground + 14) c.grid(74, ground - 1, f % 2 ? "w...w" : ".w.w.");
+ }),
+
+ // Lightbugs with a fading trail, each carrying a small lamp that flickers.
+ (c) => {
+ bugs.forEach((b, i) => {
+ const [x, y] = bugAt(b, c.phase), [px, py] = bugAt(b, c.phase - 1 / FRAMES);
+ if (px !== x || py !== y) c.px(px, py, "y");
+ c.px(x, y, "Y");
+ const flick = 0.75 + 0.25 * Math.sin((5 * c.phase + i * 0.37) * TAU);
+ c.lamp(x, y, { r: 14, color: "#e4ffb0", power: flick, z: 4 });
+ });
+ },
+
+ lighting({ cell: 2, smooth: true, ambient: 0.08, ambientColor: "#6050a0", block: 0.45, emit: "cCemMEyYb" }),
+ glow("cCmM", { r: 6, strength: 0.35 }),
+ glow("Y", { r: 4, strength: 0.6 }),
+ glow("b", { r: 3, strength: 0.4 }))
diff --git a/examples/grotto.px.js b/examples/grotto.px.js
new file mode 100644
index 0000000..b684bd4
--- /dev/null
+++ b/examples/grotto.px.js
@@ -0,0 +1,308 @@
+// Living grotto: a big cavern with a pool and a waterfall, overgrown with glowing moss, ferns,
+// hanging vines, bellflowers, mushrooms of four species and crystals. Lightbugs, moths, a snail
+// and glowing fish move through it, spores drift up, and the pool reflects it all. Everything
+// is lit by the life in it. Rock, cobbles and crystals are normal-mapped, so moving lights rake
+// across them.
+pal({
+ k: "#07060c", K: "#2a2538", r: "#4a4262", R: "#6e6488", q: "#a294c4", // rock ("daylight" albedo)
+ c: "#3fd8c8", C: "#b4fff2", e: "#1c7f8c", // cyan fungus
+ m: "#e05ad0", M: "#ffb0f4", E: "#8a2a8a", // magenta fungus
+ t: "#38e0a0", T: "#c0ffe0", n: "#1a8a5a", // glow moss / green fungus
+ u: "#5aa0ff", U: "#d8ecff", j: "#2a5aa0", // lantern mushrooms
+ f: "#b4bcd4", F: "#7a84a4", // stems
+ g: "#4f8a50", G: "#7ab868", l: "#3a7a5a", L: "#62a878", v: "#5a8a52", // grass, ferns, vines
+ o: "#ffb050", O: "#fff0b8", // berries, fish
+ z: "#a070ff", Z: "#e8d8ff", // bellflowers
+ x: "#8a6ad0", X: "#e0d4ff", // crystals
+ y: "#9ccf3a", Y: "#f4ffb0", // lightbugs
+ p: "#d8ccf0", P: "#6a5a8a", // moths
+ a: "#ff9a3a", A: "#ffe0a0", h: "#a89a88", // snail
+ w: "#4a7aa8", W: "#a8d8ff", // water
+ s: "#a8fff0", i: "#6a7898", b: "#8fd0ff", // spores, silk, glowworm beads
+})
+
+const W = 320, H = 180, FRAMES = 32, FPS = 8, TAU = Math.PI * 2;
+const loop = { frames: FRAMES, fps: FPS };
+const wave = (c, n = 1, off = 0) => Math.sin((c.phase * n + off) * TAU); // seamless over the loop
+
+// ------------------------------------------------------------------ terrain outlines
+const ceil = [0, 20, 20, 28, 44, 18, 70, 30, 96, 22, 120, 36, 146, 24, 170, 32, 196, 20, 222, 30, 250, 22, 276, 34, 300, 24, 320, 30];
+const floor = [0, 118, 24, 114, 52, 120, 76, 116, 100, 128, 112, 146, 120, 162, 136, 172, 180, 175, 200, 168, 214, 146, 228, 130, 246, 122, 268, 126, 290, 116, 320, 112];
+const ledgeTop = [236, 74, 300, 70, 320, 72], ledgeUnder = [244, 84, 270, 90, 300, 86, 320, 84];
+const POOL = 150; // water surface row
+const edgeY = (pts, x) => {
+ for (let i = 0; i < pts.length - 2; i += 2)
+ if (x <= pts[i + 2]) return Math.round(pts[i + 1] + (pts[i + 3] - pts[i + 1]) * (x - pts[i]) / (pts[i + 2] - pts[i]));
+ return pts[pts.length - 1];
+};
+const ground = (x) => edgeY(floor, x), ledge = (x) => edgeY(ledgeTop, x);
+const inPool = (x, y) => y >= POOL && y < ground(x) && x > 100 && x < 220;
+
+// ------------------------------------------------------------------ rock parts (normal-mapped)
+[[3, 2], [4, 3], [5, 3], [6, 4], [7, 4], [4, 2]].forEach(([rx, ry], i) =>
+ sprite("_stone" + i, { w: 2 * rx + 1, h: 2 * ry + 1, outline: "K" }, ellipse(rx, ry, rx, ry, "r"), bump("dome")));
+[[4, 2], [6, 3], [3, 2], [8, 3]].forEach(([rx, ry], i) =>
+ sprite("_lump" + i, { w: 2 * rx + 1, h: 2 * ry + 1, outline: "r" }, ellipse(rx, ry, rx, ry, "R"), bump("dome", { depth: 0.8 })));
+
+// Crystal shards: hand-painted facets (left face 4, front 5, right face 6, tip 8).
+const shard = (h) => [".X.", ...Array(h - 1).fill("xXx")].join("\n");
+const shardN = (h) => [".8.", "7" + "8" + "9", ...Array(h - 2).fill("456")].join("\n");
+for (const h of [5, 8, 11]) sprite("_shard" + h, shard(h), normals(0, 0, shardN(h)));
+sprite("crystals", { w: 12, h: 12 },
+ stamp("_shard5", 0, 7), stamp("_shard11", 3, 1), stamp("_shard8", 6, 4), stamp("_shard5", 9, 7),
+ lamp(5, 6, { r: 34, color: "#b090ff", power: 0.55, z: 8 }))
+
+// ------------------------------------------------------------------ vegetation parts
+sprite("_moss0", ".t.\ntTt"); sprite("_moss1", "t.tt\nTttT"); sprite("_moss2", "..t..\nttTtt");
+sprite("_tuft0", "g..g\n.gG."); sprite("_tuft1", ".G.\ngGg"); sprite("_tuft2", "g.G.g\n.ggg.");
+sprite("_bracket", "cCc.\ncccC\n.eee");
+
+// Mushroom caps from the first cave, reused for clusters in three colours.
+sprite("_cap_big", { mx: "c" }, "..cC\n.cCC\ncCcC\neeee\n...f\n...F\n...f");
+sprite("_cap_mid", { mx: "c" }, ".cC\ncCC\neee\n..f\n..F");
+sprite("_cap_tiny", ".C.\nccc\n.f.");
+const tints = { c: [{}, "#5cf0e0"], m: [{ c: "m", C: "M", e: "E" }, "#ff7ae8"], t: [{ c: "t", C: "T", e: "n" }, "#60ffb0"] };
+const shapes = {
+ a: [["_cap_big", 4, 1], ["_cap_mid", 0, 3], ["_cap_tiny", 11, 5], 7, 2],
+ b: [["_cap_mid", 0, 3], ["_cap_tiny", 5, 5], ["_cap_mid", 8, 2], 10, 3],
+};
+for (const [id, [p1, p2, p3, lx, ly]] of Object.entries(shapes))
+ for (const [tint, [swap, light]] of Object.entries(tints))
+ anim(`fungus_${id}_${tint}`, { w: 14, h: 8, ...loop },
+ ...[p1, p2, p3].map(([n, x, y]) => stamp(n, x, y, { swap })),
+ (c) => {
+ const k = wave(c);
+ if (k < -0.4) c.recolor({ C: "c", M: "m", T: "t" }); // spots fade at the dim end
+ c.lamp(lx, ly, { r: 30 + 4 * k, color: light, power: 0.85 + 0.2 * k, z: 6 });
+ });
+
+// Tall lantern mushrooms: the stem bends a little, the cap breathes.
+for (const h of [12, 16, 22])
+ anim("lantern" + h, { w: 9, h, ...loop }, (c) => {
+ const s = Math.round(wave(c) * 1.2), k = wave(c, 1, 0.3);
+ c.line(4, h - 1, 4 + s, 4, "f");
+ c.vline(4, h - 3, 3, "F");
+ c.grid(1 + s, 0, "..uUu..\n.uUuuu.\nuuuUuuu\njjjjjjj");
+ if (k > 0.5) c.recolor({ u: "U" }, [1 + s, 0, 7, 2]);
+ c.lamp(4 + s, 2, { r: 42 + 6 * k, color: "#7ab0ff", power: 0.85 + 0.15 * k, z: 8 });
+ });
+
+// Ferns sway; the further up the frond, the more it moves.
+anim("fern", { w: 11, h: 10, ...loop }, (c) => {
+ const sway = wave(c) * 1.6;
+ for (let i = 0; i <= 8; i++) {
+ const y = 9 - i, x = 5 + Math.round(sway * (i / 8) ** 2);
+ c.px(x, y, "l");
+ if (i >= 2 && i % 2 === 0)
+ for (let k = 1; k <= Math.max(1, 4 - i / 3); k++) {
+ c.px(x - k, y - Math.floor(k / 2), k === 1 ? "l" : "L");
+ c.px(x + k, y - Math.floor(k / 2), k === 1 ? "l" : "L");
+ }
+ }
+});
+
+// Bellflowers: a curled stem with a glowing bell that slowly pulses.
+anim("bell", { w: 6, h: 9, ...loop }, (c) => {
+ c.vline(1, 2, 7, "l"); c.px(2, 1, "l"); c.px(3, 1, "l"); c.px(0, 6, "L"); c.px(2, 5, "L");
+ c.grid(3, 2, wave(c, 2) > 0 ? "ZZz\nz.z" : "zZz\nz.z");
+});
+
+// Hanging vines: swing more toward the tip; berries glow, the last one carries a lamp.
+for (const len of [14, 20, 26, 34])
+ anim("vine" + len, { w: 9, h: len + 2, ...loop }, (c) => {
+ let x = 4;
+ for (let y = 0; y <= len; y++) {
+ x = 4 + Math.round(Math.sin(c.phase * TAU + y * 0.22) * 2 * (y / len));
+ c.px(x, y, "v");
+ if (y % 3 === 1) c.px(x + (y % 6 === 1 ? 1 : -1), y, y % 12 === 7 ? "t" : "L");
+ if (y > 4 && y % 9 === 5) c.px(x - 1, y, "o");
+ }
+ c.grid(x - 1, len, "oOo\n.o.");
+ c.lamp(x, len + 1, { r: 24, color: "#ffb060", power: 0.6 + 0.1 * wave(c, 2), z: 6 });
+ });
+
+// The centrepiece: a giant lantern mushroom. Thick curved stem, a wide spotted cap that sways
+// slowly, glowing gills and a big soft lamp.
+anim("giant", { w: 35, h: 56, ...loop }, (c) => {
+ const s = wave(c) * 1.5, k = wave(c, 1, 0.25);
+ for (let y = 10; y < 56; y++) {
+ const t = (56 - y) / 46, x = Math.round(17 + s * t * t + 3 * Math.sin(t * 2.2));
+ const fw = y > 49 ? 2 + Math.floor((y - 49) / 2) : 0; // flared foot
+ c.hline(x - 2 - fw, y, 5 + 2 * fw, "f"); c.hline(x + 1 + fw, y, 2, "F");
+ if (y % 7 === 3) c.px(x - 1, y, "F"); // stem fibres
+ }
+ const cx = Math.round(17 + s + 3 * Math.sin(2.2));
+ c.ellipse(cx, 8, 16, 7, "u"); c.rect(0, 9, 35, 7, "_");
+ c.hline(cx - 15, 9, 31, "j"); c.hline(cx - 13, 10, 27, "j");
+ for (const [dx, dy] of [[-9, 4], [-3, 2], [4, 3], [10, 5], [-6, 7], [7, 7], [0, 6]]) c.px(cx + dx, dy, "U");
+ if (k > 0.3) c.recolor({ u: "U" }, [cx - 6, 1, 12, 3]);
+ for (let i = 0; i < 4; i++) { // glowing drips under the cap
+ const d = Math.round(((c.phase * 2 + i * 0.25) % 1) * 14);
+ if (d < 12) c.px(cx - 12 + i * 8, 11 + d, d < 6 ? "U" : "u");
+ }
+ c.lamp(cx, 9, { r: 86 + 8 * k, color: "#86bcff", power: 1 + 0.12 * k, z: 14 });
+});
+
+// Snail with a glowing shell.
+sprite("_snail", "..aa...\n.aAAa.h\n.aAaa.h\nhhhhhhh");
+
+// ------------------------------------------------------------------ placement lists
+const fungi = [["fungus_a_c", 30], ["fungus_b_m", 50], ["fungus_a_t", 92], ["fungus_b_c", 222], ["fungus_a_m", 262], ["fungus_b_t", 304]];
+const lanterns = [[8, 16], [240, 22], [292, 12]];
+const ferns = [14, 40, 58, 100, 216, 232, 254, 274, 296, 312];
+const ledgeFerns = [258, 288, 306];
+const bells = [22, 46, 82, 236, 284];
+const vines = [[36, 26], [108, 34], [160, 20], [182, 26]];
+const ledgeVines = [[256, 20], [284, 26], [302, 14]];
+const glowworms = [[[56, 6], [60, 11], [66, 7]], [[128, 8], [133, 13], [138, 6], [142, 10]], [[222, 6], [226, 12], [231, 5]]];
+const bugs = Array.from({ length: 11 }, (_, i) => {
+ const r = rng(40 + i);
+ return [24 + i * 26 + r() * 10, 48 + r() * 56, 10 + r() * 24, 6 + r() * 12, 1 + Math.floor(r() * 2), 1 + Math.floor(r() * 2), r()];
+});
+const bugAt = ([cx, cy, ax, ay, fx, fy, p], t) =>
+ [Math.round(cx + ax * Math.sin((fx * t + p) * TAU)), Math.round(cy + ay * Math.sin((fy * t + p * 2) * TAU) + 1.5 * Math.sin((3 * t + p) * TAU))];
+const fishAt = (i, t) => [Math.round(156 + 40 * Math.sin((t + i * 0.5) * TAU)), Math.round(162 + 3 * Math.sin((2 * t + i * 0.3) * TAU))];
+const sporeSources = [[37, 112], [57, 114], [99, 121], [229, 125], [269, 120], [311, 107]];
+
+// ------------------------------------------------------------------ the grotto
+anim("grotto", { w: W, h: H, ...loop },
+ layer("backwall", { wall: true }, rect(0, 0, W, H, "K"),
+ scatter("_stone*", -8, -8, W + 16, H + 16, 620, { rflip: "xy", rswap: [{}, {}, { r: "R" }], seed: 7 })),
+
+ layer("water", rect(100, POOL, 120, 30, "w")),
+
+ layer("rock", { solid: true },
+ poly([0, 0, ...ceil, W, 0], "R"),
+ poly([0, H, ...floor, W, H], "R"),
+ poly([236, 74, 300, 70, 320, 72, 320, 84, 300, 86, 270, 90, 244, 84], "R"), // overhang
+ poly([66, 26, 90, 24, 84, 60, 80, 90, 86, 118, 64, 118, 70, 90, 72, 60], "R"), // column
+ poly([136, 176, 140, 152, 147, 145, 158, 144, 166, 147, 172, 154, 176, 176], "R"), // island
+ ...[[44, 12, 4], [96, 16, 5], [120, 26, 5], [150, 12, 3], [170, 18, 4], [250, 14, 4], [276, 20, 5]]
+ .map(([x, len, w]) => poly([x - w, edgeY(ceil, x) - 2, x + w, edgeY(ceil, x) - 2, x, edgeY(ceil, x) + len], "R")),
+ ...[[18, 10, 4], [108, 9, 3], [248, 8, 3], [282, 6, 3]]
+ .map(([x, len, w]) => poly([x - w, ground(x) + 2, x + w, ground(x) + 2, x, ground(x) - len], "R")),
+ poly([200, edgeY(ceil, 204) - 1, 207, edgeY(ceil, 204) - 1, 205, edgeY(ceil, 204) + 4, 202, edgeY(ceil, 204) + 4], "_"), // waterfall crack
+ (c) => { for (let y = 1; y < H; y++) for (let x = 0; x < W; x++) if (c.is(x, y, "R") && c.is(x, y - 1, ".")) c.px(x, y, "q"); },
+ bump("bevel", { w: 3 }),
+ scatter("_lump*", 0, 0, W, H, 140, { on: "R", clip: true, rflip: "xy", seed: 3 })),
+
+ // Moss and grass carpet every upward-facing rock lip.
+ layer("flora",
+ scatter("_moss*", 0, 0, W, POOL, 170, { on: "q", below: true, rflip: "x", seed: 5 }),
+ scatter("_tuft*", 0, 0, W, POOL, 90, { on: "q", below: true, rflip: "x", seed: 6 })),
+
+ layer("life",
+ ...ferns.map((x) => stamp("fern", x - 5, ground(x) - 9, { rdelay: true, rflip: "x" })),
+ ...ledgeFerns.map((x) => stamp("fern", x - 5, ledge(x) - 9, { rdelay: true, rflip: "x" })),
+ ...bells.map((x) => stamp("bell", x - 2, ground(x) - 8, { rdelay: true, rflip: "x" })),
+ ...lanterns.map(([x, h]) => stamp("lantern" + h, x - 4, ground(x) - h + 1, { rdelay: true })),
+ stamp("lantern12", 262, ledge(266) - 11, { rdelay: true }),
+ ...fungi.map(([n, x]) => stamp(n, x - 7, ground(x) - 7, { rdelay: true })),
+ stamp("fungus_b_c", 280, ledge(287) - 7, { rdelay: true }),
+ stamp("giant", 140, 145 - 55, { rdelay: true }),
+ stamp("fern", 160, 145 - 9, { rdelay: true }), stamp("bell", 146, 145 - 8, { rdelay: true }),
+ stamp("crystals", 222, ground(228) - 11),
+ stamp("crystals", 144, edgeY(ceil, 150) - 1, { flip: "y" }),
+ ...vines.map(([x, len]) => stamp("vine" + len, x - 4, edgeY(ceil, x) - 1, { rdelay: true })),
+ ...ledgeVines.map(([x, len]) => stamp("vine" + len, x - 4, edgeY(ledgeUnder, x) - 1, { rdelay: true })),
+ stamp("_bracket", 80, 64), stamp("_bracket", 79, 84), stamp("_bracket", 81, 100),
+ (c) => {
+ c.lamp(84, 84, { r: 26, color: "#5cf0e0", power: 0.6 + 0.15 * wave(c, 2), z: 5 });
+
+ // Glowworm colonies: silk threads, beads that twinkle in turn, one lamp per colony.
+ for (const colony of glowworms) {
+ for (const [x, len] of colony) {
+ const top = edgeY(ceil, x);
+ c.vline(x, top, len, "i");
+ c.px(x, top + len, (c.frame + x) % 7 === 0 ? "C" : "b");
+ }
+ const mx = Math.round(colony.reduce((a, [x]) => a + x, 0) / colony.length);
+ c.lamp(mx, edgeY(ceil, mx) + 9, { r: 30, color: "#7ab8ff", power: 0.6, z: 10 });
+ }
+
+ // Waterfall from the crack into the pool: falling streaks, foam and spreading ripples.
+ const top = edgeY(ceil, 204) + 4;
+ for (let y = top; y < POOL; y++)
+ for (let x = 202; x <= 206; x++) {
+ // Vertical streaks per column, each with its own offset, scrolling down 6 px a frame.
+ const k = (((y - c.frame * 6 + [0, 15, 27, 9, 33][x - 202]) % 16) + 16) % 16, edge = x === 202 || x === 206;
+ c.px(x, y, k < 3 && !edge ? "W" : edge && k > 9 ? "." : "w");
+ }
+ c.grid(199, POOL - 2, c.frame % 2 ? ".W.w.W.w.\nWwWWWWwWW" : "W.w.W.w.W\nwWWwWWWwW");
+ for (let k = 0; k < 3; k++) {
+ const r = (c.frame * 2 + k * 11) % 32 + 5;
+ if (r < 30) for (const sx of [204 - r, 204 + r]) if (inPool(sx, POOL)) c.px(sx, POOL, "W");
+ }
+
+ // Glowing lily pads drift on the pool.
+ for (const [x0, a, o] of [[122, 4, 0], [186, 5, 0.4], [198, 3, 0.7]]) {
+ const x = Math.round(x0 + a * Math.sin((c.phase + o) * TAU));
+ c.grid(x, POOL - 1, ".tTt.\nlttTtl");
+ }
+
+ // The snail crawls back and forth along the left terrace.
+ const sx = Math.round(4 + 14 * (0.5 - 0.5 * Math.cos(c.phase * TAU))), left = Math.sin(c.phase * TAU) < 0;
+ c.stamp("_snail", sx, ground(sx + 3) - 4, left ? {} : { flip: "x" });
+ c.lamp(sx + 3, ground(sx + 3) - 3, { r: 16, color: "#ffb060", power: 0.45, z: 4 });
+
+ // Fish light the pool from below the surface (drawn after the reflection).
+ for (let i = 0; i < 2; i++) {
+ const [fx, fy] = fishAt(i, c.phase);
+ c.lamp(fx, fy, { r: 20, color: "#ffc070", power: 0.5, z: 3 });
+ }
+ }),
+
+ // Moths circle the big lantern, wings beating every frame.
+ (c) => {
+ for (let i = 0; i < 2; i++) {
+ const t = c.phase * (i ? -1 : 1) + i * 0.4;
+ const x = Math.round(240 + 11 * Math.cos(t * TAU * 2) + 2 * Math.sin(t * TAU * 5));
+ const y = Math.round(104 + 6 * Math.sin(t * TAU * 2) + 2 * Math.cos(t * TAU * 3));
+ c.grid(x - 1, y - 1, (c.frame + i) % 2 ? "p.p\n.P." : "...\npPp");
+ }
+ // Lightbugs with fading trails and flickering lamps.
+ bugs.forEach((b, i) => {
+ const [x, y] = bugAt(b, c.phase), [px, py] = bugAt(b, c.phase - 1 / FRAMES);
+ if (px !== x || py !== y) c.px(px, py, "y");
+ c.px(x, y, "Y");
+ c.lamp(x, y, { r: 14, color: "#d8ff90", power: 0.5 + 0.2 * Math.sin((5 * c.phase + i * 0.37) * TAU), z: 4 });
+ });
+ // Spores drift up from the fungus and fade out.
+ sporeSources.forEach(([ox, oy], s) => {
+ for (let k = 0; k < 4; k++) {
+ const r = rng(s * 10 + k), t = (c.phase + r()) % 1;
+ if (t > 0.85) continue;
+ const x = Math.round(ox + (r() - 0.5) * 8 + 4 * Math.sin((t * 2 + r()) * TAU) + 6 * t), y = Math.round(oy - 4 - t * 46);
+ c.px(x, y, t < 0.6 ? "s" : "t");
+ }
+ });
+ },
+
+ lighting({ cell: 2, smooth: true, ambient: 0.06, ambientColor: "#5048a0", block: 0.45, emit: "cCemMEtTnuUjoOzZyYaAsb" }),
+
+ // Reflection: the lit cave above, mirrored into the pool with a gentle wobble.
+ (c) => {
+ const hex = (v) => "#" + (v >>> 0).toString(16).padStart(8, "0");
+ const mix = (a, b, t) => {
+ const ch = (v, s) => (v >>> s) & 255, m = (s) => Math.round(ch(a, s) * (1 - t) + ch(b, s) * t);
+ return ((m(24) << 24) | (m(16) << 16) | (m(8) << 8) | 255) >>> 0;
+ };
+ for (let y = POOL + 1; y < H; y++)
+ for (let x = 101; x < 220; x++) {
+ if (!inPool(x, y)) continue;
+ const d = y - POOL, sx = x + Math.round(Math.sin(y * 0.7 + c.phase * TAU * 2) * (d > 2 ? 1 : 0));
+ c.px(x, y, hex(mix(c.get(x, y), c.get(sx, POOL - d), Math.max(0.25, 0.7 - d * 0.02))));
+ }
+ // Glints run along the surface.
+ for (let x = 101; x < 220; x++)
+ if (inPool(x, POOL + 1) && (x * 7 + c.frame * 3) % 13 < 2) c.px(x, POOL, hex(mix(c.get(x, POOL), 0xa8d8ffff, 0.5)));
+ for (let i = 0; i < 2; i++) {
+ const [fx, fy] = fishAt(i, c.phase), dir = Math.cos((c.phase + i * 0.5) * TAU) > 0 ? 1 : -1;
+ c.px(fx, fy, "O"); c.px(fx - dir, fy, "o"); c.px(fx - 2 * dir, fy + (c.frame % 2 ? 1 : -1), "o");
+ }
+ },
+
+ glow("cCmMtTuU", { r: 7, strength: 0.32 }),
+ glow("zZoO", { r: 5, strength: 0.4 }),
+ glow("Ys", { r: 4, strength: 0.5 }),
+ glow("bA", { r: 3, strength: 0.4 }))
diff --git a/examples/lighting.px.js b/examples/lighting.px.js
new file mode 100644
index 0000000..24b27d9
--- /dev/null
+++ b/examples/lighting.px.js
@@ -0,0 +1,77 @@
+// Lighting demo: a snowy two-floor cabin at night. Torches, a chandelier and a lamppost carry
+// their own lamps; solid layers block light, wall layers stop the sky light from coming in.
+pal({
+ k: "#0e0b16", n: "#3b2f5c", N: "#6b5a8e", s: "#e8eef7", S: "#a9b8d0",
+ d: "#5a3a2a", D: "#3a2418", t: "#6d6a78", T: "#4a4756",
+ w: "#7a4e32", W: "#5c3a26", b: "#3d2617", l: "#c9a46b", r: "#8c2f2f",
+ g: "#5d7fa8", y: "#ffd36b", Y: "#ff8a2a", G: "#e0f4ff",
+})
+
+sprite("_plank", `
+ wwwwwwwW
+ wwwwwwwW
+ wwwwwwwW
+ WWWWWWWW`)
+
+sprite("torch", `
+ .y.
+ yYy
+ .Y.
+ .b.
+ .b.`, lamp(1, 1, { r: 44, color: "#ffb35c" }))
+
+// Written as the left half; mirroring also mirrors the candle's lamp.
+sprite("chandelier", { mx: "c" }, `
+ ....b
+ ....b
+ y...b
+ b...b
+ bbbbb`, lamp(0, 2, { r: 40, color: "#ffc070" }))
+
+sprite("lamppost", { w: 3, h: 18 },
+ rect(1, 3, 1, 15, "b"), box(0, 0, 3, 3, "b"), px(1, 1, "G"),
+ lamp(1, 1, { r: 30, color: "#bfe0ff" }))
+
+sprite("table", `
+ llllllll
+ .b....b.
+ .b....b.`)
+
+const attic = [68, 46, 112, 24, 156, 46];
+
+scene("cabin", { w: 200, h: 130, bg: "n", layers: true },
+ layer("sky", { unlit: true }, grad(0, 0, 200, 100, "nN"), noise(0, 0, 200, 100, "s", 0.012, 5)),
+
+ layer("cave", { wall: true }, ellipse(30, 120, 15, 7, "D")),
+ layer("ground", { solid: true },
+ poly([0, 110, 30, 104, 56, 95, 200, 95, 200, 130, 0, 130], "s"),
+ poly([0, 112, 30, 106, 56, 97, 200, 97, 200, 130, 0, 130], "d"),
+ noise(0, 100, 200, 30, "tD", 0.08, 3, "d"),
+ ellipse(30, 120, 14, 6, "_")),
+
+ layer("backwall", { wall: true },
+ pattern("_plank", 65, 49, 94, 47),
+ clip(attic, pattern("_plank", 68, 24, 88, 22, { swap: { w: "W", W: "b" } })),
+ rect(80, 54, 10, 10, "g"), box(80, 54, 10, 10, "b"), hline(80, 58, 10, "b"),
+ rect(110, 76, 10, 12, "g"), box(110, 76, 10, 12, "b"), vline(114, 76, 12, "b")),
+
+ layer("frame", { solid: true },
+ poly([52, 48, 112, 15, 172, 48], "s"),
+ poly([56, 48, 112, 18, 168, 48], "b"),
+ poly(attic, "_"),
+ rect(60, 46, 104, 3, "b"),
+ rect(62, 69, 100, 3, "b"), rect(140, 69, 8, 3, "_"), // upper floor, hole for the ladder
+ rect(62, 46, 3, 50, "b"), rect(159, 46, 3, 50, "b"),
+ rect(62, 80, 3, 16, "_"), // front door
+ rect(159, 54, 3, 8, "_"), // open upstairs window
+ rect(62, 96, 100, 3, "t"), noise(62, 96, 100, 3, "T", 0.3, 9)),
+
+ layer("props",
+ (c) => { c.vline(141, 69, 27, "l"); c.vline(146, 69, 27, "l"); for (let y = 71; y < 96; y += 4) c.hline(141, y, 6, "l"); },
+ stamp("torch", 70, 82), stamp("torch", 152, 82), stamp("torch", 26, 116),
+ stamp("chandelier", 96, 49),
+ stamp("table", 92, 63), stamp("table", 118, 93),
+ rect(124, 64, 12, 5, "r"), rect(124, 63, 3, 2, "s"), // bed
+ stamp("lamppost", 36, 84)),
+
+ lighting({ cell: 4, sky: 0.9, skyColor: "#d8ccf0", skyReach: 20, ambient: 0.03, emit: "yYG" }))
diff --git a/examples/moon_bakery.px.js b/examples/moon_bakery.px.js
new file mode 100644
index 0000000..bc7cac4
--- /dev/null
+++ b/examples/moon_bakery.px.js
@@ -0,0 +1,258 @@
+// "Moon Buns": a lilac corner bakery with a crescent sign, a brick-oven chimney and a roof cat.
+pal({
+ k: "#2b1740", // ink
+ W: "#4a2a74", V: "#6a3d9a", v: "#8a5cc0", q: "#b894ec", // lilac walls
+ p: "#ff7fa8", P: "#c9487a", // pink
+ R: "#8a3a30", O: "#d9643c", o: "#ff9a62", u: "#ffc890", // bread / oven
+ a: "#c98a2e", L: "#f2b84a", l: "#ffe27a", w: "#fffaf0", // butter light
+ n: "#1f5f66", M: "#2f9a86", m: "#7fe0b0", // mint
+ e: "#bb9b82", C: "#e6cfae", c: "#fff3dc", // cream plaster
+ B: "#ffcfae", b: "#f5ab8a", // peach backdrop
+ r: "#ff5d6c",
+})
+ramps("kWVvq", "kPp", "kROou", "kaLlw", "knMm", "keCc")
+
+// ---------------------------------------------------------------- small parts
+sprite("_dentil", `
+ LL..
+ aa..`)
+sprite("_brick", `
+ cccccccC
+ cccccccC
+ cccccccC
+ CCCCCCCC
+ cccCcccc
+ cccCcccc
+ cccCcccc
+ CCCCCCCC`)
+sprite("_siding", `
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ VVVVVVVV
+ vvvvvvvv`)
+sprite("_awning", `
+ PPPPCCCC
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ .pp..cc.`)
+
+// window goods, 7x7, bottom row sits on the shelf
+sprite("_loaf", `
+ .......
+ ..ooo..
+ .ouooO.
+ .oooOO.
+ .ooOOO.
+ .ROOOR.
+ .RRRRR.`)
+sprite("_croissant", `
+ .......
+ ..ouo..
+ .ouoOo.
+ ouOoOou
+ .oOoOo.
+ ..ROR..
+ .......`)
+sprite("_donut", `
+ .......
+ ..ppp..
+ .pwpPp.
+ .pP.Pp.
+ .pPPPp.
+ ..ooo..
+ .......`)
+sprite("_pie", `
+ .......
+ .......
+ .uuuuu.
+ uooooOO
+ .OOOOO.
+ .RRRRR.
+ .......`)
+sprite("_cupcake", `
+ ..ppp..
+ .pwpPp.
+ .PPPPP.
+ .cCcCc.
+ .cCcCc.
+ ..CcC..
+ .......`)
+sprite("_baguette", `
+ .....uo
+ ....uoO
+ ...uoO.
+ ..uoO..
+ .uoO...
+ uoO....
+ oO.....`)
+group("goods", ["_loaf", "_loaf", "_croissant", "_donut", "_pie", "_cupcake", "_baguette"])
+
+sprite("_plant", `
+ .m.m..
+ mMmm.m
+ .mMmm.
+ ..Mm..
+ .pppp.
+ .PppP.
+ ..PP..`)
+
+sprite("_moon_win", { w: 19, h: 19 },
+ circ(9, 9, 9, "L"), circ(9, 9, 7, "l"), circ(7, 7, 4, "w"),
+ hline(2, 9, 15, "L"), vline(9, 2, 15, "L"), ring(9, 9, 7, "a"), ring(9, 9, 9, "a"),
+ shade([10, 10, 9, 9]))
+
+sprite("_bell", `
+ .a.
+ LLL
+ LlL
+ aLa`)
+sprite("_bulb_y", "l\nL")
+sprite("_bulb_p", "p\nP")
+sprite("_bulb_m", "m\nM")
+group("bulbs", ["_bulb_y", "_bulb_p", "_bulb_m", "_bulb_y"])
+
+sprite("_steam_a", `
+ .w.
+ www
+ .w.`)
+sprite("_steam_b", "w")
+group("steam", ["_steam_a", "_steam_b", "_steam_b"])
+
+sprite("_spark", `
+ .l.
+ lwl
+ .l.`)
+sprite("_dot", "w")
+group("sparks", ["_spark", "_dot", "_dot", "_dot"])
+
+sprite("_cat", `
+ k...k..
+ kk.kk..
+ kmkmk..
+ kkkkk..
+ .kkkk..
+ .kkkkk.
+ .kkkkkk`)
+sprite("_bird", `
+ .k.
+ kkk
+ ..k`)
+
+// ---------------------------------------------------------------- the shop
+sprite("shop", { w: 104, h: 100, outline: "k", layers: true },
+ layer("walls",
+ pattern("_siding", 0, 0, 104, 40),
+ pattern("_brick", 0, 40, 104, 60),
+ rect(0, 0, 104, 4, "L"), hline(0, 4, 104, "a"), pattern("_dentil", 0, 5, 104, 2),
+ rect(0, 38, 104, 3, "L"), hline(0, 41, 104, "a"),
+ rect(0, 91, 104, 9, "n"), hline(0, 91, 104, "m"), vline(26, 92, 8, "k"), vline(52, 92, 8, "k"), vline(78, 92, 8, "k")),
+
+ layer("upstairs",
+ // crescent sign plate
+ rect(14, 10, 48, 22, "W"), box(14, 10, 48, 22, "L"),
+ px(15, 11, "l"), px(60, 11, "l"), px(15, 30, "l"), px(60, 30, "l"),
+ circ(25, 21, 7, "l"), circ(28, 19, 6, "W"), px(22, 17, "w"),
+ text(46, 14, "MOON", "l", { align: "c", shadow: "a" }),
+ text(46, 22, "BUNS", "p", { align: "c", shadow: "P" }),
+ // round window
+ stamp("_moon_win", 70, 12),
+ rect(68, 29, 23, 3, "L"), hline(68, 31, 23, "a"),
+ stamp("_plant", 71, 23), stamp("_plant", 82, 23, { flip: "x" }),
+ // drainpipe
+ rect(98, 0, 4, 40, "M"), vline(101, 0, 40, "n"), vline(99, 0, 40, "m"), hline(97, 20, 6, "n"),
+ // little vent
+ rect(3, 14, 8, 8, "W"), box(3, 14, 8, 8, "L"), hline(4, 16, 6, "V"), hline(4, 18, 6, "V"), hline(4, 20, 6, "V")),
+
+ layer("storefront",
+ // shop window
+ rect(5, 56, 62, 36, "W"), rect(7, 58, 58, 32, "L"), grad(7, 58, 58, 32, "lLLa"),
+ tile("goods", 10, 62, 7, 1, { seed: 1 }), hline(8, 69, 56, "W"),
+ tile("goods", 10, 71, 7, 1, { seed: 2 }), hline(8, 78, 56, "W"),
+ tile("goods", 10, 80, 7, 1, { seed: 3 }), rect(5, 87, 62, 5, "V"), hline(5, 87, 62, "v"),
+ vline(35, 58, 29, "W"),
+ // door
+ rect(72, 52, 26, 40, "W"), rect(74, 54, 22, 38, "M"), grad(74, 54, 22, 38, "mMMn", "v", 0.3),
+ circ(85, 65, 6, "l"), circ(83, 63, 3, "w"), ring(85, 65, 6, "n"),
+ box(77, 74, 16, 6, "n"), box(77, 82, 16, 8, "n"),
+ px(94, 78, "L"), px(94, 79, "L"),
+ rect(78, 40, 14, 8, "c"), box(78, 40, 14, 8, "C"), text(85, 42, "OPEN", "r", { align: "c" }),
+ // awning
+ pattern("_awning", 2, 46, 72, 10),
+ stamp("_bell", 81, 49)),
+
+ layer("awning_shadow", { shade: true }, rect(2, 56, 72, 2, "k")),
+ layer("glow", { light: true, density: 0.5 }, circ(36, 74, 20, "k")),
+)
+
+// ---------------------------------------------------------------- roof & street props
+// brick oven chimney with a pizza-peel hatch
+sprite("chimney", { w: 18, h: 36, outline: "k" },
+ pattern("_brick", 0, 4, 18, 32),
+ rect(0, 4, 18, 3, "R"), hline(0, 6, 18, "k"),
+ rect(-1, 0, 20, 5, "O"), hline(0, 0, 18, "o"), hline(0, 4, 18, "R"),
+ rect(4, 18, 10, 12, "W"), rect(5, 19, 8, 10, "O"), rect(6, 21, 6, 8, "l"), rect(7, 23, 4, 6, "a"),
+ shade([0, 4, 6, 32], 1, 0.5), shade([13, 4, 5, 32]))
+
+sprite("lamp", { w: 17, h: 66, outline: "k" },
+ vline(8, 16, 50, "W"), vline(7, 16, 50, "V"), rect(4, 62, 9, 4, "W"), hline(4, 62, 9, "V"),
+ hline(0, 12, 17, "V"), line(8, 16, 2, 12, "W"), line(8, 16, 14, 12, "W"),
+ circ(8, 6, 6, "l"), circ(6, 4, 3, "w"), ring(8, 6, 6, "a"),
+ circ(2, 14, 2, "p"), circ(14, 14, 2, "m"))
+
+sprite("cart", { w: 30, h: 22, outline: "k" },
+ rect(0, 0, 30, 4, "p"), pattern("_awning", 0, 0, 30, 6),
+ vline(2, 6, 10, "W"), vline(27, 6, 10, "W"),
+ rect(0, 16, 30, 3, "V"), hline(0, 16, 30, "v"),
+ stamp("_loaf", 4, 9), stamp("_croissant", 11, 9), stamp("_baguette", 18, 9), stamp("_pie", 22, 9),
+ circ(6, 20, 2, "n"), circ(24, 20, 2, "n"), px(6, 20, "m"), px(24, 20, "m"))
+
+sprite("board", { w: 22, h: 20, outline: "k" },
+ rect(1, 0, 20, 17, "W"), box(1, 0, 20, 17, "L"),
+ text(11, 3, "FRESH", "l", { align: "c" }), text(11, 10, "HOT", "p", { align: "c" }),
+ line(3, 17, 1, 19, "W"), line(18, 17, 20, 19, "W"))
+
+sprite("mailbox", { w: 10, h: 16, outline: "k" },
+ rect(0, 0, 10, 7, "r"), rect(0, 7, 10, 3, "r"), hline(0, 9, 10, "P"),
+ hline(2, 3, 6, "k"), vline(4, 10, 6, "W"), vline(5, 10, 6, "V"), px(8, 1, "w"))
+
+// ---------------------------------------------------------------- scene
+scene("moon_buns", { w: 176, h: 168, bg: "B", layers: true },
+ layer("backdrop",
+ scatter("sparks", 0, 0, 176, 120, 26, { seed: 8 }),
+ // big soft moon behind
+ circ(150, 28, 16, "b"), circ(150, 28, 13, "c"), circ(156, 25, 11, "B"), circ(150, 28, 13, "c"),
+ circ(156, 25, 11, "B")),
+
+ layer("buildings",
+ stamp("chimney", 108, 17),
+ stamp("shop", 33, 49)),
+
+ layer("roof",
+ stamp("_cat", 50, 42), stamp("_bird", 152, 56),
+ stamp("_plant", 78, 43), stamp("_plant", 120, 43, { flip: "x" }),
+ // weather vane: a star on a pole
+ vline(64, 28, 21, "W"), hline(60, 34, 9, "W"), circ(64, 25, 3, "l"), px(64, 25, "w"), px(61, 27, "l"), px(67, 27, "l")),
+
+ layer("steam",
+ // rising steam from the chimney
+ stamp("_steam_a", 114, 12), stamp("_steam_a", 118, 6), stamp("_steam_a", 113, 1),
+ stamp("_steam_b", 121, 10), stamp("_steam_b", 110, 8)),
+
+ layer("street",
+ rect(0, 150, 176, 3, "W"), hline(0, 150, 176, "V"),
+ stamp("lamp", 8, 86), stamp("cart", 142, 128), stamp("board", 22, 130), stamp("mailbox", 128, 134),
+ stamp("_plant", 131, 143, { flip: "x" }),
+ wire(16, 90, 38, 54, 6, "W", { hang: "bulbs", every: 4, seed: 3 }),
+ wire(138, 54, 168, 60, 5, "W", { hang: "bulbs", every: 4, seed: 4 })),
+
+ layer("spill", { light: true },
+ poly([40, 150, 100, 150, 108, 156, 32, 156], "k"),
+ circ(16, 92, 8, "k")),
+ layer("halo", { light: true, density: 0.5 },
+ circ(16, 92, 18, "k"), poly([34, 150, 108, 150, 118, 160, 22, 160], "k")),
+)
diff --git a/examples/moon_bakery_3d.px.js b/examples/moon_bakery_3d.px.js
new file mode 100644
index 0000000..d9ad504
--- /dev/null
+++ b/examples/moon_bakery_3d.px.js
@@ -0,0 +1,289 @@
+// "Moon Buns": a lilac corner bakery with a crescent sign, a brick-oven chimney and a roof cat.
+pal({
+ k: "#2b1740", // ink
+ W: "#4a2a74", V: "#6a3d9a", v: "#8a5cc0", q: "#b894ec", // lilac walls
+ p: "#ff7fa8", P: "#c9487a", // pink
+ R: "#8a3a30", O: "#d9643c", o: "#ff9a62", u: "#ffc890", // bread / oven
+ a: "#c98a2e", L: "#f2b84a", l: "#ffe27a", w: "#fffaf0", // butter light
+ n: "#1f5f66", M: "#2f9a86", m: "#7fe0b0", // mint
+ e: "#bb9b82", C: "#e6cfae", c: "#fff3dc", // cream plaster
+ B: "#ffcfae", b: "#f5ab8a", // peach backdrop
+ r: "#ff5d6c",
+})
+ramps("kWVvq", "kPp", "kROou", "kaLlw", "knMm", "keCc")
+
+// ---------------------------------------------------------------- small parts
+sprite("_dentil", `
+ LL..
+ aa..`)
+sprite("_brick", `
+ cccccccC
+ cccccccC
+ cccccccC
+ CCCCCCCC
+ cccCcccc
+ cccCcccc
+ cccCcccc
+ CCCCCCCC`)
+sprite("_siding", `
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ VVVVVVVV
+ vvvvvvvv`)
+sprite("_awning", `
+ PPPPCCCC
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ .pp..cc.`)
+
+// window goods, 7x7, bottom row sits on the shelf
+sprite("_loaf", `
+ .......
+ ..ooo..
+ .ouooO.
+ .oooOO.
+ .ooOOO.
+ .ROOOR.
+ .RRRRR.`)
+sprite("_croissant", `
+ .......
+ ..ouo..
+ .ouoOo.
+ ouOoOou
+ .oOoOo.
+ ..ROR..
+ .......`)
+sprite("_donut", `
+ .......
+ ..ppp..
+ .pwpPp.
+ .pP.Pp.
+ .pPPPp.
+ ..ooo..
+ .......`)
+sprite("_pie", `
+ .......
+ .......
+ .uuuuu.
+ uooooOO
+ .OOOOO.
+ .RRRRR.
+ .......`)
+sprite("_cupcake", `
+ ..ppp..
+ .pwpPp.
+ .PPPPP.
+ .cCcCc.
+ .cCcCc.
+ ..CcC..
+ .......`)
+sprite("_baguette", `
+ .....uo
+ ....uoO
+ ...uoO.
+ ..uoO..
+ .uoO...
+ uoO....
+ oO.....`)
+group("goods", ["_loaf", "_loaf", "_croissant", "_donut", "_pie", "_cupcake", "_baguette"])
+
+sprite("_plant", `
+ .m.m..
+ mMmm.m
+ .mMmm.
+ ..Mm..
+ .pppp.
+ .PppP.
+ ..PP..`)
+
+sprite("_moon_win", { w: 19, h: 19 },
+ circ(9, 9, 9, "L"), circ(9, 9, 7, "l"), circ(7, 7, 4, "w"),
+ hline(2, 9, 15, "L"), vline(9, 2, 15, "L"), ring(9, 9, 7, "a"), ring(9, 9, 9, "a"),
+ shade([10, 10, 9, 9]))
+
+sprite("_bell", `
+ .a.
+ LLL
+ LlL
+ aLa`)
+sprite("_bulb_y", "l\nL")
+sprite("_bulb_p", "p\nP")
+sprite("_bulb_m", "m\nM")
+group("bulbs", ["_bulb_y", "_bulb_p", "_bulb_m", "_bulb_y"])
+
+sprite("_steam_a", `
+ .w.
+ www
+ .w.`)
+sprite("_steam_b", "w")
+group("steam", ["_steam_a", "_steam_b", "_steam_b"])
+
+sprite("_spark", `
+ .l.
+ lwl
+ .l.`)
+sprite("_dot", "w")
+group("sparks", ["_spark", "_dot", "_dot", "_dot"])
+
+sprite("_cat", `
+ k...k..
+ kk.kk..
+ kmkmk..
+ kkkkk..
+ .kkkk..
+ .kkkkk.
+ .kkkkkk`)
+sprite("_bird", `
+ .k.
+ kkk
+ ..k`)
+
+sprite("lamp", { w: 17, h: 66, outline: "k" },
+ vline(8, 16, 50, "W"), vline(7, 16, 50, "V"), rect(4, 62, 9, 4, "W"), hline(4, 62, 9, "V"),
+ hline(0, 12, 17, "V"), line(8, 16, 2, 12, "W"), line(8, 16, 14, 12, "W"),
+ circ(8, 6, 6, "l"), circ(6, 4, 3, "w"), ring(8, 6, 6, "a"),
+ circ(2, 14, 2, "p"), circ(14, 14, 2, "m"))
+
+sprite("cart", { w: 30, h: 22, outline: "k" },
+ rect(0, 0, 30, 4, "p"), pattern("_awning", 0, 0, 30, 6),
+ vline(2, 6, 10, "W"), vline(27, 6, 10, "W"),
+ rect(0, 16, 30, 3, "V"), hline(0, 16, 30, "v"),
+ stamp("_loaf", 4, 9), stamp("_croissant", 11, 9), stamp("_baguette", 18, 9), stamp("_pie", 22, 9),
+ circ(6, 20, 2, "n"), circ(24, 20, 2, "n"), px(6, 20, "m"), px(24, 20, "m"))
+
+sprite("board", { w: 22, h: 20, outline: "k" },
+ rect(1, 0, 20, 17, "W"), box(1, 0, 20, 17, "L"),
+ text(11, 3, "FRESH", "l", { align: "c" }), text(11, 10, "HOT", "p", { align: "c" }),
+ line(3, 17, 1, 19, "W"), line(18, 17, 20, 19, "W"))
+
+// ---------------------------------------------------------------- 3/4 view: front face + side face + roof
+// Oblique projection: depth runs right and up at 2:1. Front face is lit, side is stepped down a shade.
+const FX0 = 20, FX1 = 112, TOP = 56, BOT = 150, D = 30
+const sp = (u, y) => [FX1 + u, y - u / 2] // point on the side plane
+const sidePoly = (u0, u1, y0, y1) => [...sp(u0, TOP + y0), ...sp(u1, TOP + y0), ...sp(u1, TOP + y1), ...sp(u0, TOP + y1)] // y relative to TOP
+// small box with front, side and top faces
+const box3 = (x, y, w, h, d, f, s, t) => (c) => {
+ c.poly([x + w, y, x + w + d, y - d / 2, x + w + d, y + h - d / 2, x + w, y + h], s)
+ c.poly([x, y, x + w, y, x + w + d, y - d / 2, x + d, y - d / 2], t)
+ c.rect(x, y, w, h, f)
+}
+// slanted course lines across the side face
+const sideLines = (y0, y1, step, col) => (c) => {
+ for (let y = y0; y <= y1; y += step) c.line(FX1, y, FX1 + D - 1, y - (D - 1) / 2, col)
+}
+const sideJoints = (y0, y1, step, col) => (c) => {
+ let r = 0
+ for (let y = y0; y < y1; y += step, r++)
+ for (let u = 4 + (r % 2) * 4; u < D; u += 8) c.vline(FX1 + u, y - Math.floor(u / 2) + 1, step - 1, col)
+}
+const SIDE = [FX1, TOP, FX1 + D, TOP - D / 2, FX1 + D, BOT - D / 2, FX1, BOT]
+
+
+scene("moon_buns_3d", { w: 192, h: 170, bg: "B", layers: true },
+ layer("backdrop",
+ scatter("sparks", 0, 0, 192, 110, 26, { seed: 8 }),
+ circ(160, 26, 16, "b"), circ(160, 26, 13, "c"), circ(166, 23, 11, "B"),
+ rect(0, 135, 192, 35, "b"), hline(0, 135, 192, "B"),
+ rect(0, 150, 192, 20, "C"), hline(0, 150, 192, "e"), hline(0, 151, 192, "c"),
+ (c) => { for (let x = 6; x < 192; x += 28) c.vline(x, 153, 17, "c") }),
+
+ // ---- roof (top face), then the things standing on it
+ layer("roof",
+ poly([FX0, TOP, FX1, TOP, FX1 + D, TOP - D / 2, FX0 + D, TOP - D / 2], "q"),
+ line(FX0 + D, TOP - D / 2, FX1 + D, TOP - D / 2, "v"), line(FX0, TOP, FX0 + D, TOP - D / 2, "v"),
+ line(FX1, TOP, FX1 + D, TOP - D / 2, "v"),
+ // roof hatch and ac
+ box3(34, 48, 14, 6, 6, "m", "M", "w"), px(37, 50, "n"), px(41, 50, "n"),
+ // brick-oven chimney
+ box3(74, 24, 14, 29, 8, "O", "R", "o"), rect(76, 14, 10, 4, "k"),
+ (c) => { for (let y = 28; y < 52; y += 4) c.hline(74, y, 14, "R") },
+ box3(72, 18, 18, 5, 10, "L", "a", "l"),
+ // weather vane star
+ vline(58, 26, 24, "W"), hline(54, 38, 9, "W"), circ(58, 23, 3, "l"), px(58, 23, "w"), px(55, 25, "l"), px(61, 25, "l"),
+ stamp("_cat", 98, 44), stamp("_plant", 28, 44), stamp("_plant", 118, 38, { flip: "x" }), stamp("_bird", 112, 29)),
+
+ // ---- side face
+ layer("side",
+ poly(SIDE, "v"),
+ // upstairs siding
+ sideLines(TOP + 6, TOP + 34, 6, "V"),
+ // cornice + band
+ poly(sidePoly(0, D, 0, 4), "L"), poly(sidePoly(0, D, 4, 5), "a"),
+ poly(sidePoly(0, D, 36, 39), "L"), poly(sidePoly(0, D, 39, 40), "a"),
+ // brick below the band
+ poly(sidePoly(0, D, 40, 88), "c"),
+ sideLines(TOP + 47, TOP + 87, 8, "C"), sideJoints(TOP + 40, TOP + 88, 8, "C"),
+ poly(sidePoly(0, D, 88, 94), "n"),
+ // upstairs side windows
+ poly(sidePoly(3, 11, 9, 27), "W"), poly(sidePoly(4, 10, 10, 26), "l"), poly(sidePoly(2, 12, 27, 29), "L"),
+ poly(sidePoly(18, 26, 9, 27), "W"), poly(sidePoly(19, 25, 10, 26), "l"), poly(sidePoly(17, 27, 27, 29), "L"),
+ // big side bay window
+ poly(sidePoly(4, 26, 50, 82), "W"), poly(sidePoly(6, 24, 52, 80), "L"), poly(sidePoly(6, 24, 52, 80), "l"),
+ poly(sidePoly(14, 16, 52, 80), "W"),
+ poly(sidePoly(4, 26, 82, 86), "V"),
+ poly(sidePoly(8, 14, 58, 66), "p"), poly(sidePoly(17, 23, 58, 66), "m"),
+ // lit lamp sign hanging at the corner
+ shade(SIDE, 1)),
+
+ // ---- front face (local coords: x = FX0, y = TOP)
+ layer("front", { x: FX0, y: TOP },
+ pattern("_siding", 0, 0, 92, 36),
+ pattern("_brick", 0, 39, 92, 55),
+ rect(0, 0, 92, 4, "L"), hline(0, 4, 92, "a"), pattern("_dentil", 0, 5, 92, 2),
+ rect(0, 36, 92, 3, "L"), hline(0, 39, 92, "a"),
+ rect(0, 88, 92, 6, "n"), hline(0, 88, 92, "m"),
+ // sign plate with crescent
+ rect(8, 10, 46, 20, "W"), box(8, 10, 46, 20, "L"),
+ px(9, 11, "l"), px(52, 11, "l"), px(9, 28, "l"), px(52, 28, "l"),
+ circ(19, 20, 7, "l"), circ(22, 18, 6, "W"), px(16, 16, "w"),
+ text(38, 13, "MOON", "l", { align: "c", shadow: "a" }),
+ text(38, 21, "BUNS", "p", { align: "c", shadow: "P" }),
+ // round window + planters, drainpipe
+ stamp("_moon_win", 62, 10), rect(60, 27, 23, 3, "L"), hline(60, 29, 23, "a"),
+ stamp("_plant", 63, 21), stamp("_plant", 74, 21, { flip: "x" }),
+ rect(86, 0, 4, 88, "M"), vline(89, 0, 88, "n"), vline(87, 0, 88, "m"),
+ // shop window
+ rect(5, 52, 54, 34, "W"), rect(7, 54, 50, 27, "L"), grad(7, 54, 50, 27, "lLLa"),
+ tile("goods", 9, 56, 7, 1, { seed: 1 }), hline(8, 63, 48, "W"),
+ tile("goods", 9, 65, 7, 1, { seed: 2 }), hline(8, 72, 48, "W"),
+ tile("goods", 9, 74, 7, 1, { seed: 3 }), rect(5, 81, 54, 5, "V"), hline(5, 81, 54, "v"),
+ vline(32, 54, 27, "W"),
+ // door
+ rect(64, 48, 22, 40, "W"), rect(66, 50, 18, 38, "M"), grad(66, 50, 18, 38, "mMMn", "v", 0.3),
+ circ(75, 60, 5, "l"), circ(73, 58, 2, "w"), ring(75, 60, 5, "n"),
+ box(68, 70, 14, 6, "n"), box(68, 78, 14, 8, "n"), px(82, 74, "L"), px(82, 75, "L"),
+ rect(66, 40, 18, 7, "c"), box(66, 40, 18, 7, "C"), text(75, 41, "OPEN", "r", { align: "c" }),
+ // awning
+ pattern("_awning", 0, 42, 62, 10)),
+
+ layer("awning_shadow", { shade: true }, rect(FX0, TOP + 52, 62, 2, "k")),
+ layer("roof_light", { light: true, density: 0.5 },
+ poly([FX0, TOP, FX1, TOP, FX1 + D, TOP - D / 2, FX0 + D, TOP - D / 2], "k")),
+ layer("glow", { light: true, density: 0.5 }, circ(FX0 + 30, TOP + 70, 20, "k")),
+ // cast shadow on the ground, falling right and back
+ layer("cast", { shade: true },
+ poly([FX1, BOT, FX1 + D, BOT - D / 2, FX1 + D + 26, BOT - D / 2, FX1 + 26, BOT], "k"),
+ poly([FX0 - 2, BOT, FX1, BOT, FX1 + 26, BOT, FX1 + 22, BOT + 3, FX0 - 2, BOT + 3], "k")),
+
+ layer("steam",
+ stamp("_steam_a", 78, 11), stamp("_steam_a", 83, 4), stamp("_steam_a", 77, -3),
+ stamp("_steam_b", 86, 9), stamp("_steam_b", 74, 6)),
+
+ layer("street",
+ stamp("lamp", 2, 92), stamp("lamp", 176, 84, { flip: "x" }),
+ stamp("board", 30, 138),
+ box3(100, 140, 9, 12, 5, "r", "P", "p"), vline(104, 152, 5, "W"),
+ box3(140, 148, 28, 3, 6, "V", "W", "v"),
+ stamp("cart", 142, 134),
+ stamp("_plant", 128, 146), stamp("_plant", 12, 150),
+ wire(142, 41, 184, 90, 8, "W", { hang: "bulbs", every: 4, seed: 3 }),
+ wire(2, 98, 20, 58, 2, "W", { hang: "bulbs", every: 4, seed: 5 })),
+
+ layer("spill", { light: true },
+ poly([FX0 + 4, BOT, FX0 + 60, BOT, FX0 + 66, BOT + 5, FX0 - 4, BOT + 5], "k")),
+)
diff --git a/examples/moon_bakery_flat.px.js b/examples/moon_bakery_flat.px.js
new file mode 100644
index 0000000..bc7cac4
--- /dev/null
+++ b/examples/moon_bakery_flat.px.js
@@ -0,0 +1,258 @@
+// "Moon Buns": a lilac corner bakery with a crescent sign, a brick-oven chimney and a roof cat.
+pal({
+ k: "#2b1740", // ink
+ W: "#4a2a74", V: "#6a3d9a", v: "#8a5cc0", q: "#b894ec", // lilac walls
+ p: "#ff7fa8", P: "#c9487a", // pink
+ R: "#8a3a30", O: "#d9643c", o: "#ff9a62", u: "#ffc890", // bread / oven
+ a: "#c98a2e", L: "#f2b84a", l: "#ffe27a", w: "#fffaf0", // butter light
+ n: "#1f5f66", M: "#2f9a86", m: "#7fe0b0", // mint
+ e: "#bb9b82", C: "#e6cfae", c: "#fff3dc", // cream plaster
+ B: "#ffcfae", b: "#f5ab8a", // peach backdrop
+ r: "#ff5d6c",
+})
+ramps("kWVvq", "kPp", "kROou", "kaLlw", "knMm", "keCc")
+
+// ---------------------------------------------------------------- small parts
+sprite("_dentil", `
+ LL..
+ aa..`)
+sprite("_brick", `
+ cccccccC
+ cccccccC
+ cccccccC
+ CCCCCCCC
+ cccCcccc
+ cccCcccc
+ cccCcccc
+ CCCCCCCC`)
+sprite("_siding", `
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ vvvvvvvv
+ VVVVVVVV
+ vvvvvvvv`)
+sprite("_awning", `
+ PPPPCCCC
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ ppppcccc
+ .pp..cc.`)
+
+// window goods, 7x7, bottom row sits on the shelf
+sprite("_loaf", `
+ .......
+ ..ooo..
+ .ouooO.
+ .oooOO.
+ .ooOOO.
+ .ROOOR.
+ .RRRRR.`)
+sprite("_croissant", `
+ .......
+ ..ouo..
+ .ouoOo.
+ ouOoOou
+ .oOoOo.
+ ..ROR..
+ .......`)
+sprite("_donut", `
+ .......
+ ..ppp..
+ .pwpPp.
+ .pP.Pp.
+ .pPPPp.
+ ..ooo..
+ .......`)
+sprite("_pie", `
+ .......
+ .......
+ .uuuuu.
+ uooooOO
+ .OOOOO.
+ .RRRRR.
+ .......`)
+sprite("_cupcake", `
+ ..ppp..
+ .pwpPp.
+ .PPPPP.
+ .cCcCc.
+ .cCcCc.
+ ..CcC..
+ .......`)
+sprite("_baguette", `
+ .....uo
+ ....uoO
+ ...uoO.
+ ..uoO..
+ .uoO...
+ uoO....
+ oO.....`)
+group("goods", ["_loaf", "_loaf", "_croissant", "_donut", "_pie", "_cupcake", "_baguette"])
+
+sprite("_plant", `
+ .m.m..
+ mMmm.m
+ .mMmm.
+ ..Mm..
+ .pppp.
+ .PppP.
+ ..PP..`)
+
+sprite("_moon_win", { w: 19, h: 19 },
+ circ(9, 9, 9, "L"), circ(9, 9, 7, "l"), circ(7, 7, 4, "w"),
+ hline(2, 9, 15, "L"), vline(9, 2, 15, "L"), ring(9, 9, 7, "a"), ring(9, 9, 9, "a"),
+ shade([10, 10, 9, 9]))
+
+sprite("_bell", `
+ .a.
+ LLL
+ LlL
+ aLa`)
+sprite("_bulb_y", "l\nL")
+sprite("_bulb_p", "p\nP")
+sprite("_bulb_m", "m\nM")
+group("bulbs", ["_bulb_y", "_bulb_p", "_bulb_m", "_bulb_y"])
+
+sprite("_steam_a", `
+ .w.
+ www
+ .w.`)
+sprite("_steam_b", "w")
+group("steam", ["_steam_a", "_steam_b", "_steam_b"])
+
+sprite("_spark", `
+ .l.
+ lwl
+ .l.`)
+sprite("_dot", "w")
+group("sparks", ["_spark", "_dot", "_dot", "_dot"])
+
+sprite("_cat", `
+ k...k..
+ kk.kk..
+ kmkmk..
+ kkkkk..
+ .kkkk..
+ .kkkkk.
+ .kkkkkk`)
+sprite("_bird", `
+ .k.
+ kkk
+ ..k`)
+
+// ---------------------------------------------------------------- the shop
+sprite("shop", { w: 104, h: 100, outline: "k", layers: true },
+ layer("walls",
+ pattern("_siding", 0, 0, 104, 40),
+ pattern("_brick", 0, 40, 104, 60),
+ rect(0, 0, 104, 4, "L"), hline(0, 4, 104, "a"), pattern("_dentil", 0, 5, 104, 2),
+ rect(0, 38, 104, 3, "L"), hline(0, 41, 104, "a"),
+ rect(0, 91, 104, 9, "n"), hline(0, 91, 104, "m"), vline(26, 92, 8, "k"), vline(52, 92, 8, "k"), vline(78, 92, 8, "k")),
+
+ layer("upstairs",
+ // crescent sign plate
+ rect(14, 10, 48, 22, "W"), box(14, 10, 48, 22, "L"),
+ px(15, 11, "l"), px(60, 11, "l"), px(15, 30, "l"), px(60, 30, "l"),
+ circ(25, 21, 7, "l"), circ(28, 19, 6, "W"), px(22, 17, "w"),
+ text(46, 14, "MOON", "l", { align: "c", shadow: "a" }),
+ text(46, 22, "BUNS", "p", { align: "c", shadow: "P" }),
+ // round window
+ stamp("_moon_win", 70, 12),
+ rect(68, 29, 23, 3, "L"), hline(68, 31, 23, "a"),
+ stamp("_plant", 71, 23), stamp("_plant", 82, 23, { flip: "x" }),
+ // drainpipe
+ rect(98, 0, 4, 40, "M"), vline(101, 0, 40, "n"), vline(99, 0, 40, "m"), hline(97, 20, 6, "n"),
+ // little vent
+ rect(3, 14, 8, 8, "W"), box(3, 14, 8, 8, "L"), hline(4, 16, 6, "V"), hline(4, 18, 6, "V"), hline(4, 20, 6, "V")),
+
+ layer("storefront",
+ // shop window
+ rect(5, 56, 62, 36, "W"), rect(7, 58, 58, 32, "L"), grad(7, 58, 58, 32, "lLLa"),
+ tile("goods", 10, 62, 7, 1, { seed: 1 }), hline(8, 69, 56, "W"),
+ tile("goods", 10, 71, 7, 1, { seed: 2 }), hline(8, 78, 56, "W"),
+ tile("goods", 10, 80, 7, 1, { seed: 3 }), rect(5, 87, 62, 5, "V"), hline(5, 87, 62, "v"),
+ vline(35, 58, 29, "W"),
+ // door
+ rect(72, 52, 26, 40, "W"), rect(74, 54, 22, 38, "M"), grad(74, 54, 22, 38, "mMMn", "v", 0.3),
+ circ(85, 65, 6, "l"), circ(83, 63, 3, "w"), ring(85, 65, 6, "n"),
+ box(77, 74, 16, 6, "n"), box(77, 82, 16, 8, "n"),
+ px(94, 78, "L"), px(94, 79, "L"),
+ rect(78, 40, 14, 8, "c"), box(78, 40, 14, 8, "C"), text(85, 42, "OPEN", "r", { align: "c" }),
+ // awning
+ pattern("_awning", 2, 46, 72, 10),
+ stamp("_bell", 81, 49)),
+
+ layer("awning_shadow", { shade: true }, rect(2, 56, 72, 2, "k")),
+ layer("glow", { light: true, density: 0.5 }, circ(36, 74, 20, "k")),
+)
+
+// ---------------------------------------------------------------- roof & street props
+// brick oven chimney with a pizza-peel hatch
+sprite("chimney", { w: 18, h: 36, outline: "k" },
+ pattern("_brick", 0, 4, 18, 32),
+ rect(0, 4, 18, 3, "R"), hline(0, 6, 18, "k"),
+ rect(-1, 0, 20, 5, "O"), hline(0, 0, 18, "o"), hline(0, 4, 18, "R"),
+ rect(4, 18, 10, 12, "W"), rect(5, 19, 8, 10, "O"), rect(6, 21, 6, 8, "l"), rect(7, 23, 4, 6, "a"),
+ shade([0, 4, 6, 32], 1, 0.5), shade([13, 4, 5, 32]))
+
+sprite("lamp", { w: 17, h: 66, outline: "k" },
+ vline(8, 16, 50, "W"), vline(7, 16, 50, "V"), rect(4, 62, 9, 4, "W"), hline(4, 62, 9, "V"),
+ hline(0, 12, 17, "V"), line(8, 16, 2, 12, "W"), line(8, 16, 14, 12, "W"),
+ circ(8, 6, 6, "l"), circ(6, 4, 3, "w"), ring(8, 6, 6, "a"),
+ circ(2, 14, 2, "p"), circ(14, 14, 2, "m"))
+
+sprite("cart", { w: 30, h: 22, outline: "k" },
+ rect(0, 0, 30, 4, "p"), pattern("_awning", 0, 0, 30, 6),
+ vline(2, 6, 10, "W"), vline(27, 6, 10, "W"),
+ rect(0, 16, 30, 3, "V"), hline(0, 16, 30, "v"),
+ stamp("_loaf", 4, 9), stamp("_croissant", 11, 9), stamp("_baguette", 18, 9), stamp("_pie", 22, 9),
+ circ(6, 20, 2, "n"), circ(24, 20, 2, "n"), px(6, 20, "m"), px(24, 20, "m"))
+
+sprite("board", { w: 22, h: 20, outline: "k" },
+ rect(1, 0, 20, 17, "W"), box(1, 0, 20, 17, "L"),
+ text(11, 3, "FRESH", "l", { align: "c" }), text(11, 10, "HOT", "p", { align: "c" }),
+ line(3, 17, 1, 19, "W"), line(18, 17, 20, 19, "W"))
+
+sprite("mailbox", { w: 10, h: 16, outline: "k" },
+ rect(0, 0, 10, 7, "r"), rect(0, 7, 10, 3, "r"), hline(0, 9, 10, "P"),
+ hline(2, 3, 6, "k"), vline(4, 10, 6, "W"), vline(5, 10, 6, "V"), px(8, 1, "w"))
+
+// ---------------------------------------------------------------- scene
+scene("moon_buns", { w: 176, h: 168, bg: "B", layers: true },
+ layer("backdrop",
+ scatter("sparks", 0, 0, 176, 120, 26, { seed: 8 }),
+ // big soft moon behind
+ circ(150, 28, 16, "b"), circ(150, 28, 13, "c"), circ(156, 25, 11, "B"), circ(150, 28, 13, "c"),
+ circ(156, 25, 11, "B")),
+
+ layer("buildings",
+ stamp("chimney", 108, 17),
+ stamp("shop", 33, 49)),
+
+ layer("roof",
+ stamp("_cat", 50, 42), stamp("_bird", 152, 56),
+ stamp("_plant", 78, 43), stamp("_plant", 120, 43, { flip: "x" }),
+ // weather vane: a star on a pole
+ vline(64, 28, 21, "W"), hline(60, 34, 9, "W"), circ(64, 25, 3, "l"), px(64, 25, "w"), px(61, 27, "l"), px(67, 27, "l")),
+
+ layer("steam",
+ // rising steam from the chimney
+ stamp("_steam_a", 114, 12), stamp("_steam_a", 118, 6), stamp("_steam_a", 113, 1),
+ stamp("_steam_b", 121, 10), stamp("_steam_b", 110, 8)),
+
+ layer("street",
+ rect(0, 150, 176, 3, "W"), hline(0, 150, 176, "V"),
+ stamp("lamp", 8, 86), stamp("cart", 142, 128), stamp("board", 22, 130), stamp("mailbox", 128, 134),
+ stamp("_plant", 131, 143, { flip: "x" }),
+ wire(16, 90, 38, 54, 6, "W", { hang: "bulbs", every: 4, seed: 3 }),
+ wire(138, 54, 168, 60, 5, "W", { hang: "bulbs", every: 4, seed: 4 })),
+
+ layer("spill", { light: true },
+ poly([40, 150, 100, 150, 108, 156, 32, 156], "k"),
+ circ(16, 92, 8, "k")),
+ layer("halo", { light: true, density: 0.5 },
+ circ(16, 92, 18, "k"), poly([34, 150, 108, 150, 118, 160, 22, 160], "k")),
+)
diff --git a/examples/neon_noodle_3d.px.js b/examples/neon_noodle_3d.px.js
new file mode 100644
index 0000000..fddf474
--- /dev/null
+++ b/examples/neon_noodle_3d.px.js
@@ -0,0 +1,274 @@
+// "Neon Noodle": a steel-blue ramen bar on a rainy night street, 3/4 view (front, side, roof).
+pal({
+ k: "#0c0a1e", // ink
+ X: "#1f2f5a", x: "#2f4a8a", y: "#4a6cb8", Y: "#7fa0e0", // blue steel
+ e: "#6e6892", C: "#9a94b8", c: "#d4d0e4", // concrete
+ M: "#b01e70", m: "#ff3d9a", i: "#ffd0e8", // neon magenta
+ T: "#169aa8", t: "#2fe6e0", j: "#c4fffa", // neon cyan
+ A: "#c26a1e", a: "#ffb84a", l: "#fff0b0", // lantern amber
+ R: "#9a2038", r: "#e83a4a", // noren red
+ G: "#1f8a5a", g: "#4ade80", // plants
+ w: "#e8f0ff", // steam
+ N: "#141842", B: "#1e2a5e", b: "#2c3f86", d: "#26357a", // night sky / far city
+ z: "#14173a", s: "#3a4272", // road / sidewalk
+})
+ramps("kXxyY", "keCc", "kMmi", "kTtj", "kAal", "kRr", "kGg")
+
+// ---------------------------------------------------------------- parts
+sprite("_panel", `
+ xxxxxxxxxxxxxxxX
+ xyxxxxxxxxxxxxyX
+ xxxxxxxxxxxxxxxX
+ xxxxxxxxxxxxxxxX
+ xxxxxxxxxxxxxxxX
+ xyxxxxxxxxxxxxyX
+ xxxxxxxxxxxxxxxX
+ XXXXXXXXXXXXXXXX`)
+sprite("_tile", `
+ ccccccCe
+ ccccccCe
+ ccccccCe
+ ccccccCe
+ ccccccCe
+ ccccccCe
+ CCCCCCCe
+ eeeeeeee`)
+sprite("_bowl", `
+ .......
+ .lilil.
+ lllllll
+ .rrrrr.
+ .rrrrr.
+ ..RRR..
+ .......`)
+sprite("_noren", `
+ rrrrrrr
+ rrrrrrr
+ rrcccrr
+ rrrcrrr
+ rrcccrr
+ rrrrrrr
+ RRRRRRR
+ R.R.R.R`)
+sprite("_chef", `
+ ..jjj..
+ .jjjjj.
+ ..ccc..
+ .ckckc.
+ ..ccc..
+ .jjjjj.
+ jjjjjjj
+ jjjjjjj`)
+sprite("_stool", `
+ .mmmm.
+ .MMMM.
+ ..kk..
+ ..kk..
+ ..kk..
+ ..kk..
+ .k..k.
+ k....k`)
+sprite("_lantern", `
+ ..k..
+ .aaa.
+ allla
+ allla
+ .aaa.
+ ..A..`)
+sprite("_shrub", `
+ g.g.g
+ gGggG
+ .GGG.`)
+sprite("_pigeon", `
+ ..ee.
+ .eeee
+ eeee.
+ .k.k.`)
+sprite("_cat", `
+ k...k..
+ kk.kk..
+ kakak..
+ kkkkk..
+ .kkkk..
+ .kkkkk.
+ .kkkkkk`)
+sprite("_dish", { outline: "k" }, `
+ ....ee...
+ ..eCCCe..
+ .eCCCCCe.
+ eCCCCYYe.
+ eCCCYYe..
+ .eCYYe...
+ ..eYe....
+ ....e....
+ ....e....
+ ...eYe...
+ ..eYYYe..`)
+sprite("_steam_a", `
+ .w.
+ www
+ .w.`)
+sprite("_steam_b", "w")
+sprite("_bulb_t", "t\nT")
+sprite("_bulb_m", "m\nM")
+sprite("_bulb_a", "a\nA")
+group("bulbs", ["_bulb_t", "_bulb_m", "_bulb_a", "_bulb_m"])
+
+sprite("lamp", { w: 11, h: 60, outline: "k" },
+ vline(5, 8, 52, "e"), vline(4, 8, 52, "C"), rect(2, 56, 7, 4, "e"), hline(2, 56, 7, "C"),
+ rect(0, 0, 11, 6, "e"), rect(1, 2, 9, 4, "t"), rect(2, 3, 7, 2, "j"), hline(0, 0, 11, "C"))
+
+sprite("blade", { w: 12, h: 36, outline: "k" },
+ rect(0, 0, 12, 36, "k"), box(0, 0, 12, 36, "m"),
+ text(6, 4, "B\nA\nR", "t", { align: "c", lead: 3, shadow: "T" }), vline(6, 30, 5, "M"))
+
+// ---------------------------------------------------------------- 3/4 geometry
+const FX0 = 22, FX1 = 106, TOP = 58, BOT = 150, D = 30
+const sp = (u, y) => [FX1 + u, y - u / 2] // point on the side plane
+const sidePoly = (u0, u1, y0, y1) => // y relative to TOP
+ [...sp(u0, TOP + y0), ...sp(u1, TOP + y0), ...sp(u1, TOP + y1), ...sp(u0, TOP + y1)]
+const SIDE = [FX1, TOP, FX1 + D, TOP - D / 2, FX1 + D, BOT - D / 2, FX1, BOT]
+const ROOF = [FX0, TOP, FX1, TOP, FX1 + D, TOP - D / 2, FX0 + D, TOP - D / 2]
+const box3 = (x, y, w, h, d, f, s, t) => (c) => {
+ c.poly([x + w, y, x + w + d, y - d / 2, x + w + d, y + h - d / 2, x + w, y + h], s)
+ c.poly([x, y, x + w, y, x + w + d, y - d / 2, x + d, y - d / 2], t)
+ c.rect(x, y, w, h, f)
+}
+const sideLines = (y0, y1, step, col) => (c) => {
+ for (let y = TOP + y0; y <= TOP + y1; y += step) c.line(FX1, y, FX1 + D - 1, y - (D - 1) / 2, col)
+}
+const sideJoints = (y0, y1, step, col) => (c) => {
+ let r = 0
+ for (let y = TOP + y0; y < TOP + y1; y += step, r++)
+ for (let u = 4 + (r % 2) * 4; u < D; u += 8) c.vline(FX1 + u, y - Math.floor(u / 2) + 1, step - 1, col)
+}
+const vpipe = (u, y0, y1, col) => (c) => c.vline(FX1 + u, TOP + y0 - u / 2, y1 - y0, col)
+
+// ---------------------------------------------------------------- scene
+scene("neon_noodle_3d", { w: 192, h: 170, bg: "B", layers: true },
+ layer("backdrop",
+ grad(0, 0, 192, 135, "NNBBb", "v", 0.6),
+ circ(158, 26, 10, "c"), circ(162, 24, 2, "C"), circ(155, 30, 1, "C"),
+ // far skyline: lit windows sit on a regular grid
+ (c) => {
+ const r = c.rng(11)
+ for (let x = 0, i = 0; x < 192; i++) {
+ const w = 12 + Math.floor(r() * 10), h = 40 + Math.floor(r() * 50), y = 135 - h
+ c.rect(x, y, w, h, "d"); c.hline(x, y, w, "b")
+ for (let wy = y + 4; wy < 130; wy += 5)
+ for (let wx = x + 3; wx < x + w - 2; wx += 4)
+ if (r() < 0.22) c.px(wx, wy, r() < 0.5 ? "a" : "t")
+ x += w + 1
+ }
+ },
+ rect(0, 135, 192, 15, "s"), hline(0, 135, 192, "C"),
+ rect(0, 150, 192, 20, "z"), hline(0, 150, 192, "c"), hline(0, 151, 192, "e"),
+ (c) => { for (let x = 4; x < 192; x += 24) c.hline(x, 162, 12, "a") }),
+
+ layer("roof",
+ poly(ROOF, "y"),
+ line(FX0 + D, TOP - D / 2, FX1 + D, TOP - D / 2, "Y"), line(FX0, TOP, FX0 + D, TOP - D / 2, "Y"),
+ line(FX1, TOP, FX1 + D, TOP - D / 2, "Y"),
+ // water tank on legs
+ vline(36, 52, 4, "k"), vline(51, 52, 4, "k"), vline(44, 52, 4, "k"),
+ ellipse(44, 49, 9, 4, "e"), rect(35, 38, 19, 11, "C"), ellipse(44, 38, 9, 4, "c"),
+ hline(35, 42, 19, "e"), hline(35, 46, 19, "e"), shade([47, 38, 8, 14], 1),
+ stamp("_dish", 66, 44), box3(82, 50, 10, 5, 5, "x", "X", "y"),
+ // antenna mast with a warning light
+ vline(94, 26, 26, "e"), hline(90, 30, 9, "e"), hline(91, 36, 7, "e"), px(94, 25, "r"),
+ stamp("_pigeon", 24, 48), stamp("_cat", 112, 40), stamp("_shrub", 58, 52), stamp("_shrub", 126, 38)),
+
+ // ---- side face
+ layer("side",
+ poly(SIDE, "y"),
+ sideLines(8, 28, 8, "x"),
+ poly(sidePoly(0, D, 0, 3), "x"), poly(sidePoly(0, D, 3, 4), "Y"),
+ poly(sidePoly(0, D, 30, 33), "e"),
+ poly(sidePoly(0, D, 33, 84), "c"), sideLines(41, 83, 8, "C"), sideJoints(33, 84, 8, "C"),
+ poly(sidePoly(0, D, 84, 92), "y"),
+ // upstairs window with blinds
+ poly(sidePoly(14, 26, 8, 26), "k"), poly(sidePoly(15, 25, 9, 25), "a"),
+ poly(sidePoly(15, 25, 12, 13), "A"), poly(sidePoly(15, 25, 16, 17), "A"), poly(sidePoly(15, 25, 20, 21), "A"),
+ poly(sidePoly(13, 27, 26, 28), "C"),
+ // downstairs window, cyan tv glow
+ poly(sidePoly(16, 28, 40, 54), "k"), poly(sidePoly(17, 27, 41, 53), "T"), poly(sidePoly(17, 22, 41, 47), "t"),
+ // fire escape platform + rails
+ poly(sidePoly(1, 29, 58, 61), "k"), poly(sidePoly(1, 29, 58, 59), "e"),
+ poly(sidePoly(1, 29, 50, 51), "e"),
+ (c) => { for (let u = 1; u <= 29; u += 4) c.vline(FX1 + u, TOP + 50 - Math.floor(u / 2), 9, "e") },
+ // drainpipe + ladder
+ vpipe(13, -4, 92, "Y"), vpipe(12, -4, 92, "y"),
+ (c) => { for (let y = 62; y < 90; y += 4) c.hline(FX1 + 3, TOP + y - 1, 4, "C"); c.vline(FX1 + 3, TOP + 61, 30, "e"); c.vline(FX1 + 6, TOP + 61, 30, "e") },
+ shade(SIDE, 1)),
+
+ // ---- front face (local coords: x = FX0, y = TOP)
+ layer("front", { x: FX0, y: TOP },
+ pattern("_panel", 0, 0, 84, 30),
+ rect(0, 0, 84, 3, "X"), hline(0, 3, 84, "y"),
+ rect(0, 30, 84, 3, "e"), hline(0, 30, 84, "C"),
+ pattern("_tile", 0, 33, 84, 51),
+ rect(0, 84, 84, 8, "X"), hline(0, 84, 84, "y"),
+ (c) => { for (let x = 4; x < 80; x += 6) c.vline(x, 87, 4, "k") },
+ // neon sign plate: bowl icon + RAMEN / NOODLE
+ rect(5, 6, 54, 22, "k"), box(5, 6, 54, 22, "T"), px(6, 7, "t"), px(57, 7, "t"), px(6, 26, "t"), px(57, 26, "t"),
+ poly([8, 16, 20, 16, 18, 23, 10, 23], "m"), hline(8, 16, 13, "i"), line(11, 8, 16, 15, "j"), line(14, 8, 18, 15, "j"),
+ px(9, 10, "t"), px(12, 12, "T"),
+ text(41, 10, "RAMEN", "t", { align: "c", shadow: "T" }),
+ text(41, 18, "NOODLE", "m", { align: "c", shadow: "M" }),
+ // rooftop ac units on the front
+ rect(64, 6, 17, 10, "e"), box(64, 6, 17, 10, "C"), ring(70, 11, 3, "C"), circ(70, 11, 1, "k"), hline(75, 9, 4, "C"), hline(75, 12, 4, "C"),
+ rect(64, 18, 17, 9, "e"), box(64, 18, 17, 9, "C"), ring(70, 22, 3, "C"), circ(70, 22, 1, "k"), hline(75, 20, 4, "C"), hline(75, 23, 4, "C"),
+ // corner neon tube
+ vline(82, 4, 80, "m"), vline(83, 4, 80, "M"), vline(82, 20, 8, "i"),
+ // open front: frame, warm interior, shelf of bowls, chef, counter, stools
+ rect(3, 36, 54, 48, "X"), hline(3, 36, 54, "y"),
+ rect(5, 38, 50, 44, "k"), rect(6, 39, 48, 30, "A"), grad(6, 39, 48, 30, "Aaal", "v", 0.4),
+ hline(6, 55, 48, "e"), tile("_bowl", 9, 48, 6, 1, { seed: 3 }),
+ stamp("_chef", 24, 57),
+ rect(5, 65, 50, 7, "C"), hline(5, 65, 50, "c"), hline(5, 71, 50, "e"),
+ rect(5, 72, 50, 10, "e"), vline(18, 72, 10, "X"), vline(31, 72, 10, "X"), vline(44, 72, 10, "X"),
+ tile("_noren", 5, 38, 7, 1),
+ stamp("_stool", 12, 74), stamp("_stool", 26, 74), stamp("_stool", 40, 74),
+ // door with porthole and OPEN strip
+ rect(62, 33, 20, 8, "k"), box(62, 33, 20, 8, "m"), text(72, 35, "OPEN", "t", { align: "c" }),
+ rect(62, 41, 20, 43, "X"), rect(64, 43, 16, 41, "x"), hline(64, 62, 16, "X"),
+ circ(72, 53, 5, "T"), circ(70, 51, 2, "t"), ring(72, 53, 5, "y"), px(78, 70, "a"), px(78, 71, "a"),
+ // lantern string across the opening
+ wire(3, 38, 57, 38, 3, "k", { hang: "_lantern", every: 14, start: 6 })),
+
+ layer("awning_shadow", { shade: true }, rect(FX0 + 3, TOP + 46, 54, 2, "k")),
+ layer("roof_light", { light: true, density: 0.5 }, poly(ROOF, "k")),
+ // blade sign hanging off the corner
+ layer("blade", stamp("blade", FX1 + 2, TOP + 6)),
+
+ layer("cast", { shade: true },
+ poly([FX1, BOT, FX1 + D, BOT - D / 2, FX1 + D + 28, BOT - D / 2, FX1 + 28, BOT], "k")),
+
+ layer("street",
+ stamp("lamp", 5, 92), stamp("lamp", 178, 86, { flip: "x" }),
+ // vending machine, bin
+ box3(150, 118, 14, 30, 6, "T", "X", "t"), rect(152, 121, 10, 16, "k"),
+ (c) => {
+ const cols = ["m", "a", "t", "r"]
+ for (let ry = 0; ry < 3; ry++) for (let rx = 0; rx < 4; rx++) c.rect(153 + rx * 2 + (rx > 1 ? 0 : 0), 123 + ry * 5, 1, 3, cols[(rx + ry) % 4])
+ },
+ rect(152, 140, 10, 5, "k"), px(160, 130, "a"),
+ box3(138, 138, 8, 10, 3, "e", "X", "C"), hline(138, 138, 8, "c"),
+ // puddles with neon reflections
+ ellipse(52, 158, 16, 2, "T"), hline(44, 158, 8, "t"), ellipse(48, 160, 4, 1, "m"),
+ ellipse(138, 164, 12, 2, "M"), hline(132, 164, 6, "m"),
+ // manhole + steam
+ ellipse(104, 155, 8, 2, "X"), hline(98, 155, 12, "y"),
+ stamp("_steam_a", 102, 148), stamp("_steam_a", 106, 142), stamp("_steam_b", 100, 140), stamp("_steam_b", 108, 136), stamp("_steam_a", 101, 131), stamp("_steam_b", 105, 127),
+ stamp("_shrub", 14, 146),
+ wire(FX1 + D, TOP - D / 2, 184, 90, 9, "e", { hang: "bulbs", every: 4, seed: 3 }),
+ wire(10, 97, FX0, TOP + 3, 4, "e", { hang: "bulbs", every: 4, seed: 6 })),
+
+ // neon + window spill on the sidewalk, antenna light, soft halo in the night air
+ layer("spill", { light: true },
+ poly([FX0 + 5, BOT, FX0 + 55, BOT, FX0 + 68, BOT + 8, FX0 - 6, BOT + 8], "k"),
+ circ(94, 25, 2, "k")),
+ layer("halo", { light: true, density: 0.5 },
+ circ(FX0 + 32, TOP + 17, 24, "k"), circ(FX0 + 30, TOP + 60, 28, "k"),
+ circ(10, 94, 14, "k"), circ(182, 88, 14, "k"), circ(94, 25, 6, "k")),
+)
diff --git a/examples/no_magic.px.js b/examples/no_magic.px.js
new file mode 100644
index 0000000..1429c11
--- /dev/null
+++ b/examples/no_magic.px.js
@@ -0,0 +1,1005 @@
+// "No Magic!": the witch went out for the evening and left her apprentice three chores.
+// The cat was not fed, the floor was not swept, and the spellbook came off the shelf.
+// The robe is in a heap by the cauldron; the apprentice (glasses and all) is now a frog,
+// hunting through the book for the way back, while the hungry cat gets ready to pounce.
+// The clock says 11:55. "no_magic" is the flat palette version, "no_magic_night" is lamp-lit;
+// both animate (fire, candles, bubbles, the cat's tail, the frog blinking, the pendulum).
+pal({
+ k: "#1a1220", K: "#2b1f35", // ink, deep shadow
+ j: "#1f3238", T: "#2b4a50", t: "#3a6266", y: "#4f7d7c", // teal wallpaper
+ P: "#4a2c40", p: "#643b52", m: "#7d4f62", M: "#966a74", // plum floorboards
+ e: "#3b2324", W: "#5c3832", w: "#7d5040", u: "#9d6c50", // walnut furniture
+ S: "#3d3a4c", s: "#5a5770", i: "#7c7a92", I: "#a3a2b6", // stone, iron
+ B: "#8a7a68", C: "#b8a890", c: "#ddd0b0", x: "#f4ecd2", // paper, chalk, bone
+ A: "#8a5a24", a: "#d39a3a", l: "#f5cf6a", L: "#fff4b8", // brass, candle light
+ H: "#b83a2e", h: "#e8702e", // fire, pumpkin
+ Z: "#1f5a3a", G: "#2f9a4e", g: "#6fd85a", z: "#c8ff9a", // the potion
+ R: "#7a2e48", r: "#b84a62", q: "#e07a88", // rose cloth
+ F: "#46702e", f: "#6a9a3a", v: "#9cc45a", // frog, leaves
+ N: "#141a3a", n: "#22305e", b: "#3d5a9a", o: "#6f8fd0", // night, apprentice blue
+ Q: "#f6f1d5", Y: "#f8e45c", // moon, eyeshine (both glow in the dark)
+})
+ramps("kKPpmM", "kjTty", "keWwu", "kSsiI", "SBCcx", "eAalL", "kRrq", "RHh", "kZGgz", "kFfv", "kNnbo")
+
+const FLOOR = 80 // the back wall meets the floor here
+
+// ================================================================ room shell
+sprite("_paper", { w: 12, h: 12 },
+ rect(0, 0, 12, 12, "t"), vline(0, 0, 12, "T"),
+ px(6, 2, "y"), px(5, 3, "y"), px(7, 3, "y"), px(6, 4, "y"),
+ px(6, 9, "T"))
+
+sprite("_wainscot", { w: 24, h: 22 },
+ rect(0, 0, 24, 22, "w"),
+ hline(0, 0, 24, "u"), hline(0, 2, 24, "W"), // top rail
+ hline(3, 5, 21, "W"), vline(3, 5, 11, "W"), // inset panel: shadowed top/left
+ hline(4, 15, 20, "u"), vline(23, 6, 10, "u"), // lit bottom/right
+ rect(0, 18, 24, 4, "W"), hline(0, 18, 24, "u"), hline(0, 21, 24, "e")) // baseboard
+
+sprite("floor", { w: 256, h: 144 }, (c) => {
+ const r = c.rng(7)
+ for (let y = 0; y < 144; y += 8) {
+ let x = -Math.floor(r() * 44)
+ while (x < 256) {
+ const len = 30 + Math.floor(r() * 34)
+ const lit = r() < 0.2
+ c.rect(x, y, len, 7, lit ? "m" : "p")
+ c.hline(x, y, len, lit ? "M" : "m")
+ c.hline(x, y + 7, len, "P")
+ c.vline(x + len - 1, y, 7, "P")
+ c.px(x + 1, y + 2, "P"); c.px(x + 1, y + 5, "P") // nails at the board end
+ x += len
+ }
+ }
+})
+
+sprite("cobweb", `
+ CCCCCCCCCCC
+ CB.C..C.B.
+ C.CB.C..C
+ C.BCC..C
+ CC..CBC
+ C.C.CC
+ C..CB
+ C.BC
+ CCC
+ CB
+ C`)
+
+// ================================================================ back wall
+sprite("_curtain", `
+ rrrRrq...
+ rrrRrqr..
+ rrRrrqrR.
+ rrRrrqrR.
+ rrRrrqrR.
+ rrRrrqrRr
+ rrRrrqrRr
+ rrRrrqrRr
+ rrRrrqrRr
+ rrRrrqrRr
+ rrRrrqrR.
+ rrRrrqr..
+ rrRrrqr..
+ rrRrqr...
+ rRrqr....
+ rRrqr....
+ aaAaa....
+ rRrqr....
+ rRrqr....
+ rRrqrr...
+ rRrqrr...
+ rRRrqrr..
+ rRRrqrr..
+ rRRrqrrR.
+ rRRrqrrRr
+ rRRrqrrRr
+ RRRrRqrRr
+ .RRRRRRRR`)
+
+sprite("_flytrap", `
+ .x.x....
+ frrf.x.x
+ .ff.frrf
+ ..f..ff.
+ ..ff.f..
+ ...ff...
+ .RRRRRR.
+ .rqrrrr.
+ ..rrrR..`)
+
+sprite("window", { w: 44, h: 50, outline: "k" },
+ // night outside
+ grad(9, 6, 26, 32, "NNnn", "v", 0.6),
+ circ(15, 13, 5, "c"), circ(15, 13, 4, "Q"), px(13, 12, "c"), px(17, 15, "c"), px(16, 11, "c"),
+ px(28, 9, "x"), px(31, 16, "c"), px(25, 22, "c"), px(11, 25, "c"), px(30, 27, "x"),
+ poly([9, 38, 9, 31, 15, 28, 22, 31, 28, 27, 35, 30, 35, 38], "K"),
+ vline(26, 25, 3, "K"), px(25, 26, "K"), px(27, 26, "K"), // a lonely tree on the hill
+ // frame and mullions
+ box(6, 3, 32, 38, "w"), box(7, 4, 30, 36, "w"), hline(8, 5, 28, "W"), vline(8, 5, 34, "W"),
+ vline(21, 5, 34, "w"), vline(22, 5, 34, "W"), hline(8, 21, 28, "w"), hline(8, 22, 28, "W"),
+ hline(6, 3, 32, "u"),
+ // sill
+ rect(3, 41, 38, 2, "u"), rect(3, 43, 38, 2, "w"), hline(3, 45, 38, "W"),
+ stamp("_flytrap", 27, 32),
+ // curtain rod and curtains
+ hline(0, 1, 44, "S"), hline(0, 0, 44, "i"), rect(0, 0, 2, 3, "a"), rect(42, 0, 2, 3, "a"),
+ stamp("_curtain", 1, 2), stamp("_curtain", 34, 2, { flip: "x" }))
+
+sprite("_herb_a", `
+ .A.
+ .F.
+ FfF
+ bFb
+ obo
+ bob
+ .b.`)
+sprite("_herb_b", `
+ .A.
+ .F.
+ fFf
+ vfv
+ fvf
+ .f.
+ .F.`)
+sprite("_garlic", `
+ .A.
+ .C.
+ CxC
+ cxc
+ xcx
+ .C.`)
+sprite("_chili", `
+ .F.
+ .H.
+ .H.
+ .h.
+ ..H`)
+group("herbs", ["_herb_a", "_herb_b", "_herb_b", "_garlic", "_chili"])
+
+sprite("chalkboard", { w: 48, h: 28, outline: "k" },
+ rect(0, 0, 48, 26, "w"), hline(0, 0, 48, "u"), rect(2, 2, 44, 22, "j"),
+ hline(2, 2, 44, "k"),
+ // three chores, three empty boxes
+ box(4, 4, 4, 4, "C"), text(10, 4, "FEED CAT", "c"),
+ box(4, 10, 4, 4, "C"), text(10, 10, "SWEEP", "c"),
+ box(4, 16, 4, 4, "C"), text(10, 16, "NO MAGIC!", "q"), hline(10, 22, 35, "r"),
+ // tray: eraser, no chalk
+ rect(1, 25, 46, 2, "u"), hline(1, 27, 46, "W"), rect(34, 23, 7, 2, "B"), hline(34, 23, 7, "C"))
+
+sprite("_jar_eyes", `
+ .WW.
+ CxxC
+ xkxC
+ CxkC
+ xkxC
+ CCCC`)
+sprite("_jar_glow", `
+ .WW.
+ GzzG
+ GgzG
+ GggG
+ GgGG
+ ZGGZ`)
+sprite("_jar_red", `
+ .uu.
+ .II.
+ IrrI
+ IrqI
+ IRrI
+ IRRI`)
+sprite("_jar_shroom", `
+ .ee.
+ sCCs
+ sqrs
+ sxqs
+ sCCs
+ ssss`)
+sprite("_bottle", `
+ .u.
+ .b.
+ .b.
+ bob
+ bnb
+ nnn`)
+group("jars", ["_jar_eyes", "_jar_glow", "_jar_red", "_jar_shroom", "_bottle"])
+
+sprite("jar_shelf", { w: 46, h: 13, outline: "k" },
+ stamp("_jar_glow", 2, 0), stamp("_jar_eyes", 7, 0), stamp("_bottle", 13, 0), stamp("_jar_red", 17, 0),
+ stamp("_jar_shroom", 23, 0), stamp("_bottle", 29, 0, { swap: { b: "r", o: "q", n: "R" } }),
+ stamp("_jar_glow", 33, 0, { swap: { G: "b", g: "o", z: "x", Z: "n" } }), stamp("_jar_eyes", 38, 0),
+ rect(0, 6, 46, 1, "u"), rect(0, 7, 46, 2, "w"), hline(0, 9, 46, "W"),
+ poly([4, 10, 9, 10, 5, 13], "W"), poly([37, 10, 42, 10, 41, 13], "W"))
+
+sprite("portrait", { outline: "k" }, `
+ AaaaaaaaaaaaaaaaaA
+ aAAAAAAAAAAAAAAAAa
+ aAnnnnnnnnnnnnnnAa
+ aAnnnnnnnnKKnnnnAa
+ aAnnnnnnnKKnnnnnAa
+ aAnnnnnnKKnnnnnnAa
+ aAnnnnnKKKKnnnnnAa
+ aAnnnnKKKKKKnnnnAa
+ aAnnnnRRaRRRnnnnAa
+ aAnnKKKKKKKKKKnnAa
+ aAnnnIcccccIInnnAa
+ aAnnnIckcckcInnnAa
+ aAnnnIccccCcInnnAa
+ aAnnnIcRRRccInnnAa
+ aAnnnIIccccIInnnAa
+ aAnnnIPPxxPPInnnAa
+ aAnnPPPPaPPPPPnnAa
+ aAnnPPPPPPPPPPnnAa
+ aAAAAAAAAAAAAAAAAa
+ aaaaaaaaaaaaaaaaaa`)
+
+// irregular fieldstone courses, mortar below and right of every stone
+const stonework = (x0, y0, w, h, seed) => clip([x0, y0, w, h], (c) => {
+ const r = c.rng(seed)
+ for (let y = y0, row = 0; y < y0 + h; y += 6, row++) {
+ let x = x0 - 3 - (row % 2) * 4 - Math.floor(r() * 3)
+ while (x < x0 + w) {
+ const bw = 6 + Math.floor(r() * 6), pale = r() < 0.2
+ c.rect(x, y, bw, 5, pale ? "i" : "s"); c.hline(x, y, bw - 2, pale ? "I" : "i")
+ c.vline(x + bw - 1, y, 6, "S"); c.hline(x, y + 5, bw, "S")
+ x += bw
+ }
+ }
+})
+const ARCH = (x, y) => y >= 58 || (x - 26.5) ** 2 / 144 + (y - 58) ** 2 / 100 <= 1
+
+// flames: each tongue rises and falls on its own beat; 6 frames at 10 fps loop seamlessly
+anim("_fire", { w: 22, h: 23, frames: 6, fps: 10 }, (c) => {
+ const k = c.phase * Math.PI * 2, y = 21
+ const up = (h, amp, off) => y - Math.round(h + Math.sin(k + off) * amp)
+ c.poly([2, y, 4, up(9, 2, 0), 7, up(6, 1, 2), 10, up(17, 2, 1), 13, up(9, 2, 3), 16, up(13, 2, 4.5), 19, y], "H")
+ c.poly([4, y, 7, up(7, 1, 1), 10, up(12, 2, 2.5), 12, up(7, 1, 0.5), 15, up(9, 2, 4), 17, y], "h")
+ c.poly([6, y, 9, up(6, 1, 3), 11, up(9, 1, 1.2), 13, up(5, 1, 2), 15, y], "a")
+ c.poly([8, y + 1, 10, up(4, 1, 0.7), 12, up(2, 1, 2.2), 13, y + 1], "l")
+})
+
+sprite("hearth", { w: 54, h: 84, outline: "k" },
+ // chimney breast up to the beam
+ stonework(7, 0, 40, 34, 3), vline(7, 0, 34, "S"), vline(46, 0, 34, "S"),
+ // firebox surround, sooted above the opening
+ stonework(3, 38, 48, 46, 8),
+ shade([12, 39, 30, 12], 1, 0.5), shade([17, 41, 20, 6], 1, 0.5),
+ // the opening: sooty back bricks, andirons, logs, flames
+ clip(ARCH,
+ rect(14, 46, 26, 38, "e"), rect(14, 46, 26, 6, "K"),
+ (c) => {
+ for (let y = 53, row = 0; y < 82; y += 4, row++) {
+ c.hline(14, y, 26, "K")
+ for (let x = 14 + (row % 2) * 3; x < 40; x += 6) c.vline(x, y + 1, 3, "K")
+ }
+ }),
+ (c) => { for (let a = 0; a <= 12; a++) { // voussoir stones round the arch
+ const t = Math.PI * (a / 12), x = 26.5 - Math.cos(t) * 13.5, y = 58 - Math.sin(t) * 11
+ c.px(Math.round(x), Math.round(y), a % 2 ? "I" : "i"); c.px(Math.round(x - Math.cos(t)), Math.round(y - Math.sin(t)), "s")
+ } },
+ rect(23, 44, 8, 5, "i"), hline(23, 44, 8, "I"), box(23, 44, 8, 5, "S"), // keystone
+ line(16, 81, 37, 77, "W", 3), line(17, 77, 36, 81, "e", 3), circ(16, 80, 1, "u"), circ(37, 78, 1, "u"),
+ stamp("_fire", 16, 58),
+ vline(15, 74, 8, "k"), vline(38, 74, 8, "k"), hline(14, 74, 3, "k"), hline(37, 74, 3, "k"),
+ hline(14, 82, 26, "S"), hline(14, 83, 26, "s"),
+ // mantel shelf with corbels
+ rect(0, 34, 54, 2, "u"), rect(0, 36, 54, 3, "w"), hline(0, 39, 54, "W"),
+ rect(4, 40, 4, 4, "w"), hline(4, 43, 4, "W"), rect(46, 40, 4, 4, "w"), hline(46, 43, 4, "W"))
+
+anim("clock", { outline: "k", fps: 10 }, `
+ ....AaA....
+ ...AwuwA...
+ ..WwwuwwW..
+ .WwwxxxwwW.
+ .WwxxxxxwW.
+ .WxxxxxxxW.
+ .WxxxxxxxW.
+ .WxxxxxxxW.
+ .WwxxxxxwW.
+ .WwwxxxwwW.
+ ..WwwwwwW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WKKKKKW..
+ ..WwwwwwW..
+ ...WWWWW...
+ ....WwW....
+ .....W.....`,
+ // 11:55, five minutes until she's home
+ vline(5, 4, 3, "k"), px(4, 4, "k"), px(5, 7, "k"), px(4, 6, "K"), px(6, 7, "a"),
+ // tick... tock
+ frame({ hold: 6 }, line(5, 11, 4, 14, "A"), rect(3, 15, 2, 2, "a"), px(3, 15, "l")),
+ frame({ hold: 6 }, line(5, 11, 6, 14, "A"), rect(6, 15, 2, 2, "a"), px(6, 15, "l")))
+
+sprite("door", { w: 34, h: 66, outline: "k" },
+ ellipse(17, 14, 16, 14, "W"), rect(1, 14, 32, 52, "W"), // stone-dark frame
+ ellipse(17, 14, 14, 12, "w"), rect(3, 14, 28, 52, "w"),
+ clip((x, y) => y >= 14 || (x - 17) ** 2 / 196 + (y - 14) ** 2 / 144 <= 1,
+ (c) => { for (let x = 9; x < 31; x += 6) { c.vline(x, 0, 66, "W"); c.vline(x + 1, 0, 66, "u") } },
+ rect(3, 18, 28, 3, "S"), hline(3, 18, 28, "i"), rect(3, 50, 28, 3, "S"), hline(3, 50, 28, "i"),
+ px(5, 19, "I"), px(28, 19, "I"), px(5, 51, "I"), px(28, 51, "I")),
+ // round window
+ circ(17, 11, 5, "W"), circ(17, 11, 4, "n"), px(15, 9, "o"), px(16, 9, "o"), px(15, 10, "o"), vline(17, 7, 9, "W"), hline(13, 11, 9, "W"),
+ // ring handle, keyhole
+ ring(26, 36, 2, "a"), px(25, 34, "l"), px(26, 41, "K"), px(26, 42, "K"),
+ // the note she pinned on her way out
+ rect(6, 26, 9, 11, "c"), hline(6, 36, 9, "C"), px(10, 26, "r"),
+ hline(7, 28, 6, "B"), hline(7, 30, 7, "B"), hline(7, 32, 5, "B"), hline(10, 34, 4, "R"),
+ rect(1, 64, 32, 2, "S"))
+
+sprite("horseshoe", { outline: "k" }, `
+ i...i
+ I...i
+ I...s
+ .Iis.`)
+
+sprite("broom", { w: 15, h: 47, outline: "k" }, (c) => {
+ c.line(11, 0, 6, 32, "u", 2); c.line(12, 0, 7, 32, "W")
+ c.poly([2, 46, 4, 34, 9, 33, 12, 46], "a")
+ c.line(5, 36, 4, 46, "A"); c.line(8, 36, 8, 46, "A"); c.line(10, 37, 11, 46, "l")
+ c.rect(4, 32, 6, 3, "R"); c.hline(4, 32, 6, "r")
+ // nobody has used it in ages
+ c.line(9, 6, 14, 3, "C"); c.line(9, 10, 14, 8, "C"); c.line(12, 4, 12, 9, "B")
+})
+
+// ================================================================ fireplace and floor around it
+sprite("hearthstone", { w: 62, h: 10, outline: "k" },
+ rect(0, 0, 62, 8, "s"), hline(0, 0, 62, "i"),
+ vline(20, 0, 8, "S"), vline(41, 0, 8, "S"), hline(0, 4, 62, "S"), vline(10, 4, 4, "S"), vline(31, 4, 4, "S"), vline(51, 4, 4, "S"),
+ rect(0, 8, 62, 2, "S"))
+
+sprite("logs", { w: 21, h: 17, outline: "k" }, (c) => {
+ const end = (x, y) => { c.circ(x, y, 3, "W"); c.circ(x, y, 2, "u"); c.px(x, y, "w"); c.px(x - 1, y - 1, "c") }
+ c.rect(4, 1, 14, 7, "W"); c.hline(4, 1, 14, "w"); c.hline(5, 3, 4, "e"); c.hline(12, 4, 4, "e") // bark, running back
+ c.rect(0, 6, 21, 5, "W"); c.hline(1, 7, 3, "e"); c.hline(17, 8, 3, "e")
+ end(7, 8); end(14, 8)
+ end(3, 13); end(10, 13); end(17, 13)
+})
+
+sprite("bowl", { outline: "k" }, `
+ ..qqqqqqq..
+ .qRRRRRRRq.
+ .rqqqqqqqr.
+ ..rrrxrrr..
+ ...RRRRR...`)
+
+// ================================================================ the spell
+sprite("cauldron", { w: 42, h: 36, outline: "k" },
+ // feet
+ rect(7, 30, 5, 5, "S"), rect(19, 32, 5, 4, "S"), rect(30, 30, 5, 5, "S"),
+ // pot
+ ellipse(21, 21, 19, 12, "S"), ellipse(19, 18, 15, 9, "s"), ellipse(15, 15, 7, 4, "i"),
+ clip([0, 24, 42, 12], ellipse(21, 21, 19, 12, "K")),
+ ring(1, 13, 2, "s"), ring(41, 13, 2, "s"),
+ // rim and the potion inside
+ ellipse(21, 11, 18, 5, "i"), ellipse(21, 11, 18, 5, "S", true), hline(6, 7, 30, "I"),
+ ellipse(21, 11, 15, 3, "G"), ellipse(20, 10, 11, 2, "g"),
+ circ(13, 10, 1, "z"), ring(27, 9, 2, "z"), px(27, 9, "g"), px(19, 11, "z"), px(31, 11, "G"),
+ // it's boiling over the front
+ (c) => {
+ const drips = [[8, 6], [12, 13], [17, 4], [22, 17], [26, 7], [31, 11], [35, 5]]
+ for (const [x, len] of drips) {
+ c.vline(x, 14, len, "g"); c.vline(x + 1, 14, len, "G"); c.px(x, 14 + len, "G"); c.px(x + 1, 14 + len, "Z")
+ }
+ c.hline(5, 14, 32, "g")
+ },
+ // bubbles rising out
+ ring(14, 2, 1, "z"), px(24, 1, "g"), px(30, 3, "z"), px(9, 5, "g"))
+
+sprite("goo", { w: 80, h: 32, outline: "Z" },
+ ellipse(46, 6, 12, 4, "G"),
+ ellipse(36, 15, 28, 8, "G"), ellipse(14, 21, 12, 6, "G"), ellipse(56, 21, 14, 6, "G"),
+ ellipse(30, 25, 10, 4, "G"), circ(72, 25, 2, "G"), circ(4, 13, 1, "G"), circ(76, 18, 1, "G"),
+ ellipse(34, 13, 16, 4, "g"), ellipse(12, 19, 6, 2, "g"), ellipse(54, 19, 7, 2, "g"),
+ hline(30, 11, 6, "z"), px(10, 18, "z"), px(52, 18, "z"), px(44, 5, "g"), hline(42, 4, 5, "g"))
+
+sprite("_shroom_a", `
+ .qq.
+ qxqq
+ .xC.`)
+sprite("_shroom_b", `
+ qrq
+ .x.`)
+sprite("_shroom_c", `
+ .zz.
+ zggz
+ .xC.`)
+group("shrooms", ["_shroom_a", "_shroom_b", "_shroom_b", "_shroom_c"])
+
+sprite("chalk_circle", { w: 92, h: 44 },
+ ellipse(46, 22, 45, 21, "c", true), ellipse(46, 22, 41, 18, "C", true),
+ // runes between the two rings
+ grid(44, 1, "c.c\n.c."), grid(44, 40, ".c.\nc.c"), grid(2, 21, "c\ncc\nc"), grid(88, 21, ".c\ncc\n.c"),
+ grid(14, 6, "cc\n.c"), grid(75, 6, "cc\nc."), grid(14, 36, ".c\ncc"), grid(75, 36, "c.\ncc"),
+ // scuffed where someone stepped through
+ recolor({ c: "_", C: "_" }, [62, 30, 18, 14], 0.5))
+
+anim("candle", { outline: "k", fps: 5 }, `
+ .l.
+ lLl
+ .a.
+ xxx
+ cxc
+ cxc
+ CCC`,
+ frame(), frame(grid(0, 0, "l_.\n_Ll")), frame(grid(0, 0, "._l\nlL_")))
+sprite("candle_out", { outline: "k" }, `
+ ..k....
+ xxxxxcB
+ cccccCB
+ .CCCC..`)
+sprite("chalk", "xxc")
+
+// knocked over by the blast: seat on its edge, three legs in the air
+sprite("stool", { w: 21, h: 15, outline: "k" },
+ line(5, 7, 16, 7, "e", 2),
+ line(6, 3, 19, 1, "W", 2), line(6, 11, 19, 13, "W", 2), hline(7, 2, 11, "w"), hline(7, 11, 11, "w"),
+ line(14, 2, 14, 12, "W"),
+ ellipse(4, 7, 4, 7, "W"), ellipse(4, 7, 3, 6, "u"), ellipse(3, 6, 1, 3, "c"))
+
+// ================================================================ what's left of the apprentice
+sprite("clothes", { w: 38, h: 21, outline: "k" },
+ // robe in a heap, one sleeve flung out
+ ellipse(15, 15, 14, 5, "n"), ellipse(14, 13, 12, 5, "b"), ellipse(9, 11, 6, 3, "o"),
+ line(4, 15, 12, 13, "n"), line(16, 16, 24, 14, "n"), line(12, 10, 18, 11, "n"),
+ line(26, 15, 34, 18, "b", 3), line(26, 14, 34, 17, "o"), line(27, 17, 34, 19, "n"),
+ rect(35, 17, 2, 3, "x"), // lace cuff
+ hline(5, 10, 3, "x"), px(8, 9, "x"), px(4, 11, "x"), // lace collar
+ // her pointy hat, fallen on its side, the tip still bent
+ ellipse(14, 6, 2, 6, "N"),
+ poly([15, 1, 27, 4, 33, 0, 31, 5, 15, 12], "n"), poly([16, 3, 27, 5, 31, 2, 29, 5, 16, 6], "b"),
+ poly([16, 1, 19, 2, 19, 11, 16, 12], "a"), vline(17, 2, 9, "l"), px(25, 8, "l"),
+ // shoes
+ ellipse(3, 19, 3, 1, "W"), ellipse(9, 20, 3, 1, "W"), px(2, 18, "u"), px(8, 19, "u"))
+
+sprite("wand", { outline: "k" }, `
+ .........l.
+ ........lLl
+ ......Wu.l.
+ ....Wu.....
+ ..Wu.......
+ Wu.........`)
+
+sprite("spellbook", { w: 28, h: 15, outline: "k" },
+ poly([0, 12, 3, 2, 14, 2, 14, 12], "R"), poly([14, 2, 25, 2, 28, 12, 14, 12], "R"),
+ rect(0, 12, 28, 3, "R"), hline(0, 12, 28, "r"),
+ poly([2, 11, 4, 1, 13, 1, 13, 11], "c"), poly([14, 1, 23, 1, 25, 11, 14, 11], "x"),
+ vline(13, 1, 11, "C"), vline(14, 1, 11, "c"),
+ hline(5, 3, 7, "B"), hline(5, 5, 6, "B"), hline(4, 7, 7, "B"), hline(4, 9, 5, "B"),
+ // the page is a frog diagram with a glowing circle
+ ring(19, 5, 3, "G"), px(18, 4, "F"), px(20, 4, "F"), hline(18, 5, 3, "f"), hline(18, 6, 3, "F"),
+ hline(16, 9, 7, "B"), hline(17, 10, 5, "B"),
+ rect(20, 12, 2, 3, "q"))
+
+// written as the left half; the gold rims are the apprentice's glasses
+anim("frog", { mx: true, outline: "k" }, `
+ .aaa..
+ axxxa.
+ axkxaa
+ .aaaff
+ ffffff
+ fFFFFF
+ .fvvvv
+ ffvvvv
+ FFf...`,
+ frame({ ms: 2200 }), frame({ ms: 200 }, grid(1, 1, "fff\nfff")))
+
+// low on its elbows, rump up, tail tip twitching: about to pounce
+anim("cat", { outline: "k" }, `
+ .......................sK.
+ ........................K.
+ .s...s..................K.
+ .Ks.sKs........sssss...K..
+ .KKKKKK......ssKKKKKs.Ks..
+ KKKKKKKs...ssKKKKKKKKKK...
+ KkYKKkYKsssKKKKKKKKKKKK...
+ KKKKKKKKKKKKKKKKKKKKKKK...
+ .KKqKKrKKKKKKKKKKKKKKKK...
+ ..KKKKrKKKKKKKKKKKKKKKK...
+ ...KKKaKKKKKKKKKKKKKKK....
+ .KKKKK.KKKK...KKKKKKK.....
+ KKKKK.KKK....KKKKKKK......`,
+ frame({ ms: 300 }), frame({ ms: 300 }, grid(23, 0, "__K")), frame({ ms: 300 }, grid(23, 0, "_K")),
+ frame({ ms: 300 }, grid(22, 0, "sK_")))
+
+// ================================================================ furniture
+const BOOKS = ["rR", "bn", "aA", "fF", "MP", "CB", "uW", "qr", "on", "GZ"]
+const books = (x0, x1, yb, hmax, seed, gaps = []) => (c) => {
+ const r = c.rng(seed)
+ for (let x = x0; x < x1;) {
+ const g = gaps.find(([gx]) => gx === x)
+ if (g) { x += g[1]; continue }
+ const bw = Math.min(r() < 0.35 ? 3 : 2, x1 - x), bh = hmax - Math.floor(r() * 4)
+ const [m, d] = BOOKS[Math.floor(r() * BOOKS.length)]
+ c.rect(x, yb - bh + 1, bw, bh, m); c.vline(x + bw - 1, yb - bh + 1, bh, d)
+ if (bw === 3 || r() < 0.4) c.hline(x, yb - bh + 3, bw - 1, r() < 0.5 ? "l" : "x")
+ x += bw
+ }
+}
+
+sprite("_skull", `
+ .cxxc.
+ cxxxxC
+ xkxxkC
+ cxxxxC
+ .cKKC.
+ .cxcC.`)
+
+sprite("bookshelf", { w: 36, h: 66, outline: "k" },
+ rect(0, 0, 36, 66, "w"),
+ rect(0, 0, 36, 4, "u"), hline(0, 4, 36, "W"), vline(0, 5, 61, "u"),
+ rect(3, 6, 30, 13, "e"), rect(3, 22, 30, 13, "e"), rect(3, 38, 30, 13, "e"),
+ books(3, 22, 18, 12, 2), stamp("_skull", 24, 13), stamp("_bottle", 30, 13),
+ books(3, 33, 34, 12, 5, [[13, 5]]), // the spellbook's empty slot
+ books(3, 11, 50, 11, 9), stamp("_jar_glow", 12, 45), stamp("_jar_red", 17, 45),
+ rect(23, 48, 9, 3, "b"), hline(23, 48, 9, "o"), rect(24, 45, 8, 3, "R"), hline(24, 45, 8, "r"), // lying books
+ hline(3, 6, 30, "k"), hline(3, 22, 30, "k"), hline(3, 38, 30, "k"),
+ rect(2, 19, 32, 3, "w"), hline(2, 19, 32, "u"), hline(2, 21, 32, "W"),
+ rect(2, 35, 32, 3, "w"), hline(2, 35, 32, "u"), hline(2, 37, 32, "W"),
+ rect(2, 51, 32, 3, "w"), hline(2, 51, 32, "u"), hline(2, 53, 32, "W"),
+ box(3, 55, 14, 10, "W"), box(19, 55, 14, 10, "W"), px(15, 60, "a"), px(21, 60, "a"))
+
+sprite("table", { w: 56, h: 32, outline: "k" },
+ rect(0, 0, 56, 14, "u"), hline(0, 4, 56, "w"), hline(0, 9, 56, "w"), hline(0, 0, 56, "w"),
+ rect(0, 14, 56, 5, "w"), hline(0, 14, 56, "u"), hline(0, 18, 56, "W"),
+ rect(22, 15, 12, 3, "W"), px(27, 16, "a"), px(28, 16, "a"), // drawer
+ rect(8, 19, 3, 8, "e"), rect(45, 19, 3, 8, "e"), // back legs
+ rect(2, 19, 4, 13, "W"), vline(2, 19, 13, "w"), rect(50, 19, 4, 13, "W"), vline(50, 19, 13, "w"),
+ hline(6, 27, 44, "e"))
+
+sprite("mortar", { outline: "k" }, `
+ .....u..
+ ....u...
+ .iiiIii.
+ isSSSSsi
+ sssssss.
+ .sssss..
+ ..SSS...`)
+anim("candle_tall", { outline: "k", fps: 5 }, `
+ ..l..
+ .lLl.
+ ..a..
+ .xxx.
+ .cxc.
+ .cxx.
+ .cxc.
+ .cxc.
+ .CcC.
+ aAAAa
+ .aAa.`,
+ frame(), frame(grid(1, 0, "l_\n_Ll")), frame(grid(1, 0, "._l\n.L_")))
+sprite("scale", { outline: "k" }, `
+ ......A......
+ AAAAAAaAAAAAA
+ a.....a.....a
+ a.....a.....a
+ aaa...a...aaa
+ AAA...a...AAA
+ ......a......
+ ....AAaAA....`)
+sprite("recipe", { outline: "k" }, `
+ cccccccc..
+ cBBBBcccc.
+ ccccccccc.
+ cBBBBBBcc.
+ ccccccBBcc
+ cBBBcccccc
+ .ccccccccc`)
+sprite("teacup", { outline: "k" }, `
+ xxxxx.
+ xWWWxx
+ cxxxc.x
+ .ccc..`)
+sprite("feather", { outline: "k" }, `
+ ......xc
+ ....xxc.
+ ..xxc...
+ .xc.....
+ C.......`)
+
+// tufted wingback, written as the left half
+sprite("_chair_frame", { mx: true }, `
+ .....aaaaaaaa
+ ...aallllllll
+ ..alaaaaaaaaa
+ ..alaaaaaaaaa
+ ..aaaaaaaaaaA
+ ..aaaaaaaaaaa
+ ..aaaaaaaAaaa
+ ..aaaaaaaaaaa
+ ..aaaaaaaaaaa
+ ..aaaaaaaaaaa
+ ..aaaaaaaaaaA
+ .lllaaaaaaaaa
+ lllllaaaaaaaa
+ allllAAAAAAAA
+ aaaaaAlllllll
+ aaaaaAlllllll
+ aaaaaAlllllll
+ aaaaaAxxxxxxx
+ aaaaaAaaaaaaa
+ aaaaaAaaaaaaa
+ AaaaaAAaaaaaa
+ AAAAAAAAAAAAA
+ .AAAAAAAAAAAA
+ ..WW.........
+ ..We.........`)
+
+sprite("armchair", { base: "_chair_frame", outline: "k" },
+ shade([0, 12, 2, 10]),
+ // a knitted blanket thrown over the right arm
+ poly([19, 10, 24, 11, 26, 14, 26, 24, 20, 23, 18, 16], "c"),
+ line(19, 13, 25, 14, "C"), line(19, 17, 25, 18, "C"), hline(20, 21, 6, "r"), vline(25, 12, 11, "C"),
+ px(21, 24, "x"), px(23, 24, "x"), px(25, 24, "x"))
+
+sprite("basket", { outline: "k" }, `
+ ..l..rrr.....
+ ..l.rqrrR.Ii.
+ ..lrrrrRbbI..
+ .oorrrRbbobb.
+ oobnRRbbbbnbb
+ uwuwuwuwuwuwu
+ wuwuwuwuwuwuw
+ uwuwuwuwuwuwu
+ WWWWWWWWWWWWW
+ .WWWWWWWWWWW.`)
+
+sprite("rug", { w: 128, h: 36 },
+ (c) => { for (let y = 1; y < 35; y += 2) { c.hline(0, y, 3, "c"); c.hline(125, y, 3, "c") } }, // fringe
+ rect(3, 0, 122, 36, "R"),
+ rect(5, 2, 118, 32, "a"), rect(6, 3, 116, 30, "R"),
+ (c) => { for (let x = 9; x < 120; x += 6) { c.px(x, 4, "a"); c.px(x + 3, 31, "a") } },
+ rect(9, 6, 110, 24, "r"), box(9, 6, 110, 24, "q"),
+ // medallion and corner pieces
+ poly([64, 8, 94, 18, 64, 28, 34, 18], "R"), poly([64, 10, 88, 18, 64, 26, 40, 18], "a"),
+ poly([64, 12, 82, 18, 64, 24, 46, 18], "R"), poly([64, 15, 73, 18, 64, 21, 55, 18], "q"),
+ poly([10, 7, 22, 7, 10, 13], "R"), poly([118, 7, 106, 7, 118, 13], "R"),
+ poly([10, 29, 22, 29, 10, 23], "R"), poly([118, 29, 106, 29, 118, 23], "R"),
+ hline(3, 35, 122, "P"))
+
+sprite("doormat", { outline: "k" }, `
+ AaaaaaaaaaaaaaaaaaaaaaaaaaA
+ aAaAaAaAaAaAaAaAaAaAaAaAaAa
+ aaAaAaAaAaAaAaAaAaAaAaAaAaa
+ AAAAAAAAAAAAAAAAAAAAAAAAAAA`)
+
+sprite("dust", `
+ ..C.....
+ .BCC..c.
+ BBCCBk.C
+ .BBBBC..`)
+
+sprite("pumpkin", { outline: "k" }, `
+ .....FF.....
+ ....F.......
+ .hhHhhhhHhh.
+ hhhHhhhhHhhh
+ hhHhhlhhhHhh
+ hhHhhhhhhHhh
+ hhHhhhhhhHhh
+ .HhHhhhhHhH.
+ ..HHHHHHHH..`)
+sprite("pumpkin_s", { outline: "k" }, `
+ ...F...
+ .hhHhh.
+ hhHhlHh
+ hhHhhHh
+ .HHHHH.`)
+
+sprite("barrel", { w: 22, h: 30, outline: "k" },
+ rect(0, 4, 22, 24, "w"), ellipse(11, 4, 10, 3, "u"), ellipse(11, 4, 10, 3, "W", true),
+ ellipse(11, 4, 7, 2, "w", true),
+ (c) => { for (let x = 4; x < 22; x += 5) c.vline(x, 7, 21, "W") },
+ vline(1, 7, 21, "u"), rect(0, 9, 22, 2, "S"), rect(0, 21, 22, 2, "S"), hline(0, 9, 22, "i"), hline(0, 21, 22, "i"),
+ ellipse(11, 28, 10, 2, "W"))
+
+// pointed leaf from a base point, along an angle (degrees, 0 = right, -90 = up)
+const leaf = (bx, by, deg, len, wid, body, rib, hi) => (c) => {
+ const a = (deg * Math.PI) / 180, dx = Math.cos(a), dy = Math.sin(a), nx = -dy, ny = dx
+ const mx = bx + dx * len * 0.45, my = by + dy * len * 0.45, tx = bx + dx * len, ty = by + dy * len
+ c.poly([bx, by, mx + nx * wid, my + ny * wid, tx, ty, mx - nx * wid, my - ny * wid], body)
+ c.poly([bx, by, mx + nx * wid, my + ny * wid, tx, ty], hi)
+ c.line(Math.round(bx), Math.round(by), Math.round(tx - dx), Math.round(ty - dy), rib)
+}
+
+sprite("plant", { w: 30, h: 40, outline: "k" },
+ leaf(15, 27, -150, 15, 4, "F", "k", "F"), leaf(15, 27, -35, 15, 4, "F", "k", "F"),
+ leaf(15, 27, -120, 20, 5, "f", "F", "v"), leaf(15, 27, -65, 22, 5, "f", "F", "v"),
+ leaf(15, 27, -92, 25, 5, "f", "F", "v"), leaf(15, 27, -170, 13, 4, "f", "F", "v"), leaf(15, 27, -12, 13, 4, "f", "F", "v"),
+ rect(7, 28, 16, 3, "h"), hline(7, 28, 16, "l"), rect(8, 31, 14, 9, "H"), vline(9, 31, 9, "h"), hline(8, 39, 14, "R"),
+ hline(9, 29, 12, "e"))
+
+sprite("hourglass", { outline: "k" }, `
+ AAAAA
+ .xcx.
+ ..l..
+ .lll.
+ AAAAA`)
+sprite("photo", { outline: "k" }, `
+ aaaaaa
+ anKnna
+ anKnba
+ acKcba
+ aaaaaa`)
+
+sprite("_page_a", `
+ xxxxx..
+ xBBBxxx
+ xxxxxxx
+ .xBBBxx
+ ..CCCCC`)
+sprite("_page_b", `
+ ..xxxx
+ xxBBxx
+ xxxxxx
+ xBBBxC
+ xxxxC.
+ CCC...`)
+sprite("_page_c", `
+ ccccccc
+ cBBcBBc
+ CCCCCCC`)
+group("pages", ["_page_a", "_page_b", "_page_c"])
+
+sprite("side_table", { w: 18, h: 22, outline: "k" },
+ ellipse(9, 4, 8, 3, "w"), ellipse(9, 3, 8, 3, "u"), hline(4, 1, 8, "c"),
+ rect(8, 7, 3, 12, "W"), vline(8, 7, 12, "w"), ellipse(9, 19, 6, 2, "W"), hline(5, 19, 3, "w"))
+
+sprite("oil_lamp", { outline: "k" }, `
+ ..x..
+ .xLx.
+ .xlx.
+ .cax.
+ ..A..
+ .aaa.
+ alllA
+ .AAA.`)
+
+sprite("cookies", { outline: "k" }, `
+ ..ccccc..
+ .cxuuWxc.
+ cxuWuuxxc
+ .cxxxxuc.
+ ..ccccc..`)
+
+sprite("crate", { w: 28, h: 24, outline: "k" },
+ rect(0, 0, 28, 8, "e"), box(0, 0, 28, 8, "u"),
+ // potion bottles packed upright, seen from above: corks and shoulders
+ (c) => {
+ const cols = ["G", "b", "r", "G", "a", "b", "r", "G"]
+ for (let i = 0; i < 8; i++) {
+ const x = 3 + (i % 4) * 6, y = 1 + Math.floor(i / 4) * 3, k = cols[i]
+ c.rect(x, y + 1, 4, 3, k); c.px(x + 1, y + 1, "x"); c.rect(x + 1, y, 2, 2, "u"); c.px(x + 1, y, "c")
+ }
+ },
+ rect(0, 8, 28, 16, "w"), hline(0, 8, 28, "u"),
+ hline(0, 13, 28, "W"), hline(0, 18, 28, "W"), vline(0, 8, 16, "W"), vline(27, 8, 16, "W"),
+ rect(1, 10, 2, 13, "W"), rect(25, 10, 2, 13, "W"), text(14, 12, "XXX", "W", { align: "c" }))
+
+// the cat's bed, empty: it has better things to do tonight
+sprite("catbed", { w: 32, h: 17, outline: "k" },
+ ellipse(16, 9, 15, 7, "W"), ellipse(16, 8, 15, 7, "w"), ellipse(16, 7, 14, 6, "u"),
+ (c) => { for (let x = 3; x < 30; x += 3) { c.vline(x, 10 + (x % 2), 3, "W"); c.px(x + 1, 11, "u") } }, // wicker
+ ellipse(16, 7, 11, 4, "r"), ellipse(16, 8, 8, 3, "R"), ellipse(14, 6, 5, 1, "q"),
+ px(19, 8, "K"), px(20, 9, "K"), px(12, 9, "K"), // black hairs
+ ring(26, 3, 2, "b"), px(27, 2, "o"), line(24, 4, 20, 6, "b")) // a toy yarn ball
+
+sprite("trunk", { w: 36, h: 24, outline: "k" },
+ rect(0, 0, 36, 8, "b"), hline(0, 0, 36, "o"), rect(0, 8, 36, 3, "n"), rect(0, 11, 36, 13, "b"),
+ hline(0, 11, 36, "o"), hline(0, 23, 36, "n"),
+ rect(7, 0, 2, 24, "W"), rect(27, 0, 2, 24, "W"), px(7, 0, "w"), px(27, 0, "w"),
+ rect(0, 0, 2, 2, "a"), rect(34, 0, 2, 2, "a"), rect(0, 22, 2, 2, "A"), rect(34, 22, 2, 2, "A"),
+ rect(16, 8, 4, 5, "a"), px(17, 9, "l"), px(18, 10, "k"), px(18, 11, "k"),
+ // travel stickers: a moon, a star, and (of course) a frog
+ circ(4, 16, 2, "l"), circ(5, 15, 1, "b"), grid(11, 14, `.x.
+ xxx
+ .x.`),
+ rect(30, 14, 4, 4, "f"), px(30, 14, "v"), px(33, 14, "v"), hline(31, 16, 2, "F"))
+
+// the chair pushed back from the work table; we see its back
+sprite("chair", { w: 14, h: 25, outline: "k" },
+ rect(0, 0, 2, 25, "w"), rect(12, 0, 2, 25, "w"), vline(0, 0, 25, "u"),
+ rect(0, 0, 14, 3, "u"), hline(0, 2, 14, "w"),
+ rect(2, 6, 10, 2, "w"), hline(2, 6, 10, "u"), rect(2, 10, 10, 2, "w"), hline(2, 10, 10, "u"),
+ rect(0, 14, 14, 3, "u"), hline(0, 16, 14, "W"),
+ rect(0, 17, 2, 8, "W"), rect(12, 17, 2, 8, "W"), rect(3, 17, 2, 6, "e"), rect(9, 17, 2, 6, "e"))
+
+sprite("book_stack", { outline: "k" }, `
+ ..rrrrrrrrrq.
+ ..RRRRRRRRRx.
+ .bbbbbbbbbbbo
+ .nnnnnnnnnnxx
+ aaaaaaaaaaal.
+ AAAAAAAAAAxx.
+ .ffffffffffv.
+ .FFFFFFFFFFx.`)
+
+// bubbles rising out of the pot, popping at the top: 12 frames, each bubble on its own phase
+anim("bubbles", { w: 24, h: 22, frames: 12, fps: 10 }, (c) => {
+ const bubbles = [[6, 0, 2], [15, 0.35, 1], [10, 0.6, 1], [18, 0.8, 0], [4, 0.15, 0]]
+ for (const [x, off, r] of bubbles) {
+ const p = (c.phase + off) % 1, y = Math.round(21 - p * 20), bx = x + Math.round(Math.sin(p * 9) * 1.5)
+ if (p > 0.85) { c.px(bx - 1, y, "z"); c.px(bx + 1, y, "z"); c.px(bx, y - 1, "z") } // pop
+ else if (r && p < 0.5) { c.ring(bx, y, r, "z"); c.px(bx, y, "g") }
+ else c.px(bx, y, p < 0.5 ? "g" : "z")
+ }
+})
+
+sprite("spider", `
+ .C.
+ .C.
+ .C.
+ .C.
+ kCk
+ kKk
+ k.k`)
+
+sprite("tin", { outline: "k" }, `
+ .iIIi.
+ siiiis
+ rrrrrr
+ rxxxqr
+ rrxrrr
+ SsssSS`)
+
+sprite("_moth", `
+ c.c
+ .C.`)
+
+sprite("mousehole", { outline: "e" }, `
+ ..kkkk..
+ .kkkkkk.
+ kkkkkkkk
+ kkkkkkkk
+ kkkkkkkk
+ kkkkkkkk`)
+sprite("mouse", `
+ .ii....
+ iqis...
+ .ssssk.
+ .sssssq
+ C.ss...`)
+sprite("cheese", `
+ ..l
+ lla
+ aAa`)
+
+sprite("_print", "g.g")
+sprite("_spark_a", ".l.\nlLl\n.l.")
+sprite("_spark_b", "L")
+group("sparks", ["_spark_a", "_spark_b", "_spark_b"])
+
+// ================================================================ flickering light
+// An irregular but seamless wobble (-1..1): a few sines whose frequencies are whole numbers.
+const wobble = (c, seed) => {
+ const k = c.phase * Math.PI * 2
+ return 0.55 * Math.sin(k + seed) + 0.3 * Math.sin(3 * k + seed * 2) + 0.15 * Math.sin(5 * k + seed * 3)
+}
+// Invisible anims that only carry a lamp: stamping one places a light that breathes.
+const flame_lamp = (name, r, power, color, seed) =>
+ anim(name, { w: 1, h: 1, frames: 12, fps: 10 }, (c) => {
+ const f = wobble(c, seed)
+ c.lamp(0, 0, { r: r * (1 + 0.04 * f), power: power * (1 + 0.06 * f), color })
+ })
+flame_lamp("_fire_lamp", 90, 1.1, "#ffb27a", 0)
+flame_lamp("_candle_lamp", 26, 1, "#ffd58a", 1)
+flame_lamp("_lamp_lamp", 46, 1, "#ffd58a", 2)
+// For the flat version: light pools (drawn into light: layers) that grow and shrink a pixel or two.
+anim("_pool", { w: 13, h: 13, frames: 12, fps: 10 }, (c) => c.circ(6, 6, Math.round(4 + 0.6 * wobble(c, 1)), "k"))
+anim("_pool_big", { w: 23, h: 23, frames: 12, fps: 10 }, (c) => c.circ(11, 11, Math.round(8 + 0.7 * wobble(c, 2)), "k"))
+anim("_fire_pool", { w: 70, h: 20, frames: 12, fps: 10 }, (c) => {
+ const f = wobble(c, 0)
+ c.ellipse(35, 10, Math.round(30 + 1.5 * f), 7, "k")
+})
+
+// ================================================================ the room
+const PRINTS = [[150, 160], [147, 164], [144, 168], [141, 172], [138, 176]]
+
+scene("no_magic", { w: 256, h: 224, bg: "k", layers: true },
+ layer("room",
+ pattern("_paper", 0, 0, 256, 58), pattern("_wainscot", 0, 58, 256, 22),
+ stamp("floor", 0, FLOOR),
+ shade([0, FLOOR, 256, 2]), // where floor meets wall
+ rect(0, 0, 256, 6, "w"), hline(0, 0, 256, "u"), hline(0, 5, 256, "W"), hline(0, 6, 256, "e"),
+ shade([0, 7, 256, 2], 1, 0.5)),
+
+ layer("wall",
+ stamp("cobweb", 0, 7), stamp("spider", 7, 9),
+ stamp("window", 42, 7),
+ wire(44, 7, 86, 7, 5, "W", { hang: "herbs", every: 7, start: 5 }),
+ stamp("jar_shelf", 92, 11), stamp("chalkboard", 92, 29),
+ stamp("clock", 199, 12),
+ stamp("horseshoe", 228, 7), stamp("door", 213, 15),
+ stamp("mousehole", 70, 72)),
+
+ layer("rugs",
+ stamp("hearthstone", 138, 89), stamp("doormat", 218, 81),
+ stamp("rug", 66, 172),
+ stamp("chalk_circle", 78, 106),
+ stamp("goo", 70, 132),
+ scatter("shrooms", 70, 136, 76, 26, 9, { on: "gG", seed: 3 }),
+ ...PRINTS.map(([x, y]) => stamp("_print", x, y))),
+
+ // fire, potion and moon light on the floor
+ layer("floor_light", { light: true },
+ poly([52, FLOOR, 78, FLOOR, 96, 104, 66, 104], "k"),
+ stamp("_fire_pool", 135, 87),
+ ellipse(124, 134, 38, 17, "k")),
+
+ layer("contact", { shade: true },
+ rect(2, 89, 40, 4, "k"), ellipse(124, 140, 20, 3, "k"), ellipse(20, 133, 14, 3, "k"),
+ rect(196, 150, 56, 3, "k"), ellipse(45, 139, 6, 2, "k"), ellipse(164, 191, 12, 2, "k"),
+ rect(28, 197, 36, 3, "k"), ellipse(228, 180, 15, 2, "k"), rect(214, 158, 14, 2, "k"),
+ ellipse(14, 222, 13, 3, "k"), ellipse(15, 155, 8, 2, "k")),
+
+ layer("furniture",
+ stamp("bookshelf", 2, 22),
+ stamp("hearth", 142, 7),
+ stamp("logs", 119, 77), stamp("bowl", 205, 97), stamp("tin", 219, 92), stamp("dust", 236, 86),
+ stamp("broom", 239, 38),
+ stamp("pumpkin", 42, 80), stamp("pumpkin_s", 54, 86),
+ stamp("mouse", 77, 75), stamp("cheese", 86, 82),
+ stamp("stool", 62, 106),
+ stamp("table", 194, 118),
+ stamp("cauldron", 102, 104),
+ stamp("chair", 214, 133),
+ stamp("book_stack", 6, 94),
+ stamp("armchair", 6, 106), stamp("side_table", 36, 118), stamp("basket", 8, 142),
+ stamp("clothes", 140, 137), stamp("wand", 128, 160),
+ stamp("spellbook", 110, 178), stamp("frog", 113, 172),
+ stamp("cat", 150, 177),
+ stamp("catbed", 212, 163),
+ stamp("trunk", 26, 172), stamp("barrel", 2, 192), stamp("crate", 32, 204), stamp("plant", 228, 186)),
+
+ layer("props",
+ stamp("portrait", 159, 9),
+ // mantel
+ stamp("candle", 145, 33, { rdelay: true }), stamp("hourglass", 155, 35), stamp("photo", 181, 34), stamp("candle", 190, 33, { rdelay: true }),
+ // side table and work table
+ stamp("bubbles", 110, 84),
+ stamp("oil_lamp", 37, 109), stamp("_moth", 31, 103), stamp("_moth", 45, 100), stamp("_moth", 42, 106), stamp("cookies", 44, 115),
+ stamp("mortar", 198, 112), stamp("candle_tall", 212, 104), stamp("recipe", 222, 115),
+ stamp("scale", 232, 108), stamp("teacup", 201, 123), stamp("feather", 238, 122),
+ // the ritual circle
+ stamp("candle", 82, 120, { rdelay: true }), stamp("candle", 162, 120, { delay: 200 }), stamp("candle_out", 84, 140), stamp("chalk", 96, 156),
+ stamp("_page_a", 70, 100), stamp("_page_b", 176, 128), stamp("_page_c", 100, 160), stamp("_page_a", 160, 104, { flip: "x" }),
+ stamp("_page_b", 58, 156, { flip: "x" }),
+ scatter("sparks", 126, 154, 22, 12, 4, { seed: 2 })),
+
+ // small warm pools around flames
+ layer("flame_light", { light: true },
+ stamp("_pool", 77, 118, { rdelay: true }), stamp("_pool", 157, 118, { rdelay: true }),
+ stamp("_pool_big", 28, 101, { rdelay: true }), stamp("_pool_big", 203, 99, { rdelay: true }),
+ ellipse(146, 34, 3, 2, "k"), ellipse(191, 34, 3, 2, "k")),
+ glow("Q", { r: 6, ramp: 2 }),
+)
+
+// The same room with the lamps doing the lighting: fire, potion, candles and moonlight.
+scene("no_magic_night", { w: 256, h: 224, bg: "k" },
+ stamp("no_magic", 0, 0),
+ stamp("_fire_lamp", 169, 78),
+ lamp(124, 112, { r: 80, color: "#b4ff9c" }),
+ lamp(64, 26, { r: 30, color: "#b9c3ff", power: 0.8 }), lamp(66, 96, { r: 46, color: "#a9b6ff", power: 0.8 }),
+ lamp(130, 182, { r: 40, color: "#a8ffd8", power: 0.9 }), // the open spellbook glows
+ stamp("_lamp_lamp", 39, 112, { rdelay: true }), stamp("_lamp_lamp", 214, 106, { rdelay: true }),
+ ...[[146, 34], [191, 34], [83, 121], [163, 121]].map(([x, y]) => stamp("_candle_lamp", x, y, { rdelay: true })),
+ lighting({ cell: 2, smooth: true, ambient: 0.42, ambientColor: "#8f8fd0", emit: "zYQ" }),
+ // things that shine get a halo on top of the light
+ glow("zgG", { r: 7, strength: 0.32 }),
+ glow("Q", { r: 9, strength: 0.55 }),
+ glow("lLah", { where: [155, 66, 26, 22], r: 14, strength: 0.55 }), // the fire
+ glow("L", { r: 5, strength: 0.7 }), // candle and lamp flames
+ glow("Y", { r: 3, strength: 0.8 })) // the cat's eyes
+
+sheet("no_magic_props", [
+ "window", "chalkboard", "jar_shelf", "portrait", "hearth", "clock", "door", "horseshoe", "broom", "cobweb", "spider",
+ "bookshelf", "table", "chair", "armchair", "side_table", "trunk", "barrel", "crate", "plant", "catbed",
+ "cauldron", "bubbles", "goo", "chalk_circle", "clothes", "wand", "spellbook", "frog", "cat",
+ "hearthstone", "logs", "bowl", "tin", "stool", "basket", "book_stack", "pumpkin", "pumpkin_s", "rug", "doormat", "dust",
+ "candle", "candle_out", "candle_tall", "oil_lamp", "cookies", "mortar", "scale", "recipe", "teacup", "feather", "chalk",
+ "hourglass", "photo", "mousehole", "mouse", "cheese",
+], { pad: 2 })
diff --git a/examples/normals.px.js b/examples/normals.px.js
new file mode 100644
index 0000000..9981eb0
--- /dev/null
+++ b/examples/normals.px.js
@@ -0,0 +1,65 @@
+// Normal maps: bump() derives surface directions from shape, normals() paints them by hand, and
+// lighting() rakes each lamp across them. The anim swings a lantern so the relief shows.
+pal({
+ k: "#141020", K: "#2a2238",
+ b: "#7a3b2e", B: "#a4553d", m: "#4a3c4e", // brick, mortar
+ s: "#6d7a8c", S: "#9aa8b8", // stone
+ g: "#3e8a5a", G: "#6cc27c", // slime
+ w: "#8a5a32", W: "#b07a44", i: "#5a6470", // crate wood, iron
+ y: "#ffd36b",
+})
+
+sprite("_brick", `
+ bbbbbbbm
+ bbbbbbbm
+ bbbbbbbm
+ mmmmmmmm
+ bbbmbbbb
+ bbbmbbbb
+ bbbmbbbb
+ mmmmmmmm`)
+
+// Each brick bevels on its own: mortar counts as the edge.
+sprite("bricks", { w: 32, h: 24 }, pattern("_brick", 0, 0, 32, 24), bump("bevel", { on: "b", w: 2 }))
+
+sprite("slime", { w: 15, h: 10 }, ellipse(7, 9, 7, 8, "g"),
+ px(5, 5, "k"), px(9, 5, "k"), bump("dome", { depth: 1.5 }))
+
+// Hand-painted: plank edges face out (8 up, 2 down, 4 left, 6 right; 5 = straight at you).
+sprite("crate", `
+ iwwwwwwwwi
+ wWWWWWWWWw
+ wWwwwwwwWw
+ wWwWWWWwWw
+ wWwWWWWwWw
+ wWwwwwwwWw
+ wWWWWWWWWw
+ iwwwwwwwwi`,
+ normals(0, 0, `
+ 7888888889
+ 4777777776
+ 4626666464
+ 4625555464
+ 4625555464
+ 4623333364
+ 4111111116
+ 1222222223`))
+
+// Shaded the classic way, then luma turns that shading into relief.
+sprite("rock", { w: 14, h: 10 }, ellipse(7, 6, 6, 4, "s"), ellipse(5, 4, 3, 2, "S"), px(9, 7, "K"), bump("luma", { depth: 2 }))
+
+sprite("lantern", ".y.\nyyy\n.y.")
+
+const props = () => [
+ layer("wall", rect(0, 0, 96, 40, "K"), stamp("bricks", 2, 2), stamp("bricks", 34, 2), stamp("bricks", 66, 2)),
+ layer("props", stamp("slime", 6, 29), stamp("crate", 40, 30), stamp("rock", 70, 29)),
+];
+const lantern = (c, x, y) => { c.stamp("lantern", x - 1, y - 1); c.lamp(x, y, { r: 60, color: "#ffd9a0", z: 6 }); };
+
+anim("relief", { w: 96, h: 40, fps: 8, frames: 16 }, ...props(),
+ (c) => lantern(c, 48 + Math.round(40 * Math.cos(c.phase * 2 * Math.PI)), 14 + Math.round(6 * Math.sin(c.phase * 2 * Math.PI))),
+ lighting({ cell: 1, ambient: 0.12, emit: "y" }))
+
+// Side by side: the same lamp with relief (normals on) and without.
+scene("lit", { w: 96, h: 40 }, ...props(), (c) => lantern(c, 30, 12), lighting({ cell: 1, ambient: 0.12, emit: "y" }))
+scene("flat", { w: 96, h: 40 }, ...props(), (c) => lantern(c, 30, 12), lighting({ cell: 1, ambient: 0.12, emit: "y", relief: 0 }))
diff --git a/examples/outpost.px.js b/examples/outpost.px.js
new file mode 100644
index 0000000..a50a43d
--- /dev/null
+++ b/examples/outpost.px.js
@@ -0,0 +1,157 @@
+// Rainy-night outpost: a brick smithy and a two-floor wooden house over a dug-out cave.
+// Lit with lighting(): chandelier, candle, gem lamps, furnace, a cave torch and a crimson glow.
+pal({
+ k: "#0b0b10", a: "#1b1e27", A: "#2a2e39", q: "#45536f",
+ d: "#6b4a2e", D: "#4e3420", c: "#4a3322", C: "#36251a",
+ g: "#46a843", G: "#2b7232", r: "#a32e2e", R: "#6e1c1f",
+ t: "#73737e", T: "#4b4b56", w: "#7a5634", W: "#5a3e26", b: "#3a2616", l: "#b08a58",
+ o: "#b04a3c", O: "#6e2a24", i: "#56698e",
+ y: "#ffd86a", Y: "#ff9a3a", e: "#ff4a4a", u: "#3b5ba8", v: "#3f8f4f",
+})
+
+// ---------------------------------------------------------------- tiles
+sprite("_brick", `
+ tttTtttT
+ TTTTTTTT
+ tTtttTtt
+ TTTTTTTT`)
+sprite("_plank", `
+ wwwwwwwW
+ wwwwwwwW
+ WWWWWWWW`)
+sprite("_shingle", `
+ ooooOo
+ OOOOOO
+ oOoooo
+ OOOOOO`)
+sprite("_drop", `
+ .q
+ .q
+ q.
+ q.`)
+
+// ---------------------------------------------------------------- lit props
+sprite("torch", `
+ .y.
+ yYy
+ .Y.
+ .b.
+ .b.`, lamp(1, 1, { r: 72, color: "#ffb35c" }))
+
+sprite("chandelier", { mx: "c" }, `
+ .......b
+ .......b
+ y......y
+ b......b
+ bbbbbbbb
+ ...bbbbb`, lamp(0, 2, { r: 60, color: "#ffc070" }), lamp(7, 2, { r: 60, color: "#ffc070" }))
+
+sprite("candle", `
+ .y.
+ .Y.
+ .l.
+ lll`, lamp(1, 0, { r: 34, color: "#ffc070" }))
+
+sprite("gem", "e\ne\nb", lamp(0, 0, { r: 30, color: "#ff6a50", power: 0.75 }))
+
+sprite("furnace", `
+ .TTTTTTTTTT.
+ TttttttttttT
+ TtTTTTTTTTtT
+ TtTYYyyYYTtT
+ TtTYyyyyYTtT
+ TtTYYYYYYTtT
+ TttttttttttT
+ TTTTTTTTTTTT`, lamp(6, 4, { r: 48, color: "#ff9a40" }))
+
+// ---------------------------------------------------------------- furniture
+sprite("anvil", `
+ bbbbbbb
+ .bbbbb.
+ ..bbb..
+ .bbbbb.`)
+sprite("table", `
+ llllllllll
+ .b......b.
+ .b......b.
+ .b......b.`)
+sprite("chest", `
+ .llllll.
+ lOOOOOOl
+ llllyyll
+ lOOOOOOl
+ llllllll`)
+sprite("bookshelf", { w: 16, h: 22 },
+ rect(0, 0, 16, 22, "W"), box(0, 0, 16, 22, "b"),
+ (c) => {
+ const r = c.rng(4);
+ for (const y of [2, 9, 16]) {
+ for (let x = 2; x < 14; x++) if (r() < 0.8) c.vline(x, y, 5, "uvroi"[Math.floor(r() * 5)]);
+ c.hline(1, y + 5, 14, "b");
+ }
+ })
+
+const fence = (x, y, w, h) => (c) => {
+ c.hline(x, y + 1, w, "W");
+ for (let i = x; i < x + w; i += 3) c.vline(i, y, h, "w");
+}
+
+// ---------------------------------------------------------------- scene
+const cave = [100, 123, 198, 123, 196, 150, 200, 175, 195, 200, 185, 222, 165, 240, 145, 244,
+ 118, 232, 98, 216, 82, 200, 72, 182, 76, 168, 92, 156, 100, 148];
+
+scene("outpost", { w: 264, h: 280, bg: "a", layers: true },
+ layer("sky", { unlit: true },
+ grad(0, 0, 264, 130, "Aa"),
+ scatter("_drop", 0, 0, 264, 130, 70, { seed: 2 })),
+
+ layer("cavewall", { wall: true }, poly(cave, "c"), noise(70, 120, 132, 126, "C", 0.25, 7, "c")),
+
+ layer("ground", { solid: true },
+ rect(0, 122, 264, 158, "d"),
+ noise(0, 122, 264, 158, "D", 0.2, 3),
+ poly(cave, "_"),
+ poly([130, 166, 170, 166, 172, 169, 128, 169], "d"), // ledge for the chest
+ (c) => {
+ // Grass (crimson on the left) on every dirt pixel within 2px of open space.
+ const open = (x, y) => y >= 0 && y < c.h && x >= 0 && x < c.w && c.is(x, y, ".");
+ const edge = [];
+ for (let y = 120; y < c.h; y++)
+ for (let x = 0; x < c.w; x++)
+ if (c.is(x, y, "dD") && (open(x, y - 1) || open(x, y - 2) || open(x - 1, y) || open(x + 1, y) || open(x, y + 1)))
+ edge.push([x, y]);
+ for (const [x, y] of edge) c.px(x, y, x < 60 ? (y % 2 ? "R" : "r") : (y % 3 ? "g" : "G"));
+ }),
+
+ layer("backwall", { wall: true },
+ pattern("_brick", 38, 78, 82, 42),
+ pattern("_brick", 120, 26, 76, 50),
+ pattern("_plank", 120, 78, 76, 42),
+ rect(66, 86, 28, 16, "i"), box(66, 86, 28, 16, "b"),
+ vline(73, 86, 16, "b"), vline(80, 86, 16, "b"), vline(87, 86, 16, "b"), hline(66, 93, 28, "b")),
+
+ layer("frame", { solid: true },
+ // Smithy: chimney, sloped shingle roof, left wall.
+ pattern("_brick", 54, 50, 8, 22),
+ clip([30, 80, 42, 68, 122, 68, 122, 80], pattern("_shingle", 30, 68, 92, 12)),
+ rect(34, 80, 4, 40, "t"), rect(34, 80, 4, 40, "T"), pattern("_brick", 34, 80, 4, 40),
+ // House: roof trim, side posts, upper floor with a stair hole.
+ clip([110, 30, 124, 16, 194, 16, 208, 30, 198, 30, 190, 22, 128, 22, 120, 30], pattern("_shingle", 110, 16, 98, 14)),
+ rect(117, 26, 4, 50, "b"), rect(195, 26, 4, 72, "b"),
+ rect(117, 75, 82, 3, "b"), rect(170, 75, 22, 3, "_"),
+ rect(120, 76, 77, 2, "W"), rect(170, 76, 22, 2, "_"),
+ // Shared floor.
+ rect(34, 120, 165, 3, "t"), noise(34, 120, 165, 3, "T", 0.4, 5)),
+
+ layer("props",
+ fence(64, 56, 54, 12), fence(199, 62, 18, 12), rect(199, 74, 18, 2, "W"),
+ rect(204, 84, 11, 7, "l"), box(204, 84, 11, 7, "W"), vline(209, 78, 6, "b"), // sign
+ line(144, 120, 190, 76, "W", 2), line(144, 117, 188, 75, "l"), // stairs
+ stamp("chandelier", 147, 30), stamp("table", 145, 66), stamp("table", 152, 109),
+ stamp("candle", 157, 105), stamp("bookshelf", 175, 98),
+ stamp("gem", 50, 88), stamp("gem", 110, 88),
+ stamp("furnace", 52, 112), stamp("anvil", 70, 116), stamp("chest", 100, 115),
+ stamp("chest", 146, 161), stamp("torch", 125, 205),
+ lamp(16, 124, { r: 50, color: "#c0302a", power: 0.8 })), // crimson glow
+
+ lighting({ cell: 4, sky: 0.75, skyColor: "#8a98b8", skyReach: 16, ambient: 0.02, emit: "yYe" }))
diff --git a/examples/shop.px.js b/examples/shop.px.js
new file mode 100644
index 0000000..69c4251
--- /dev/null
+++ b/examples/shop.px.js
@@ -0,0 +1,276 @@
+// "Comet Repair": a night-time telescope shop under its own observatory dome.
+pal({
+ k: "#1b1630", // ink
+ Z: "#2a2550", z: "#383270", // night sky (lit)
+ w: "#fff6e0", // starlight
+ c: "#efdcb6", C: "#c8ae8a", e: "#a88c6c", // plaster
+ d: "#8a5a3c", D: "#5c3a2c", // wood
+ t: "#3e7f86", T: "#2a5560", q: "#62a8a4", // teal wall
+ o: "#d9844a", O: "#a0553a", u: "#f2b36e", // copper / brass
+ p: "#78c4a4", P: "#4b8c7a", // patina
+ l: "#fff0a8", L: "#ffc85e", a: "#ef8f3e", // lamp light
+ m: "#b4b8cf", M: "#727893", n: "#4a4e6a", // metal / stone
+ r: "#e2585e", R: "#a63a4c", // red
+ g: "#8ccf63", G: "#4c8a44", // leaves
+})
+// dark -> light; earlier ramps win when a key appears twice (lighting D gives wood d)
+ramps("kZz", "kDd", "kDeCc", "kTtq", "kOou", "aLl", "kPp", "knMm", "kRr", "kGg")
+
+// ---------------------------------------------------------------- small parts
+sprite("_dentil", `
+ dd..
+ DD..`)
+sprite("_awning", `
+ RRRRCCCC
+ RRRRCCCC
+ rrrrcccc
+ rrrrcccc
+ rrrrcccc
+ rrrrcccc
+ rrrrcccc
+ rrrrcccc
+ rrrrcccc
+ .rr..cc.`)
+sprite("_rail", `
+ nM.
+ nM.
+ nM.
+ nM.
+ nM.
+ nM.
+ nM.`)
+
+// shop-window trinkets (6x7, bottom row sits on the shelf)
+sprite("_globe", `
+ ......
+ ..PP..
+ .PpgP.
+ .PppP.
+ ..PP..
+ ...n..
+ ..nnn.`)
+sprite("_jar", `
+ ......
+ .nnnn.
+ .MllM.
+ .MlwM.
+ .MllM.
+ .MLLM.
+ ..MM..`)
+sprite("_scope", `
+ ......
+ ....uo
+ ...uO.
+ ..nn..
+ .n.n..
+ n...n.
+ n...n.`)
+sprite("_books", `
+ ......
+ ......
+ .r....
+ .rd...
+ .rdt..
+ .rdtq.
+ .rdtq.`)
+sprite("_bottle", `
+ ......
+ ...n..
+ ...M..
+ ..ppp.
+ ..pwp.
+ ..ppp.
+ ..PPP.`)
+group("trinkets", ["_globe", "_jar", "_scope", "_books", "_bottle"])
+
+sprite("_pot", `
+ .g.g..
+ gGgg.g
+ .gGgg.
+ ..Gg..
+ .oooo.
+ .OooO.
+ ..OO..`)
+
+sprite("_porthole", { w: 19, h: 19 },
+ circ(9, 9, 9, "M"), circ(9, 9, 7, "L"), circ(7, 7, 4, "l"), px(6, 6, "w"), px(5, 7, "w"),
+ hline(2, 9, 15, "M"), vline(9, 2, 15, "M"), ring(9, 9, 7, "m"), ring(9, 9, 9, "n"),
+ shade([10, 10, 9, 9]))
+
+sprite("_ac", { w: 13, h: 10 }, rect(0, 0, 13, 10, "m"), box(0, 0, 13, 10, "M"),
+ circ(4, 4, 3, "M"), circ(4, 4, 1, "n"), vline(9, 2, 6, "M"), vline(11, 2, 6, "M"), hline(1, 9, 11, "n"))
+
+sprite("_lantern", `
+ ..n..
+ .nnn.
+ nllLn
+ nlwLn
+ nlLan
+ .nnn.`)
+
+sprite("_drip_a", "p\np\nP")
+sprite("_drip_b", "P\np\np\np\nP")
+
+sprite("_bulb_y", "l\nL")
+sprite("_bulb_r", "r\nR")
+sprite("_bulb_p", "p\nP")
+group("bulbs", ["_bulb_y", "_bulb_y", "_bulb_r", "_bulb_p"])
+
+sprite("_star_a", "w")
+sprite("_star_b", "m")
+sprite("_star_c", `
+ .m.
+ mwm
+ .m.`)
+group("stars", ["_star_a", "_star_a", "_star_b", "_star_b", "_star_c"])
+
+// ---------------------------------------------------------------- the shop (with its own layers)
+sprite("shop", { w: 104, h: 100, outline: "k", layers: true },
+ layer("walls",
+ rect(0, 0, 104, 48, "c"), noise(0, 6, 104, 42, "C", 0.05, 2, "c"),
+ rect(0, 48, 104, 52, "t"), noise(0, 52, 104, 44, "T", 0.05, 3, "t"),
+ rect(0, 0, 104, 4, "d"), hline(0, 4, 104, "D"), pattern("_dentil", 0, 5, 104, 2),
+ rect(0, 48, 104, 3, "d"), hline(0, 51, 104, "D"),
+ rect(0, 95, 104, 5, "M"), hline(0, 95, 104, "m"), noise(0, 96, 104, 4, "n", 0.2, 4, "M")),
+
+ layer("upstairs",
+ rect(20, 9, 50, 15, "D"), box(20, 9, 50, 15, "d"),
+ px(21, 10, "u"), px(68, 10, "u"), px(21, 22, "u"), px(68, 22, "u"),
+ text(45, 12, "COMET", "l", { scale: 2, align: "c", shadow: "a" }),
+ stamp("_porthole", 5, 26), stamp("_porthole", 47, 26), stamp("_ac", 28, 36),
+ rect(76, 18, 18, 30, "D"), grad(78, 20, 14, 27, "lLa"), vline(84, 20, 27, "D"),
+ rect(70, 46, 34, 2, "D"), hline(70, 37, 34, "n"), pattern("_rail", 70, 38, 34, 8),
+ stamp("_pot", 70, 30), stamp("_pot", 96, 30, { flip: "x" })),
+
+ layer("storefront",
+ pattern("_awning", 2, 52, 56, 10),
+ rect(6, 62, 48, 31, "d"), grad(8, 64, 44, 28, "lLLa"),
+ tile("trinkets", 9, 65, 7, 1), tile("trinkets", 9, 75, 7, 1), tile("trinkets", 9, 85, 7, 1),
+ hline(8, 72, 44, "D"), hline(8, 82, 44, "D"), vline(30, 64, 28, "d"),
+ rect(4, 92, 52, 3, "d"), hline(4, 94, 52, "D"),
+ rect(60, 57, 20, 38, "D"), rect(62, 59, 16, 36, "d"),
+ circ(69, 65, 4, "L"), circ(68, 64, 2, "l"), ring(69, 65, 4, "D"),
+ box(64, 79, 12, 7, "D"), box(64, 87, 12, 7, "D"), px(76, 82, "u"),
+ line(64, 71, 69, 69, "n"), line(75, 71, 70, 69, "n"),
+ rect(61, 71, 18, 7, "c"), box(61, 71, 18, 7, "C"), text(63, 72, "OPEN", "r"),
+ stamp("_lantern", 86, 60),
+ rect(83, 71, 14, 19, "c"), box(83, 71, 14, 19, "C"),
+ circ(90, 78, 3, "o"), circ(89, 77, 1, "u"), line(84, 80, 96, 76, "R"),
+ px(85, 73, "a"), px(94, 74, "a"), text(90, 84, "SKY", "D", { align: "c" }),
+ rect(99, 6, 3, 89, "m"), vline(101, 6, 89, "M"), hline(98, 30, 5, "n"), hline(98, 70, 5, "n")),
+
+ layer("awning_shadow", { shade: true }, rect(0, 62, 60, 3, "k")),
+ layer("glow", { light: true }, circ(88, 63, 8, "k")),
+)
+
+// ---------------------------------------------------------------- rooftop
+sprite("dome", { w: 56, h: 32, outline: "k" },
+ clip([0, 0, 56, 28],
+ ellipse(27, 28, 27, 26, "o"),
+ ellipse(27, 28, 15, 26, "O", true), ellipse(27, 28, 6, 26, "O", true)),
+ light([17, 12, 13], 1, 0.5), light([16, 11, 9]), light([14, 9, 4], 1, 0.5),
+ shade([38, 0, 18, 28], 1, 0.5), shade([45, 0, 11, 28]), shade([0, 22, 56, 6], 1, 0.5),
+ scatter("_drip_*", 0, 2, 56, 24, 9, { on: "oOu", clip: true, seed: 4 }),
+ rect(30, 0, 6, 28, "k"), vline(29, 2, 26, "O"), vline(36, 2, 26, "D"),
+ rect(0, 26, 56, 6, "M"), hline(0, 26, 56, "m"), hline(0, 31, 56, "n"),
+ (c) => { for (let x = 3; x <= 53; x += 6) c.px(x, 28, "n") })
+
+sprite("scope", { w: 30, h: 24, outline: "k" },
+ line(4, 19, 20, 8, "M", 5), line(3, 17, 19, 6, "m"), line(5, 21, 21, 10, "n"),
+ line(8, 13, 11, 17, "u"), line(9, 13, 12, 17, "o"),
+ line(20, 8, 24, 5, "n", 6), line(19, 6, 23, 3, "M"),
+ line(23, 2, 27, 8, "u"), line(24, 3, 26, 6, "l"))
+
+sprite("dish", { outline: "k" }, `
+ ....nn......
+ ..nmmmn.....
+ .nmmmmmn....
+ nmmmmmMMn...
+ nmmmmMMn....
+ .nmmMMn.....
+ ..nMMn......
+ ....n.......
+ ....n.......
+ ...nMn......
+ ..nMMMn.....
+ ..nnnnn.....`)
+
+sprite("_cat", `
+ n...n..
+ nn.nn..
+ nlnln..
+ nnnnn..
+ .nnnn..
+ .nnnnn.
+ .nnnnnn`)
+
+// ---------------------------------------------------------------- street props
+sprite("_plank", `
+ dddD
+ dddD
+ ddDD
+ dddD`)
+sprite("_tin", `
+ ppP
+ ppP
+ pPP`)
+
+sprite("shed", { w: 30, h: 34, outline: "k" },
+ clip([0, 7, 30, 0, 30, 16, 0, 16], pattern("_tin", 0, 0, 30, 16)), // roof sloping up to the right
+ pattern("_plank", 0, 16, 30, 18),
+ rect(8, 19, 12, 9, "D"), grad(9, 20, 10, 7, "lLa"), vline(13, 20, 7, "D"), hline(9, 23, 10, "D"),
+ rect(0, 33, 30, 1, "D"))
+
+sprite("crate", { w: 12, h: 10, outline: "k" },
+ rect(0, 0, 12, 10, "d"), box(0, 0, 12, 10, "D"), line(1, 8, 10, 1, "D"),
+ px(5, 4, "u"), px(6, 4, "u"), px(5, 5, "u"), px(6, 5, "l"))
+
+sprite("lamp", { w: 11, h: 58, outline: "k" },
+ vline(5, 12, 44, "n"), vline(4, 12, 44, "M"), rect(2, 54, 7, 4, "n"), hline(2, 54, 7, "M"),
+ rect(1, 2, 9, 9, "n"), rect(2, 3, 7, 7, "L"), rect(3, 4, 4, 4, "l"), px(3, 4, "w"),
+ hline(0, 1, 11, "n"), hline(3, 0, 5, "n"), hline(1, 11, 9, "n"))
+
+// ---------------------------------------------------------------- scene
+scene("comet_repair", { w: 192, h: 192, bg: "Z", layers: true },
+ layer("sky",
+ scatter("stars", 0, 0, 192, 140, 46, { seed: 9 }),
+ // comet: bright core, tail fading up-left
+ (c) => {
+ c.line(41, 35, 19, 20, "L")
+ c.line(41, 35, 29, 27, "l")
+ const r = c.rng(5)
+ for (let t = 0; t <= 44; t++) {
+ const x = 40 - t, y = 34 - t * 0.7, half = 1 + t * 0.07
+ for (let o = -half; o <= half; o++)
+ if (r() < 1 - t / 46)
+ c.px(Math.floor(x - o * 0.5), Math.floor(y + o * 0.8), t < 6 ? "w" : t < 14 ? "l" : t < 28 ? "L" : "a")
+ }
+ c.circ(41, 35, 2, "w")
+ }),
+
+ layer("roof",
+ stamp("dome", 75, 36), stamp("scope", 101, 32), stamp("dish", 52, 54),
+ vline(140, 34, 34, "n"), hline(136, 44, 9, "n"), hline(137, 52, 7, "n"),
+ line(136, 44, 140, 38, "n"), line(144, 44, 140, 38, "n"), circ(140, 33, 1, "r")),
+
+ layer("buildings",
+ stamp("shed", 15, 133), stamp("shop", 45, 67),
+ stamp("_cat", 64, 61), stamp("_cat", 30, 124, { flip: "x" })),
+
+ layer("street",
+ rect(8, 169, 178, 4, "M"), hline(8, 169, 178, "m"), noise(8, 170, 178, 3, "n", 0.15, 3, "M"),
+ hline(10, 173, 174, "n"),
+ stamp("crate", 150, 158), stamp("crate", 156, 148), stamp("crate", 162, 158, { flip: "x" }),
+ stamp("_pot", 22, 162), stamp("_pot", 36, 162, { flip: "x" }),
+ stamp("lamp", 170, 111),
+ vline(10, 112, 57, "n"), hline(7, 114, 7, "n"),
+ wire(47, 70, 10, 114, 6, "n", { hang: "bulbs", every: 4 }),
+ wire(151, 70, 175, 112, 5, "n", { hang: "bulbs", every: 4, seed: 2 })),
+
+ // window and lamp light on the street and the night air: dithered halo + solid core
+ layer("halo", { light: true, density: 0.5 },
+ circ(175, 117, 16, "k"), circ(140, 33, 5, "k"), poly([40, 169, 110, 169, 120, 175, 30, 175], "k")),
+ layer("spill", { light: true },
+ poly([50, 169, 100, 169, 106, 173, 44, 173], "k"), poly([166, 169, 184, 169, 188, 173, 162, 173], "k"),
+ circ(175, 117, 10, "k"), circ(140, 33, 3, "k")),
+)
diff --git a/examples/tackle.px.js b/examples/tackle.px.js
new file mode 100644
index 0000000..e351c61
--- /dev/null
+++ b/examples/tackle.px.js
@@ -0,0 +1,297 @@
+// "Gull & Gill": a bait & tackle shop with a tugboat bridge parked on its roof.
+// 3/4 oblique view: front face + right side face receding up-right (2:1 slope).
+pal({
+ k: "#2a1b3d", // ink
+ v: "#c9b6ee", V: "#a891d8", U: "#8670b9", X: "#6a5598", // lilac bg / pavement
+ q: "#7cc6b4", t: "#3f8f8c", T: "#2c6670", N: "#1f4554", // sea-green walls
+ w: "#fffaf0", c: "#f4e4c8", C: "#d4bea4", e: "#a8907e", // cream
+ o: "#ffb39a", r: "#f0766a", R: "#c24d5a", Q: "#7e2f4a", // coral
+ h: "#ffe28a", y: "#f2b544", Y: "#c47f2e", // mustard
+ d: "#9a6248", D: "#663c3c", // wood
+ m: "#b7b4d6", M: "#7d7aa6", n: "#4b4774", // metal
+ W: "#e6fff8", a: "#8ff0e0", A: "#4cc2c4", // aquarium glow
+ g: "#8fcf6a", G: "#4a8a52", // kelp / plants
+})
+ramps("kNTtq", "kQRro", "keCcw", "kDd", "kYyh", "knMm", "AaW", "kGg", "XUVv")
+
+// ---------------------------------------------------------------- oblique helpers
+// Main block: front face at x F0..F0+W, y T0..T0+H; side face goes D px right and D/2 up.
+const F0 = 36, T0 = 76, W = 76, H = 94, D = 24
+const S = (u, v) => [F0 + W + u, T0 + v - u / 2] // side-face coords -> screen
+const side = (u0, v0, u1, v1, c) => poly([...S(u0, v0), ...S(u1, v0), ...S(u1, v1), ...S(u0, v1)], c)
+// A box seen from the front-right-top: (x, y) = front top-left corner.
+const box3 = (x, y, w, h, d, top, sd, front) => [
+ poly([x, y, x + d, y - d / 2, x + w + d, y - d / 2, x + w, y], top),
+ poly([x + w, y, x + w + d, y - d / 2, x + w + d, y + h - d / 2, x + w, y + h], sd),
+ rect(x, y, w, h, front),
+]
+// Ordered-dither test: true on a fraction t of pixels, evenly spread.
+const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5]
+const dirty = (x, y, t) => BAYER[(y & 3) * 4 + (x & 3)] / 16 < t
+// Paint flaked off a siding board: rows of [offset, length] starting at face coords (u, v).
+// "front" maps straight; "side" follows the side face slant. Top row is shadowed by the paint edge.
+const flake = (face, u, v, rows) => (c) => rows.forEach(([o, n], j) => {
+ for (let i = o; i < o + n; i++) {
+ const x = F0 + i + u + (face === "side" ? W : 0)
+ const y = face === "side" ? Math.floor(T0 + v + j - (u + i) / 2) : T0 + v + j
+ c.px(x, y, j === 0 ? "D" : "d")
+ }
+})
+// Rain stain running down from a ledge: solid at the top, broken up toward the end.
+const stain = (x, y, len, from, to) => (c) => {
+ for (let k = 0; k < len; k++) if ((k < len / 2 || k % 2 === 0) && c.is(x, y + k, from)) c.px(x, y + k, to)
+}
+// Rain splash-back: darkens "from" pixels in the h rows above yb(x), densest at the bottom.
+const grime = (x0, x1, yb, h, from, to) => (c) => {
+ for (let x = x0; x < x1; x++)
+ for (let k = 0; k < h; k++) {
+ const y = yb(x) - 1 - k
+ if (c.is(x, y, from) && dirty(x, y, 1 - k / h)) c.px(x, y, to)
+ }
+}
+
+// ---------------------------------------------------------------- the shop block
+sprite("shop", { w: 192, h: 172, outline: "k" },
+ layer("mass",
+ ...box3(F0, T0, W, H, D, "M", "T", "t"), // roof deck, side, front
+ ...box3(52, 50, 40, 23, 12, "N", "C", "c")), // wheelhouse on the roof
+
+ layer("roof",
+ noise(40, 65, 94, 11, "n", 0.08, 5, "M"),
+ // funnel behind the bridge: red stack, white band, sooty rim
+ rect(66, 25, 11, 22, "r"), vline(66, 25, 22, "o"), rect(75, 25, 2, 22, "R"),
+ rect(66, 31, 11, 4, "w"), rect(75, 31, 2, 4, "C"), stamp("_anchor", 69, 37),
+ ellipse(71, 25, 5, 2, "Q"), ellipse(71, 25, 3, 1, "k"),
+ // mast with radar bar and fish weathervane
+ vline(99, 14, 33, "n"), hline(94, 27, 11, "n"), px(94, 28, "r"), px(104, 28, "q"),
+ rect(97, 20, 5, 3, "M"), hline(92, 20, 15, "m"), hline(92, 21, 15, "n"),
+ stamp("_vane", 95, 8),
+ // bridge front: portholes, nameplate; side: porthole; railing on the bridge roof
+ ...[60, 72, 84].map((x) => stamp("_porthole", x - 4, 53)),
+ rect(53, 64, 38, 8, "N"), hline(53, 64, 38, "T"), text(72, 66, "GULL&GILL", "h", { align: "c" }),
+ stamp("_porthole", 94, 54),
+ hline(52, 46, 40, "m"), (c) => { for (let x = 52; x <= 91; x += 6) c.vline(x, 46, 4, "m") },
+ line(92, 46, 103, 41, "m"), vline(97, 44, 4, "m"), vline(103, 41, 4, "m"),
+ // deck clutter: rope coil, lobster trap, vent
+ ellipse(47, 72, 4, 2, "y"), ellipse(47, 72, 2, 1, "Y"), px(47, 72, "M"),
+ ...box3(104, 67, 9, 7, 6, "D", "D", "d"),
+ (c) => { for (let x = 105; x < 113; x += 2) c.vline(x, 68, 5, "D"); c.hline(104, 70, 9, "D") },
+ rect(118, 60, 4, 5, "m"), rect(117, 59, 6, 2, "M"),
+ ),
+ layer("self_shadow", { shade: true },
+ rect(46, 101, 50, 2, "k"), rect(96, 84, 2, 18, "k"), // under/right of the sign
+ rect(38, 135, 52, 2, "k"), rect(F0, 124, 2, 40, "k"), // under the awning, corner
+ poly([92, 73, 104, 67, 104, 70, 98, 73], "k"), // wheelhouse on the deck
+ poly([77, 47, 80, 47, 86, 44, 77, 44], "k")), // funnel on the bridge roof
+
+ layer("facade",
+ // siding on the upper floor (front + side), cornice, floor band, cream ground floor, stone base
+ (c) => { for (let v = 9; v < 44; v += 4) { c.hline(F0, T0 + v, W, "T"); c.line(...S(0, v), ...S(23, v), "N") } },
+ rect(F0, T0, W, 5, "c"), hline(F0, T0, W, "w"), hline(F0, T0 + 5, W, "C"),
+ side(0, 0, 24, 5, "C"), line(...S(0, 5), ...S(23, 5), "e"),
+ rect(F0, 120, W, 4, "d"), hline(F0, 123, W, "D"), side(0, 44, 24, 48, "D"),
+ rect(F0, 124, W, 40, "c"), side(0, 48, 24, 88, "C"),
+ // stone base: front blocks in running bond, side in shadow
+ rect(F0, 164, W, 6, "M"), hline(F0, 164, W, "m"), hline(F0, 167, W, "n"),
+ (c) => { for (let x = F0 + 6; x < F0 + W; x += 8) { c.vline(x, 165, 2, "n"); c.vline(x + 4, 168, 2, "n") } },
+ side(0, 88, 24, 94, "n"), line(...S(0, 88), ...S(23, 88), "M"),
+ vline(119, 157, 3, "k"), vline(127, 153, 3, "k"), line(...S(0, 91), ...S(23, 91), "k"),
+
+ // big sign board with thickness
+ ...box3(42, 85, 50, 16, 4, "h", "Y", "y"),
+ text(46, 88, "BAIT", "Q", { scale: 2, shadow: "Y" }), stamp("_fish", 79, 90),
+ px(43, 86, "w"), px(90, 86, "Y"), px(43, 99, "Y"), px(90, 99, "Y"),
+
+ // upper windows, life ring
+ stamp("_win", 41, 105), stamp("_win", 59, 105),
+ circ(91, 111, 6, "r"), circ(91, 111, 3, "t"), ring(91, 111, 6, "R"), ring(91, 111, 3, "R"),
+ rect(90, 105, 3, 3, "w"), rect(90, 115, 3, 3, "w"), rect(85, 110, 3, 3, "w"), rect(95, 110, 3, 3, "w"),
+ line(91, 104, 91, 102, "e"),
+
+ // side window with a half-down blind
+ side(5, 11, 17, 31, "e"), side(6, 12, 16, 30, "N"), side(6, 12, 16, 17, "C"),
+ line(...S(7, 22), ...S(11, 20), "T"), line(...S(7, 26), ...S(14, 23), "T"),
+
+ // awning (coral/white stripes, scalloped hem)
+ (c) => {
+ for (let x = 38; x < 90; x += 8) {
+ c.rect(x, 124, 4, 9, "r"); c.rect(x + 4, 124, 4, 9, "w")
+ c.hline(x + 1, 133, 2, "R"); c.hline(x + 5, 133, 2, "C")
+ }
+ },
+ shade([38, 124, 52, 2]),
+
+ // shop window: aquarium on the left, the bait-man at the counter on the right
+ rect(40, 135, 48, 28, "D"), rect(42, 137, 44, 24, "N"),
+ rect(43, 140, 20, 13, "A"), hline(43, 140, 20, "W"), rect(43, 141, 20, 2, "a"),
+ rect(43, 153, 20, 2, "n"), vline(45, 155, 6, "n"), vline(60, 155, 6, "n"),
+ line(46, 152, 47, 147, "g"), line(48, 152, 48, 145, "G"), line(58, 152, 59, 148, "g"),
+ stamp("_minnow", 50, 145), stamp("_minnow", 54, 148, { flip: "x", swap: { o: "h" } }),
+ vline(64, 137, 24, "D"),
+ stamp("_baitman", 69, 140), rect(65, 153, 21, 3, "d"), hline(65, 153, 21, "C"),
+ stamp("_jar", 66, 149), stamp("_jar", 81, 149, { swap: { g: "o", G: "r" } }),
+ line(43, 138, 45, 136, "q"), line(66, 139, 69, 136, "q"),
+ rect(38, 162, 52, 2, "c"), hline(38, 162, 52, "w"),
+
+ // door + wall lamp
+ rect(92, 129, 18, 35, "D"), rect(94, 131, 14, 33, "t"), vline(94, 131, 33, "q"),
+ circ(101, 139, 4, "M"), circ(101, 139, 3, "a"), px(100, 137, "W"), px(99, 138, "W"), ring(101, 139, 4, "n"),
+ box(96, 147, 10, 14, "T"), px(106, 152, "h"),
+ rect(99, 125, 5, 3, "h"), hline(98, 124, 7, "n"),
+
+ // side wall: drain pipe, chalk price board
+ vline(131, 68, 91, "m"), vline(132, 67, 91, "M"), hline(130, 90, 4, "n"), hline(130, 130, 4, "n"),
+ side(8, 52, 18, 66, "D"), side(9, 53, 17, 65, "N"),
+ (c) => { for (let v = 56; v < 64; v += 3) c.line(...S(10, v), ...S(15 - (v % 4), v), "C") },
+
+ // weathering: sea air has flaked the paint off a few siding boards down to bare wood,
+ // rust runs off the pipe bracket, rain splash-back grime darkens the base of both walls
+ flake("front", 41, 34, [[1, 5], [0, 4], [1, 2]]), flake("front", 67, 38, [[0, 6], [1, 4], [3, 2]]),
+ flake("front", 41, 30, [[2, 4], [0, 3]]), flake("front", 70, 14, [[0, 3], [0, 2]]),
+ flake("side", 3, 34, [[1, 6], [0, 5], [2, 3]]), flake("side", 10, 38, [[0, 4], [1, 4], [1, 2]]),
+ flake("side", 1, 18, [[0, 3], [1, 2]]), flake("side", 21, 26, [[0, 2], [0, 3], [1, 1]]),
+ stain(114, 124, 6, "C", "e"), stain(117, 122, 4, "C", "e"), stain(134, 114, 7, "C", "e"),
+ stain(89, 136, 5, "c", "C"), stain(110, 124, 6, "c", "C"),
+ px(130, 131, "Y"), px(130, 132, "Y"), px(130, 133, "e"), px(130, 135, "e"),
+ px(133, 131, "Y"), px(133, 132, "e"), px(133, 134, "e"),
+ grime(F0, F0 + W, () => 164, 7, "c", "C"),
+ grime(F0 + W, F0 + W + D, (x) => 164 - Math.floor((x - F0 - W) / 2), 9, "C", "e"),
+
+ // blade sign sticking out toward the viewer from the front-left corner
+ poly([24, 96, 36, 90, 36, 126, 24, 132], "y"),
+ line(24, 96, 35, 90, "Y"), line(24, 131, 35, 126, "Y"), vline(24, 96, 36, "Y"),
+ text(28, 98, "F\nI\nS\nH", "R"), line(24, 94, 36, 88, "n"), line(24, 133, 36, 128, "n"),
+ ),
+)
+
+// ---------------------------------------------------------------- facade parts
+sprite("_fish", `
+ ..RRR...R.
+ .RrrrR.RR.
+ RrkrrrrRR.
+ .RrrrR.RR.
+ ..RRR...R.`)
+sprite("_minnow", `
+ .oo.o
+ okooo
+ .oo.o`)
+sprite("_win", { w: 15, h: 14 },
+ rect(0, 0, 15, 13, "e"), rect(1, 1, 13, 11, "N"), rect(1, 1, 13, 4, "C"), hline(1, 4, 13, "e"),
+ vline(7, 5, 7, "e"), line(2, 10, 5, 7, "T"), line(9, 11, 13, 7, "T"),
+ rect(0, 12, 15, 2, "c"), hline(0, 12, 15, "w"))
+sprite("_baitman", `
+ ..yyyy...
+ .yyhhyy..
+ yyyyyyyyy
+ ..ooko...
+ ..oooo...
+ .cccccc..
+ yyccccyy.
+ yyyccyyyy
+ yyyyyyyyy
+ yyyyyyyyy
+ yYyyyyyYy
+ yYyyyyyYy`)
+sprite("_porthole", { w: 9, h: 9 },
+ circ(4, 4, 4, "M"), circ(4, 4, 3, "a"), ring(4, 4, 4, "n"), px(3, 2, "W"), px(2, 3, "W"),
+ shade([5, 5, 4, 4]))
+sprite("_anchor", `
+ .n.
+ nnn
+ .n.
+ n.n
+ .n.`)
+sprite("_vane", `
+ ....n.....
+ ..yyyy..y.
+ .yykyyyyy.
+ ..yyyy..y.
+ ....n.....
+ ....n.....`)
+sprite("_jar", `
+ nnn
+ gGg
+ GgG`)
+
+// ---------------------------------------------------------------- scene
+// ---------------------------------------------------------------- street props
+sprite("lamp", { w: 13, h: 80, outline: "k" },
+ vline(6, 12, 64, "n"), vline(5, 12, 64, "M"), rect(3, 75, 7, 5, "n"), hline(3, 75, 7, "M"),
+ rect(2, 3, 9, 9, "t"), rect(3, 4, 7, 7, "h"), rect(4, 5, 3, 4, "w"), vline(6, 4, 7, "T"),
+ hline(1, 2, 11, "T"), hline(3, 1, 7, "T"), px(6, 0, "T"), hline(1, 12, 11, "T"),
+ rect(0, 30, 13, 7, "c"), hline(0, 36, 13, "C"), text(1, 31, "EEL", "R"),
+ rect(0, 39, 13, 7, "c"), hline(0, 45, 13, "C"), text(1, 40, "COD", "T"))
+sprite("pole", { w: 4, h: 64, outline: "k" }, rect(1, 0, 2, 64, "d"), vline(1, 0, 64, "o"), rect(0, 60, 4, 4, "D"))
+
+sprite("crate", { w: 20, h: 19, outline: "k" },
+ ...box3(0, 6, 14, 12, 6, "D", "D", "d"),
+ hline(0, 11, 14, "D"), line(1, 17, 13, 7, "D"), rect(1, 7, 12, 1, "C"),
+ stamp("_tail", 2, 1), stamp("_tail", 8, 0, { flip: "x" }), stamp("_tail", 12, 2))
+sprite("_tail", `
+ m.m
+ mmm
+ .M.
+ .M.
+ .m.`)
+sprite("icebox", { w: 30, h: 22, outline: "k" },
+ ...box3(0, 5, 22, 16, 8, "m", "C", "w"), rect(0, 5, 22, 3, "m"), hline(0, 8, 22, "M"),
+ line(22, 5, 29, 1, "M"), text(11, 11, "ICE", "A", { align: "c", shadow: "a" }),
+ rect(1, 19, 3, 2, "M"), rect(18, 19, 3, 2, "M"))
+sprite("buoy", { w: 9, h: 16, outline: "k" },
+ ellipse(4, 8, 4, 7, "r"), rect(0, 5, 9, 3, "w"), rect(0, 11, 9, 2, "w"),
+ shade([6, 0, 3, 16]), vline(4, 0, 2, "n"), light([1, 3, 2, 3]))
+sprite("rods", { w: 14, h: 50 },
+ line(1, 49, 6, 0, "D"), line(8, 49, 13, 6, "n"), line(2, 44, 6, 6, "d"),
+ rect(1, 37, 3, 3, "k"), rect(2, 38, 1, 1, "m"), rect(8, 39, 3, 3, "k"), px(9, 40, "y"))
+sprite("bucket", { w: 10, h: 10, outline: "k" },
+ poly([0, 2, 10, 2, 9, 10, 1, 10], "q"), hline(0, 2, 10, "w"), vline(8, 3, 7, "t"),
+ px(2, 1, "o"), px(3, 0, "o"), px(5, 1, "r"), px(6, 1, "o"), line(1, 2, 5, -2, "n"), line(9, 2, 5, -2, "n"))
+sprite("_cat", `
+ n...n..
+ nn.nn..
+ nhnhn..
+ nnnnn..
+ .nnnn..
+ .nnnnn.
+ .nnnnnn`)
+sprite("_gull", `
+ ..ww.
+ .wwwy
+ mwww.
+ .Mw..
+ ..y..`)
+sprite("_gull_fly", `
+ mm...mm
+ ..mwm..
+ ...w...`)
+sprite("_pennant_r", `rrr\nrr\nr`)
+sprite("_pennant_y", `yyy\nyy\ny`)
+sprite("_pennant_w", `www\nww\nw`)
+sprite("_pennant_t", `qqq\nqq\nq`)
+group("pennants", ["_pennant_*"])
+
+// ---------------------------------------------------------------- scene
+scene("gull_and_gill", { w: 192, h: 192, bg: "v", layers: true },
+ layer("sky",
+ circ(82, 18, 3, "w"), circ(88, 12, 4, "w"), circ(96, 7, 3, "c"), circ(102, 4, 2, "c"), px(86, 10, "c"),
+ stamp("_gull_fly", 22, 30), stamp("_gull_fly", 150, 22, { flip: "x" }), stamp("_gull_fly", 162, 34)),
+ layer("pavement",
+ poly([8, 178, 158, 178, 192, 161, 192, 154, 50, 154, 42, 158, 8, 158], "V"),
+ rect(8, 178, 150, 3, "U"), poly([158, 178, 192, 161, 192, 164, 158, 181], "X"),
+ (c) => { for (let x = 22; x < 190; x += 16) c.line(x, 177, x + 44, 155, "U") },
+ hline(8, 172, 156, "U"), hline(8, 165, 170, "U")),
+ layer("cast_shadow", { shade: true },
+ poly([112, 171, 136, 159, 166, 159, 148, 171], "k"),
+ poly([4, 172, 22, 172, 24, 169, 6, 169], "k"),
+ poly([132, 170, 168, 170, 172, 165, 136, 165], "k")),
+ layer("buildings", stamp("shop", -1, -1)),
+ layer("props",
+ stamp("rods", 18, 122), stamp("bucket", 23, 161),
+ stamp("lamp", 2, 92), stamp("_gull", 4, 88),
+ stamp("pole", 176, 106), stamp("_gull", 175, 101, { flip: "x" }),
+ stamp("crate", 113, 152), stamp("crate", 116, 140, { flip: "x" }),
+ stamp("icebox", 137, 148), stamp("buoy", 166, 154),
+ stamp("_cat", 84, 77), stamp("_gull", 60, 41),
+ wire(103, 27, 178, 107, 10, "n", { hang: "pennants", every: 5, seed: 3 }),
+ wire(8, 93, 25, 95, 2, "n")),
+)
diff --git a/lighting.md b/lighting.md
new file mode 100644
index 0000000..80459e2
--- /dev/null
+++ b/lighting.md
@@ -0,0 +1,134 @@
+# pxl lighting (Terraria-style)
+
+Light spreads over a grid of cells from lamps and the sky. Open cells cost a fixed amount (so a
+lamp's `r` is its reach). Solid cells keep only a fraction of the light that enters, so bright
+light seeps deeper into blocks than dim light. Rooms fill with light, wall and ground edges fade
+out over a few cells, and deep ground stays black. The result multiplies the image's RGB, so lit
+art leaves the palette by design.
+
+## Setup in three parts
+
+```js
+sprite("torch", `
+ .y.
+ yYy
+ .Y.
+ .b.`, lamp(1, 1, { r: 44, color: "#ffb35c" })) // the lamp travels with every stamp
+
+scene("cabin", { w: 200, h: 130, bg: "n" },
+ layer("sky", { unlit: true }, grad(0, 0, 200, 100, "nN")), // backdrop: never lit
+ layer("ground", { solid: true }, ...), // blocks light
+ layer("backwall", { wall: true }, ...), // light passes, sky light can't enter
+ layer("frame", { solid: true }, ...), // floors, roof, outer walls
+ layer("props", stamp("torch", 70, 82), ...),
+ lighting({ cell: 4, sky: 0.9, skyColor: "#d8ccf0", ambient: 0.03, emit: "yY" }),
+ layer("ui", ...)) // after lighting() = not lit
+```
+
+Full demo: `examples/lighting.px.js`.
+
+## lamp(x, y, { r = 32, color = "#fff", power = 1, z = 8 })
+
+A light source. It's an op, so it goes anywhere: in a sprite body (torches, chandeliers, lanterns,
+lava), in a layer, or in a function as `c.lamp(...)`. Lamps travel with their image through
+`stamp`, `tile`, `pattern`, `tilemap`, `scatter`, wire `hang`, `base`, flips and rotations. `mx`/`my`
+mirroring copies them too, so a symmetric chandelier needs one lamp. `r` is the reach in pixels
+through open space. `power` is the starting intensity: above 1 it overexposes near the source and
+pushes further into blocks. `z` is the lamp's height above the picture, used only by normal maps:
+low (2–6) rakes across the relief, high (20+) lights it head-on.
+
+## lighting({ ... })
+
+Goes directly in a sprite or scene body (not inside a layer) and lights everything drawn before it.
+It uses every lamp placed so far and consumes them, so a lit asset stamped elsewhere isn't lit
+twice.
+
+| Option | Default | Meaning |
+|---|---|---|
+| `cell` | 4 | Light-grid cell size in px. Bigger = blockier (Terraria look); 1 = per pixel. |
+| `smooth` | false | Interpolate between cells instead of hard steps. |
+| `block` | 0.4 | Fraction of light lost per 8px of solid (0..1), independent of `cell`. Solids never pass more light than open space. Lower = light seeps deeper into blocks. |
+| `sky` | 0 | Sky light level (0..1+, also how deep it seeps into the ground), seeded in cells open to the sky (top of each column down to the first solid or wall cell). |
+| `skyColor` | white | |
+| `skyReach` | 24 | How far sky light spreads from open cells, in px (into doorways, ground edges). |
+| `ambient` | 0 | Minimum light everywhere, 0..1. Keep it low (0.02–0.08) for Terraria-black darkness. |
+| `ambientColor` | white | |
+| `emit` | — | Keys that ignore lighting: flames, glowing windows, lava (`"yYG"`). |
+| `shape` | `"round"` | `"diamond"` spreads to 4 neighbours only (diamond-shaped pools). |
+| `relief` | 1 | How strongly normal maps shape the light; 0 ignores them. |
+| `skyDir` | `[0, -1]` | Direction sky light travels from, for normal maps (`[1, -1]` = from the upper left). |
+
+Overlapping lights combine by max per channel, so they don't blow out.
+
+## Layer flags
+
+| Flag | Effect |
+|---|---|
+| `solid: true` | Opaque pixels block light (a cell is solid when most of its pixels are). |
+| `wall: true` | Back walls: light passes through, but sky light doesn't start there. Without one, rooms open at the sides fill with sky light. |
+| `unlit: true` | Pixels this layer leaves visible are drawn as-is (sky, distant backdrop). Layers drawn on top of it are still lit. |
+
+## Normal maps (relief)
+
+Pixels can carry a surface direction. `lighting()` then brightens the sides that face each light
+and darkens the sides that face away, so bricks, domes and bevels catch the light as it moves.
+Flat or unmapped pixels light exactly as before. Normals travel with the pixels through stamps,
+flips, rotations and mirroring. A layer drawn on top without normals clears them where it covers.
+
+```js
+sprite("bricks", { w: 32, h: 24 }, pattern("_brick", 0, 0, 32, 24),
+ bump("bevel", { on: "b", w: 2 })) // each brick bevelled; mortar is the edge
+sprite("slime", ..., bump("dome", { depth: 1.5 })) // the blob bulges like a pillow
+sprite("rock", ..., bump("luma", { depth: 2 })) // the existing shading becomes relief
+sprite("crate", `...`, normals(0, 0, `
+ 7888889
+ 4555556
+ 1222223`)) // hand-painted, numpad directions
+```
+
+`bump(shape = "dome", { w, depth = 1, on = "*", where })` works on the current sprite or layer's
+opaque pixels:
+
+| Shape | Height comes from |
+|---|---|
+| `"dome"` | Each connected blob bulges, steep at the rim and flat at the top (barrels, slimes, fruit). |
+| `"bevel"` | Edges slope over `w` px (default 2), with a flat top (bricks, panels, buttons, tiles). |
+| `"luma"` | Brightness: lighter pixels are higher. Good for art that's already shaded. |
+
+`on` limits it to some keys, and the other keys act as edges, so `on: "b"` bevels every brick
+separately. The image border counts as an edge too. `depth` sets the steepness.
+
+`normals(x, y, grid)` paints directions with the numpad: `8` faces up, `2` down, `4` left, `6`
+right, `7 9 1 3` the diagonals, `5` straight at the viewer. `q w e / a s d / z x c` are the same
+directions with a gentler tilt. `0` clears a normal and `.` skips.
+
+`pxl build` also writes `<name>_n.png` for every sprite or scene that has normals. It uses the
+usual engine encoding (RGB = normal × 0.5 + 0.5, green pointing up, flat = `#8080ff`), so Godot,
+Unity and similar engines can light the sprite with it. The viewer shows a **normal map** frame
+before the light map.
+
+Full demo: `examples/normals.px.js` (`relief` animates a lantern swinging past; `lit` and `flat`
+compare the same lamp with and without relief).
+
+## Glow on top of the light
+
+Lighting darkens; it doesn't make things shine. Add `glow()` after `lighting()` for halos around
+flames, potions, moons and eyes (see reference.md, "Glow"). Glowing pixels are found by their
+palette key even though lighting changed their colors, so you don't need them in `emit` (though
+`emit` keeps them at full brightness):
+
+```js
+lighting({ cell: 2, smooth: true, ambient: 0.4, emit: "zQ" }),
+glow("zgG", { r: 7, strength: 0.3 }), // potion
+glow("lLah", { where: [155, 66, 26, 22], r: 14 }), // just the fire, not every orange pixel
+glow("L", { r: 5, strength: 0.7 }) // candle flames
+```
+
+## Tips
+
+- Check the result in the live viewer. The painting steps include a **light map** frame right
+ before the lit result.
+- Doors, windows and holes in floors are just gaps in the `solid` layer. Light flows through them.
+- Too dark? Raise the lamp's `r` before `power`. Light reaching too far into the ground? Raise `block`
+ (0.5–0.6). Want more Terraria-style glow through dirt? Lower it (0.25–0.3).
+- Smaller `cell` for small sprites and close-ups, 4–8 for scenes.
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..f338d90
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,415 @@
+{
+ "name": "pxl-pixelart",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "pxl-pixelart",
+ "version": "0.1.0",
+ "license": "MIT",
+ "bin": {
+ "pxl": "bin/pxl.js"
+ },
+ "devDependencies": {
+ "@types/node": "^24.0.0",
+ "typescript": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=22.18"
+ }
+ },
+ "node_modules/@types/node": {
+ "version": "24.19.2",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
+ "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": ">=7.24.0 <7.24.7"
+ }
+ },
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc"
+ },
+ "engines": {
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.24.6",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..724ff6b
--- /dev/null
+++ b/package.json
@@ -0,0 +1,57 @@
+{
+ "name": "pxl-pixelart",
+ "version": "0.1.0",
+ "description": "A compact pixel-art DSL for AI agents and humans: sprites, layers, scenes, sheets, with a live painting viewer.",
+ "type": "module",
+ "license": "MIT",
+ "bin": {
+ "pxl": "./bin/pxl.js"
+ },
+ "exports": {
+ ".": "./dist/index.js",
+ "./core": "./dist/core/index.js"
+ },
+ "files": [
+ "bin",
+ "src",
+ "dist",
+ "scripts",
+ "types",
+ "examples/*.px.js",
+ "SKILL.md",
+ "reference.md",
+ "lighting.md"
+ ],
+ "engines": {
+ "node": ">=22.18"
+ },
+ "scripts": {
+ "build": "node scripts/build.js",
+ "prepare": "node scripts/build.js",
+ "test": "node --test --disable-warning=ExperimentalWarning \"test/**/*.test.ts\"",
+ "typecheck": "tsc -p tsconfig.json",
+ "check": "npm run typecheck && npm test"
+ },
+ "devDependencies": {
+ "@types/node": "^24.0.0",
+ "typescript": "^7.0.0"
+ },
+ "keywords": [
+ "pixel-art",
+ "sprites",
+ "dsl",
+ "gamedev",
+ "sprite-sheet",
+ "ai-agent",
+ "claude-code",
+ "skill"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/crsolver/claude-pxl.git"
+ },
+ "homepage": "https://github.com/crsolver/claude-pxl#readme",
+ "bugs": {
+ "url": "https://github.com/crsolver/claude-pxl/issues"
+ }
+}
diff --git a/reference.md b/reference.md
new file mode 100644
index 0000000..9095abf
--- /dev/null
+++ b/reference.md
@@ -0,0 +1,224 @@
+# pxl reference
+
+Art files are plain JavaScript (or TypeScript) evaluated with the DSL as globals. Nothing draws
+at definition time: `sprite`, `scene`, ... record definitions; everything renders at build time,
+so assets may reference each other in any order.
+
+Coordinates are 0-based from the top-left. Sizes are `w, h`. Colors are a single palette key
+(`"k"`), a hex string (`"#1b1630"`, `"#rgb"`, `"#rrggbbaa"`), `"."` (skip: leave the pixel) or
+`"_"` (erase to transparent).
+
+## Palette
+
+| Call | Effect |
+|---|---|
+| `use("pico8")` | Built-in palette: `pico8` (default), `sweetie16`, `db16`, `endesga32`, `gray8`. Keys are index chars `0-9a-z`. |
+| `use(["#000", "#fff", ...])` | Custom list, keys `0-9a-zA-Z` by index. |
+| `pal({ k: "#1b1630", g: 11, h: "k" })` | Add/override single-char keys: hex, palette index, or copy of another key. `. _ # space` are reserved. |
+| `ramps("kDdu", "kTtq")` | Light ramps, dark → light. `shade` steps a color left, `light` steps right. When a key is in several ramps, the first ramp wins. |
+
+Every asset keeps the palette that was active where it was defined, so files with different
+palettes can be included and stamped together.
+
+## Assets
+
+```js
+sprite(name, opts?, ...items)
+scene(name, { w, h, bg?, ... }, ...items)
+layer(name, layerOpts?, ...items) // only as an item of a sprite or scene
+group(name, ["a", "b", "rock_*", ...]) // random pick per placement; repeat a name to weight it
+sheet(name, ["slime*", "heart", groupName], { cols?, pad? })
+include("other.px.js") // path relative to the current file
+```
+
+Names starting with `_` are **parts**: usable everywhere but not exported, and not matched by
+sheet globs.
+
+### Items (run in order)
+
+- **Grid string**: one char per pixel, drawn at 0,0. Rows are trimmed, blank edge rows dropped,
+ short rows padded. `.`/space keep, `_` erases. Use template literals for multi-line grids.
+- **Op**: `rect(...)`, `stamp(...)`, ... (below).
+- **Function**: `(c) => { ... }` gets the canvas; call ops as methods (`c.rect(...)`), plus
+ `c.w`, `c.h`, `c.is(x, y, "ab")` (pixel is one of these keys; `"*"` opaque, `"."` transparent),
+ `c.key(x, y)`, `c.get(x, y)` (packed color), `c.rng(seed)` (deterministic, follows reseed).
+- **Layer**: drawn on its own image, then blended in at its place in the list.
+
+### Sprite / scene options
+
+| Option | Meaning |
+|---|---|
+| `w, h` | Canvas size. Sprites infer it from grid strings (including grids inside layers) when omitted; scenes require it. |
+| `base: "name"` | Start from a copy of another asset (variant). Overlay coordinates are the base's final coordinates (outline included). |
+| `bg` | Scene background color. |
+| `mx: true` | Mirror the left half onto the right after all items. Inferred width doubles (write half a row). `mx: "c"`: odd width, shared center column. `my` likewise vertically. |
+| `swap: { g: "r" }` | Recolor after drawing. |
+| `flip: "x" \| "y" \| "xy"`, `rot: 90 \| 180 \| 270` | Transform. |
+| `outline: "k"` | 1px outline around opaque pixels; **grows the canvas 1px on every side**. `outline8` also fills diagonals. |
+| `crop: true` | Trim to opaque bounds. |
+| `layers: true` | Also export each layer as `out/<sprites\|scenes>/<name>/<layer>.png`. |
+
+Post-processing order: mirror → swap → flip → rot → outline → crop.
+
+### Layer options
+
+| Option | Meaning |
+|---|---|
+| `x, y` | Offset of every op in the layer. |
+| `hidden: true` | Skip when compositing (still exported with `layers: true`). |
+| `shade: true \| n \| { m: "M" }` | Blend layer: not drawn. Wherever it is opaque, what's below steps darker along the ramps (`n` steps, or the given map). |
+| `light: ...` | Same, lighter. Cast shadows, light spills, glows. |
+| `density: 0..1` | Ordered-dither the layer (soft edges). Stack a low-density big shape and a full small one for falloff. |
+
+## Ops
+
+`?` marks optional arguments.
+
+### Shapes
+| Op | Notes |
+|---|---|
+| `px(x, y, c)` | |
+| `rect(x, y, w, h, c)` · `box(x, y, w, h, c)` | filled · 1px border |
+| `line(x0, y0, x1, y1, c, width?)` | width > 1 = round brush (tubes, poles, thick strokes) |
+| `hline(x, y, len, c)` · `vline(x, y, len, c)` | |
+| `circ(cx, cy, r, c)` · `ring(cx, cy, r, c)` | pixel-art circles; ring is a clean 1px border |
+| `ellipse(cx, cy, rx, ry, c, ring?)` | |
+| `poly([x0, y0, x1, y1, ...], c)` | filled; vertices on pixel corners (`[0,0, 4,0, 4,4, 0,4]` = `rect(0,0,4,4)`) |
+| `fill(x, y, c)` | 4-connected flood fill |
+| `wire(x0, y0, x1, y1, sag, c, { hang?, every = 6, start?, ...placement })` | sagging cable; `hang` stamps an asset/group under it every `every` px (string lights) |
+| `text(x, y, "str", c, { scale = 1, gap = 1, lead = 1, align: "l"\|"c"\|"r", shadow? })` | built-in 3×5 font: A-Z 0-9 and common punctuation, `\n` for lines |
+
+### Texture and tone
+| Op | Notes |
+|---|---|
+| `dither(x, y, w, h, c1, c2, density = 0.5)` | Bayer 4×4; c2 covers `density` |
+| `grad(x, y, w, h, "abc", dir = "v", soft = 0.5)` | bands with dithered seams; `"h"` horizontal; soft 0 = hard bands |
+| `noise(x, y, w, h, "ab", density = 0.1, seed = 1, on?)` | deterministic speckle; `on: "g"` only touches those keys (`"*"` any opaque) |
+| `shade(where?, steps = 1, density = 1)` · `light(...)` | step colors along ramps inside a region |
+| `recolor({ a: "b" }, where?, density = 1)` | swap colors inside a region |
+
+**Regions** (`where`, `clip`): `undefined` = everywhere, `[cx, cy, r]` circle, `[x, y, w, h]`
+rect, `[x0, y0, x1, y1, x2, y2, ...]` polygon, or `(x, y) => boolean`.
+
+### Placing assets
+| Op | Notes |
+|---|---|
+| `stamp(name, x, y, opts?)` | |
+| `tile(name, x, y, cols, rows, opts?)` | grid of copies (each cell picks separately for groups) |
+| `pattern(name, x, y, w, h, opts?)` | fill an area with copies; edges cut to fit |
+| `tilemap("gg\nd.", { map: { g: "grass", d: "dirt" }, size?, w?, h?, x?, y?, ...placement })` | character map; `.` empty |
+| `scatter(name, x, y, w, h, count, { on?, clip?, below?, ...placement })` | brush: `count` picks centered at random points; `on` = center must land on these keys; `clip` = paint only onto them; `below` = masks read the composite under this layer |
+| `clip(region, ...items)` | run items with drawing restricted to the region (half domes, roof slopes, masked textures) |
+
+Any `name` may be a sprite, scene, group, or glob (`"tree_*"`). **Placement opts**: `flip`, `rot`,
+`swap`, `rflip: "x"|"y"|"xy"` (random flips), `rswap: [{ g: "r" }, {}]` (random recolor; `{}` =
+none), `seed`, `reseed: true | n` (rebuild the placed asset with its own random choices; `true`
+derives it from the position, so `tile("house", 0, 0, 4, 1, { reseed: true })` gives four
+different houses from one definition).
+
+Randomness is seeded from the placement position + `seed`, so builds are reproducible and moving
+one placement doesn't reshuffle the others. Change `seed` to reroll.
+
+## Lighting
+
+`lamp(x, y, { r, color, power })`, `lighting({ cell, sky, ambient, emit, ... })`, and the layer flags
+`solid`, `wall`, `unlit`: see [lighting.md](lighting.md). The same file covers normal maps:
+`bump("dome"|"bevel"|"luma", { w, depth, on, where })` and the numpad grid `normals(x, y, grid)`.
+
+## Glow
+
+`glow(keys, { where, r = 6, strength = 0.5, color, bands, ramp })` goes directly in a sprite or
+scene body (like `lighting`) and works on everything drawn before it: every pixel whose color is
+one of `keys` spills a halo onto the opaque pixels within `r`, falling off with distance. The
+glowing pixels themselves are left as they are, and transparent pixels stay empty.
+
+| Option | Meaning |
+|---|---|
+| `where` | Region: only pixels inside it glow (the halo may spread past it). |
+| `r` | Halo radius in px. |
+| `strength` | How strongly the halo brightens (screen blend in the glowing color; 0..1+). |
+| `color` | One tint for the whole halo instead of each pixel's own color. |
+| `bands` | Quantize the falloff into this many rings: crisp, pixel-art halos. |
+| `ramp` | Palette mode: step neighbours up to `ramp` shades lighter along the ramps, dithering between steps. Stays in the palette; ignores `strength`/`color`. Use it before `lighting()`. |
+
+Color mode leaves the palette (like lighting). Several `glow`s can stack, each with its own keys
+and radius. After `lighting()`, pixels still glow by their palette key even though the light has
+changed their colors.
+
+## Animation
+
+```js
+anim(name, { fps = 8, frames, loop = true, base, w, h, outline, mx, ... }, ...items)
+frame({ ms, hold }?, ...items) // only inside an anim (top level or in its layers)
+```
+
+An anim is a sprite with frames. Its items run in order on every frame, except `frame(...)` items:
+the k-th `frame()` only runs on frame k, so frames are **patches** over the shared items (or over
+`base`). Post-processing (mirror, outline, ...) runs on each frame. A frame lasts `1000 / fps` ms,
+or `ms`, or `hold` × that. `loop: false` plays once and holds the last frame.
+
+```js
+anim("candle", { outline: "k", fps: 5 }, `
+ .l.
+ lLl
+ xxx`,
+ frame(), frame(grid(0, 0, "l_.\n_Ll")), frame(grid(0, 0, "._l\nlL_"))) // "_" erases
+anim("frog", { base: "frog_idle" }, frame({ ms: 2200 }), frame({ ms: 200 }, grid(1, 1, "ff")))
+```
+
+**Procedural**: without `frame()` items, `frames: n` sets the count and functions draw from
+`c.frame` (0..n-1), `c.frames` and `c.phase` (`frame / frames`, 0..<1). Use `phase` with `sin`
+for loops that wrap seamlessly:
+
+```js
+anim("fire", { w: 22, h: 23, frames: 6, fps: 10 }, (c) => {
+ const k = c.phase * Math.PI * 2
+ c.poly([2, 21, 10, 21 - Math.round(16 + Math.sin(k) * 2), 19, 21], "h")
+})
+```
+
+**Placing anims animates the placer.** A sprite or scene that stamps (tiles, scatters, ...) an anim,
+directly or through other assets, is animated too: it loops over the least common multiple of
+what it contains (capped at 60s), sampled at their common step. Keep durations on a shared grid
+(e.g. multiples of 100ms) so loops stay short. Placement options:
+
+| Option | Meaning |
+|---|---|
+| `frame: n` | Freeze on frame n (the placer doesn't animate from it). |
+| `delay: ms` | Start later, snapped to the anim's step: desync copies. |
+| `rdelay: true` | Random start per placement (seeded, reproducible). |
+
+**Output**: anims go to `anims/<name>.png` (horizontal strip), `anims/<name>.json` (per-frame
+`duration` + `meta.frameTags`, Aseprite style: Phaser, Godot, ... read it) and `anims/<name>.gif`.
+Animated sprites and scenes get `<name>.gif` next to their PNG (which shows frame 0). Previews:
+`_preview/<name>.png` shows an anim's frames side by side; anything animated also gets
+`_preview/<name>.gif`. Sheets expand anims into `name_0`, `name_1`, ... with durations and tags.
+`pxl ascii` prints every frame of an anim. The live viewer loops animated assets after the
+painting replay ends ("animate" toggle).
+
+## CLI
+
+```
+node <pxl>/bin/pxl.js build <file> [--out DIR] [--only a,b] [--scale N] [--no-preview]
+node <pxl>/bin/pxl.js serve <file> [--port 4321] [--out DIR | --no-out] [--no-preview]
+node <pxl>/bin/pxl.js ascii <file> <name>
+node <pxl>/bin/pxl.js list <file>
+```
+
+Outputs go to `<file dir>/out`: `sprites/<n>.png`, `scenes/<n>.png`, `<sheet>.png` + `<sheet>.json`
+(TexturePacker hash format: Phaser, Godot importers, ...), `_preview/<n>.png` (upscaled to
+~768px, checkerboard behind transparency, pixel grid at scale ≥ 6 with every 8th line darker).
+
+`serve` opens a live viewer that rebuilds on save, follows the asset you edited and replays its
+painting steps (each top-level op, layer and post-processing step, with its file:line). It also
+writes the same outputs as `build`.
+
+## Library
+
+```ts
+import { loadProject, loadSource, writeOutputs, serve, ascii, preview } from "pxl-pixelart";
+const p = loadProject("art.px.js");
+const img = p.image("slime"); // Img { w, h, data: Uint32Array of 0xRRGGBBAA }
+```
+
+`pxl-pixelart/core` exports the platform-independent engine (no Node APIs).
diff --git a/scripts/build.js b/scripts/build.js
new file mode 100644
index 0000000..bd5775c
--- /dev/null
+++ b/scripts/build.js
@@ -0,0 +1,35 @@
+// Strips types from src/**/*.ts into dist/**/*.js so the CLI also runs from node_modules
+// (Node refuses to type-strip files there). No dependencies; runs on `npm install`/`npm pack`.
+import { cpSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { stripTypeScriptTypes } from "node:module";
+import { dirname, join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+
+process.removeAllListeners("warning");
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const src = join(root, "src");
+const dist = join(root, "dist");
+
+rmSync(dist, { recursive: true, force: true });
+
+function walk(dir) {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ const out = join(dist, relative(src, p));
+ if (e.isDirectory()) walk(p);
+ else if (dir.endsWith("viewer")) {
+ // The viewer is served as-is; the server type-strips app.ts on request.
+ mkdirSync(dirname(out), { recursive: true });
+ cpSync(p, out);
+ } else if (e.name.endsWith(".ts")) {
+ const code = stripTypeScriptTypes(readFileSync(p, "utf8"), { mode: "strip" })
+ .replace(/(from\s+|import\(\s*)(["'])(\.{1,2}\/[^"']+)\.ts\2/g, "$1$2$3.js$2");
+ mkdirSync(dirname(out), { recursive: true });
+ writeFileSync(out.replace(/\.ts$/, ".js"), code);
+ }
+ }
+}
+
+walk(src);
+console.log(`pxl: built ${relative(root, dist)}/`);
diff --git a/scripts/gallery.ts b/scripts/gallery.ts
new file mode 100644
index 0000000..392cbfa
--- /dev/null
+++ b/scripts/gallery.ts
@@ -0,0 +1,35 @@
+// Renders the README gallery (docs/gallery/) from the examples: clean nearest-neighbour upscales,
+// GIFs for animated assets. Run: node scripts/gallery.ts
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { encodeGif } from "../src/node/gif.ts";
+import { loadProject } from "../src/node/load.ts";
+import { encodePng } from "../src/node/png.ts";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const out = join(root, "docs", "gallery");
+mkdirSync(out, { recursive: true });
+
+// [example file, asset, target width in px]
+const shots: [string, string, number][] = [
+ ["shop.px.js", "comet_repair", 576],
+ ["tackle.px.js", "gull_and_gill", 576],
+ ["moon_bakery_3d.px.js", "moon_buns_3d", 576],
+ ["neon_noodle_3d.px.js", "neon_noodle_3d", 576],
+ ["cave.px.js", "cave", 576],
+ ["no_magic.px.js", "cat", 192],
+ ["no_magic.px.js", "frog", 192],
+ ["no_magic.px.js", "clock", 192],
+];
+
+for (const [file, name, width] of shots) {
+ const p = loadProject(join(root, "examples", file));
+ const b = p.build(name);
+ const s = Math.max(1, Math.floor(width / b.img.w));
+ if (b.anim) {
+ const frames = p.frames(name).map((f) => ({ img: f.img.scale(s), ms: f.ms }));
+ writeFileSync(join(out, name + ".gif"), encodeGif(frames));
+ } else writeFileSync(join(out, name + ".png"), encodePng(b.img.scale(s)));
+ console.log(`${name} ${b.img.w}x${b.img.h} @${s}x`);
+}
diff --git a/src/core/build.ts b/src/core/build.ts
new file mode 100644
index 0000000..1f06233
--- /dev/null
+++ b/src/core/build.ts
@@ -0,0 +1,336 @@
+// Turns an asset definition into an image: base -> items (ops, grids, functions, layers)
+// -> post-processing (mirror, swap, flip, rot, outline, crop). Optionally traced.
+import { Canvas, type Resolver } from "./canvas.ts";
+import { type Color, TRANSPARENT } from "./color.ts";
+import { PxError, wrap } from "./errors.ts";
+import { Img } from "./image.ts";
+import { applyGlow } from "./glow.ts";
+import { applyLighting } from "./light.ts";
+import { normalImage } from "./normals.ts";
+import { type AssetDef, type FrameOpts, type GlowOpts, type Item, type Layer, type LayerOpts, type LightingOpts, type Op, type Timeline, isLayer, isOp } from "./model.ts";
+import type { Palette } from "./palette.ts";
+import { Trace } from "./trace.ts";
+import { bayer, fmtArgs, gridRows, gridSize, type Region } from "./util.ts";
+
+export interface BuildCtx extends Resolver {
+ /** Art-file location from an error stack, if any frame points into an art file. */
+ locFromStack(stack: string): string | undefined;
+ /** Art-file location of the current call site. */
+ callerLoc(): string | undefined;
+}
+
+export interface LayerOut {
+ name: string;
+ img: Img;
+}
+
+export interface BuildOut {
+ img: Img;
+ layers: LayerOut[];
+ trace?: Trace;
+ /** Set when the asset is animated (an anim, or places one). */
+ anim?: Timeline;
+}
+
+/** An anim's frames: count and durations (ms), from its frame() items or { frames, fps }. */
+export function animTimeline(def: AssetDef): Timeline {
+ const fps = def.opts.fps ?? 8;
+ if (!(fps > 0)) throw new PxError(`fps must be > 0, got ${fps}`);
+ const unit = 1000 / fps;
+ // frame() items may sit at the top level or inside layers; frame k of every list plays together.
+ let lists: Op[][] = [];
+ const walk = (items: Item[]) => {
+ lists.push(items.filter((v): v is Op => isOp(v) && v.name === "frame"));
+ for (const v of items) if (isLayer(v)) walk(v.items);
+ };
+ walk(def.items);
+ lists = lists.filter((l) => l.length);
+ const n = lists.length ? Math.max(...lists.map((l) => l.length)) : Math.max(1, Math.floor(def.opts.frames ?? 1));
+ const durations: number[] = [];
+ for (let i = 0; i < n; i++) {
+ // The first list that has frame i sets its duration.
+ const f = lists.find((l) => l[i])?.[i];
+ const fo = (f && isFrameOpts(f.args[0]) ? f.args[0] : {}) as FrameOpts;
+ const ms = fo.ms ?? unit * (fo.hold ?? 1);
+ if (!(ms > 0)) throw new PxError(`frame ${i} duration must be > 0`, f?.loc);
+ durations.push(Math.round(ms));
+ }
+ const loop = durations.reduce((a, d) => a + d, 0);
+ return { loop, step: durations.reduce(gcd), durations, once: def.opts.loop === false };
+}
+
+/** Index of the frame showing at time t. */
+export function frameAt(tl: Timeline, t: number): number {
+ const d = tl.durations!;
+ let tt = tl.once ? Math.min(Math.max(0, t), tl.loop - 1) : ((t % tl.loop) + tl.loop) % tl.loop;
+ for (let i = 0; i < d.length; i++) {
+ if (tt < d[i]) return i;
+ tt -= d[i];
+ }
+ return d.length - 1;
+}
+
+export function gcd(a: number, b: number): number {
+ a = Math.round(a); b = Math.round(b);
+ while (b) [a, b] = [b, a % b];
+ return a;
+}
+
+function isFrameOpts(v: unknown): boolean {
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !isOp(v) && !isLayer(v);
+}
+
+export function buildAsset(ctx: BuildCtx, def: AssetDef, seed: number, trace?: Trace, t = 0): BuildOut {
+ const { opts, pal } = def;
+ const tl = def.kind === "anim" ? animTimeline(def) : undefined;
+ const frame = tl ? frameAt(tl, t) : 0, frames = tl ? tl.durations!.length : 1;
+ let base: Img;
+ if (def.kind === "scene") {
+ if (!opts.w || !opts.h) throw new PxError("scene needs { w, h }");
+ base = new Img(opts.w, opts.h);
+ if (opts.bg) {
+ const bg = pal.resolve(opts.bg);
+ if (bg !== null) base.fill(bg);
+ }
+ } else if (opts.base) {
+ base = ctx.image(opts.base, seed, t).copy();
+ } else {
+ let { w, h } = opts;
+ if (!w || !h) {
+ const s = inferSize(def.items);
+ if (opts.mx) s.w = opts.mx === "c" ? 2 * s.w - 1 : 2 * s.w;
+ if (opts.my) s.h = opts.my === "c" ? 2 * s.h - 1 : 2 * s.h;
+ w ??= s.w;
+ h ??= s.h;
+ }
+ if (!(w >= 1 && h >= 1)) throw new PxError("no size: give { w, h } or a grid string");
+ base = new Img(w, h);
+ }
+
+ // Current layer being painted, so traced frames show the composite in progress.
+ let cur: { img: Img; opts: LayerOpts } | undefined;
+ const snap = trace
+ ? (label: string, loc?: string) => {
+ if (!cur) return trace.record(label, loc, base);
+ const o = base.copy();
+ blend(o, cur.img, cur.opts, pal);
+ trace.record(label, loc, o);
+ }
+ : undefined;
+ if (snap && def.kind === "scene") snap("background", def.loc);
+
+ const hook = (c: Canvas) => {
+ if (!snap) return;
+ c.onOp = (name, args) => snap(`${name}(${fmtArgs(args)})`, c.loc ?? ctx.callerLoc());
+ };
+
+ const layers: LayerOut[] = [];
+ // Pixels of solid / wall layers, for lighting().
+ let solid: Uint8Array | undefined, wall: Uint8Array | undefined, unlit: Uint8Array | undefined;
+ const timed = (c: Canvas) => {
+ c.t = t;
+ c.frame = frame;
+ c.frames = frames;
+ c.inAnim = !!tl;
+ return c;
+ };
+ const main = timed(new Canvas(base, pal, ctx, 0, 0, seed));
+ hook(main);
+ // After lighting(), pixels it changed still count as their palette color for glow().
+ let preLight: { before: Uint32Array; after: Uint32Array } | undefined;
+ const keyed = () => {
+ if (!preLight) return base.data;
+ const k = base.data.slice();
+ for (let i = 0; i < k.length; i++) if (k[i] === preLight.after[i]) k[i] = preLight.before[i];
+ return k;
+ };
+ const onPass: OnPass = (name, args, loc) => {
+ if (name === "glow") {
+ base.data.set(applyGlow(base, args[0] as string | string[], (args[1] ?? {}) as GlowOpts, pal, keyed()).data);
+ snap?.("glow", loc);
+ return;
+ }
+ const lo = (args[0] ?? {}) as LightingOpts;
+ const none = () => new Uint8Array(base.data.length);
+ const lit = applyLighting(base, { solid: solid ?? none(), wall: wall ?? none(), unlit }, base.lamps ?? [], lo, pal);
+ if (base.norm) trace?.record("normal map", loc, normalImage(base));
+ trace?.record("light map", loc, lit.map);
+ const before = preLight ? keyed() : base.data.slice();
+ base.data.set(lit.img.data);
+ preLight = { before, after: base.data.slice() };
+ base.lamps = undefined; // consumed: stamping this lit asset elsewhere doesn't light twice
+ snap?.("lighting", loc);
+ };
+ runItems(ctx, def.items, main, def.loc, onPass, (l) => {
+ const limg = new Img(base.w, base.h);
+ const lc = timed(new Canvas(limg, pal, ctx, l.opts.x ?? 0, l.opts.y ?? 0, seed));
+ lc.below = base;
+ hook(lc);
+ cur = { img: limg, opts: l.opts };
+ try {
+ runItems(ctx, l.items, lc, l.loc);
+ } catch (e) {
+ throw wrap(e, (st) => ctx.locFromStack(st)).within(`layer '${l.name}'`, l.loc);
+ } finally {
+ cur = undefined;
+ }
+ if (!l.opts.hidden) {
+ blend(base, limg, l.opts, pal);
+ if (l.opts.solid || l.opts.wall) {
+ const m = l.opts.solid ? (solid ??= new Uint8Array(base.data.length)) : (wall ??= new Uint8Array(base.data.length));
+ for (let i = 0; i < m.length; i++) if (limg.data[i] !== TRANSPARENT) m[i] = 1;
+ }
+ // Track which visible pixels came from unlit layers (later layers cover them again).
+ if (l.opts.unlit || unlit) {
+ unlit ??= new Uint8Array(base.data.length);
+ const v = l.opts.unlit ? 1 : 0;
+ for (let i = 0; i < unlit.length; i++) if (limg.data[i] !== TRANSPARENT) unlit[i] = v;
+ }
+ }
+ layers.push({ name: l.name, img: limg });
+ snap?.(`layer '${l.name}'${l.opts.hidden ? " (hidden)" : ""}`, l.loc);
+ });
+
+ const img = finish(base, def, pal, trace);
+ trace?.finish(img);
+ return { img, layers, trace, anim: tl };
+}
+
+/** Whole-image passes (lighting, glow) that run on everything drawn before them. */
+type OnPass = (name: "lighting" | "glow", args: unknown[], loc?: string) => void;
+
+/** Run body items in order on a canvas. Layers go to `onLayer` (not allowed inside layers). */
+function runItems(
+ ctx: BuildCtx, items: Item[], c: Canvas, ownerLoc: string | undefined,
+ onPass?: OnPass, onLayer?: (l: Layer) => void, inFrame = false,
+): void {
+ let frameNo = 0;
+ items.forEach((item, i) => {
+ if (inFrame && isOp(item) && item.name === "frame") throw new PxError("frame() can't be nested in another frame()", item.loc);
+ if (typeof item === "string") {
+ c.loc = ownerLoc;
+ try { c.grid(0, 0, item); } catch (e) { throw wrap(e).within(`grid #${i + 1}`, ownerLoc); }
+ } else if (isOp(item)) {
+ c.loc = item.loc;
+ try {
+ if (item.name === "frame") {
+ if (!c.inAnim) throw new PxError("frame() only goes inside an anim (directly or in its layers)");
+ if (frameNo++ === c.frame) {
+ const inner = (isFrameOpts(item.args[0]) ? item.args.slice(1) : item.args) as Item[];
+ runItems(ctx, inner, c, item.loc, undefined, undefined, true);
+ }
+ } else if (item.name === "clip") {
+ const [region, ...inner] = item.args as [Region, ...Item[]];
+ c.clip(region, () => runItems(ctx, inner, c, item.loc));
+ } else if (item.name === "lighting" || item.name === "glow") {
+ if (!onPass) throw new PxError(`${item.name}() goes directly in a sprite or scene, after what it affects, not inside a layer or clip`);
+ onPass(item.name, item.args, item.loc);
+ } else {
+ (c as unknown as Record<string, (...a: unknown[]) => void>)[item.name](...item.args);
+ }
+ } catch (e) {
+ throw wrap(e, (st) => ctx.locFromStack(st)).within(item.name, item.loc);
+ }
+ } else if (typeof item === "function") {
+ c.loc = undefined;
+ try { item(c); } catch (e) { throw wrap(e, (st) => ctx.locFromStack(st)).within("function", ownerLoc); }
+ } else if (isLayer(item)) {
+ if (!onLayer) throw new PxError(`layer '${item.name}' can't be nested inside another layer`, item.loc);
+ onLayer(item);
+ } else {
+ throw new PxError(`item #${i + 1} is ${describe(item)}; expected a grid string, an op, a function or a layer`, ownerLoc);
+ }
+ });
+}
+
+function describe(v: unknown): string {
+ if (Array.isArray(v)) return "an array (spread it, or pass items directly)";
+ return v === null ? "null" : `a ${typeof v}`;
+}
+
+/** Size from grid strings, including those inside layers (offset by the layer position). */
+function inferSize(items: Item[]): { w: number; h: number } {
+ let w = 0, h = 0;
+ const walk = (list: Item[], ox: number, oy: number) => {
+ for (const v of list) {
+ if (typeof v === "string") {
+ const s = gridSize(gridRows(v));
+ w = Math.max(w, s.w + ox);
+ h = Math.max(h, s.h + oy);
+ } else if (isLayer(v)) walk(v.items, ox + (v.opts.x ?? 0), oy + (v.opts.y ?? 0));
+ else if (isOp(v) && v.name === "frame") walk((isFrameOpts(v.args[0]) ? v.args.slice(1) : v.args) as Item[], ox, oy);
+ }
+ };
+ walk(items, 0, 0);
+ return { w, h };
+}
+
+function finish(img: Img, def: AssetDef, pal: Palette, trace?: Trace): Img {
+ const o = def.opts;
+ const step = (label: string, f: () => Img | void) => {
+ const r = f();
+ if (r) img = r;
+ trace?.record(label, def.loc, img);
+ };
+ if (o.mx) step("mirror x", () => img.mirror("x"));
+ if (o.my) step("mirror y", () => img.mirror("y"));
+ if (o.swap) {
+ const sw = o.swap;
+ step(`swap ${fmtArgs([sw])}`, () => {
+ const m = new Map<Color, Color>();
+ for (const k of Object.keys(sw)) {
+ const a = pal.resolve(k), b = pal.resolve(sw[k]);
+ if (a !== null && b !== null) m.set(a, b);
+ }
+ return img.remap(m);
+ });
+ }
+ if (o.flip) step(`flip ${o.flip}`, () => img.flip(o.flip!));
+ if (o.rot) step(`rot ${o.rot}`, () => img.rot(o.rot!));
+ if (o.outline) step(`outline ${o.outline}`, () => img.outline(solid(pal, o.outline!), false));
+ if (o.outline8) step(`outline8 ${o.outline8}`, () => img.outline(solid(pal, o.outline8!), true));
+ if (o.crop) step("crop", () => img.crop());
+ return img;
+}
+
+function solid(pal: Palette, spec: string): Color {
+ const c = pal.resolve(spec);
+ if (c === null || c === TRANSPARENT) throw new PxError(`outline color must be a visible color, got '${spec}'`);
+ return c;
+}
+
+/** Composite a layer onto img: draw it, or (shade/light) step what's below where it's opaque. */
+export function blend(img: Img, limg: Img, l: LayerOpts, pal: Palette): void {
+ if (limg.lamps?.length) (img.lamps ??= []).push(...limg.lamps);
+ const density = l.density ?? 1;
+ const mode = l.shade ?? l.light;
+ if (mode === undefined || mode === false) {
+ if (density >= 1) return img.blit(limg, 0, 0);
+ for (let i = 0; i < img.data.length; i++) {
+ const c = limg.data[i];
+ if (c === TRANSPARENT || bayer(i % img.w, Math.floor(i / img.w)) >= density) continue;
+ img.data[i] = c;
+ if (limg.norm) img.normals().set(limg.norm.subarray(i * 3, i * 3 + 3), i * 3);
+ else if (img.norm) img.norm[i * 3 + 2] = 0;
+ }
+ return;
+ }
+ let map: Map<Color, Color>, steps = 1;
+ if (typeof mode === "object") {
+ map = new Map();
+ for (const k of Object.keys(mode)) {
+ const a = pal.resolve(k), b = pal.resolve(mode[k]);
+ if (a !== null && b !== null) map.set(a, b);
+ }
+ } else {
+ map = pal.stepMap(l.shade !== undefined && l.shade !== false ? -1 : 1);
+ if (typeof mode === "number") steps = mode;
+ }
+ for (let i = 0; i < img.data.length; i++) {
+ if (limg.data[i] === TRANSPARENT) continue;
+ if (density < 1 && bayer(i % img.w, Math.floor(i / img.w)) >= density) continue;
+ let c = img.data[i];
+ for (let s = 0; s < steps; s++) c = map.get(c) ?? c;
+ img.data[i] = c;
+ }
+}
diff --git a/src/core/canvas.ts b/src/core/canvas.ts
new file mode 100644
index 0000000..d006e5c
--- /dev/null
+++ b/src/core/canvas.ts
@@ -0,0 +1,553 @@
+import { type Color, TRANSPARENT } from "./color.ts";
+import { Img } from "./image.ts";
+import type { Palette, Resolved } from "./palette.ts";
+import { PxError } from "./errors.ts";
+import { glyph, lineWidth } from "./font.ts";
+import type { BumpOpts, LampOpts, PlaceOpts, ScatterOpts, TextOpts, Timeline, TilemapOpts, WireOpts } from "./model.ts";
+import { bump, dirOf, setNormal } from "./normals.ts";
+import { bayer, colorList, gridRows, hash, inPoly, polyBounds, type Region, regionPred, rng } from "./util.ts";
+
+/** How a canvas reaches other assets. */
+export interface Resolver {
+ /**
+ * Built image of an asset; seed != 0 rerolls its random choices; t is the time in ms (animated
+ * assets). `track` false: don't make the caller animated by this lookup (frozen frames).
+ */
+ image(name: string, seed: number, t?: number, track?: boolean): Img;
+ /** How the asset changes over time, or undefined if it's still. */
+ timeline(name: string, seed: number): Timeline | undefined;
+ /** Names a reference can stand for: group members, glob matches, or itself. */
+ candidates(name: string): string[];
+}
+
+type Pred = (x: number, y: number) => boolean;
+
+/**
+ * Drawing surface over an image. Coordinates are relative to (ox, oy); colors are palette
+ * keys, "#hex", "." (skip) or "_" (erase). All writes go through plot(), which honours clip().
+ */
+export class Canvas {
+ img: Img;
+ pal: Palette;
+ res: Resolver;
+ ox: number;
+ oy: number;
+ /** Reseed offset applied to every random choice made on this canvas. */
+ seed: number;
+ /** Time in ms of this build: placed anims show the frame at this time. */
+ t = 0;
+ /** Inside an anim: the frame being drawn and the frame count (for procedural animation). */
+ frame = 0;
+ frames = 1;
+ /** Building an anim (frame() items allowed). */
+ inAnim = false;
+ /** Composite below the current layer (absolute coords), for `below` masks. */
+ below?: Img;
+ /** Called after each top-level (non-nested) op call; used for tracing. */
+ onOp?: (name: string, args: unknown[]) => void;
+ /** Art-file location of the op item currently running (set by the builder). */
+ loc?: string;
+ private clipPred?: Pred;
+ /** Nesting depth of op calls (internal). */
+ _depth = 0;
+ private rev?: Map<Color, string>;
+
+ constructor(img: Img, pal: Palette, res: Resolver, ox = 0, oy = 0, seed = 0) {
+ this.img = img;
+ this.pal = pal;
+ this.res = res;
+ this.ox = ox;
+ this.oy = oy;
+ this.seed = seed;
+ }
+
+ /** Inside an anim: frame / frames, 0 (first frame) up to just below 1. */
+ get phase(): number { return this.frame / this.frames; }
+
+ get w(): number { return this.img.w; }
+ get h(): number { return this.img.h; }
+
+ color(c: unknown): Resolved {
+ return this.pal.resolve(c);
+ }
+
+ /** Write an already-resolved color (null = skip); true if it landed. */
+ plot(x: number, y: number, c: Resolved): boolean {
+ if (c === null) return false;
+ x = Math.floor(x);
+ y = Math.floor(y);
+ if (this.clipPred && !this.clipPred(x, y)) return false;
+ if (!this.img.inside(this.ox + x, this.oy + y)) return false;
+ this.img.set(this.ox + x, this.oy + y, c);
+ return true;
+ }
+
+ get(x: number, y: number): Color {
+ return this.img.get(this.ox + Math.floor(x), this.oy + Math.floor(y));
+ }
+
+ /** Palette key at (x, y): "." when transparent, "?" when not in the palette. */
+ key(x: number, y: number): string {
+ const c = this.get(x, y);
+ if (c === TRANSPARENT) return ".";
+ this.rev ??= this.pal.reverse();
+ return this.rev.get(c) ?? "?";
+ }
+
+ /** Pixel is one of `keys` ("*" = any opaque, "." = transparent). */
+ is(x: number, y: number, keys: string): boolean {
+ if (keys === ".") return this.get(x, y) === TRANSPARENT;
+ return this.colorTest(keys)(this.get(x, y));
+ }
+
+ /** Seeded random generator that follows this canvas's reseed offset. */
+ rng(seed = 1): () => number {
+ return rng(hash(seed, 0, this.seed));
+ }
+
+ private colorTest(on: string): (c: Color) => boolean {
+ if (on === "*") return (c) => c !== TRANSPARENT;
+ const set = new Set<Color>();
+ for (const k of colorList(on)) {
+ const c = this.color(k);
+ if (c !== null) set.add(c);
+ }
+ return (c) => set.has(c);
+ }
+
+ /** Mask predicate over canvas coords; `below` reads the composite under this layer. */
+ maskAt(on: string | undefined, below = false): Pred {
+ if (on === undefined) return () => true;
+ const test = this.colorTest(on);
+ if (below) {
+ const b = this.below;
+ if (!b) return (x, y) => test(this.get(x, y));
+ return (x, y) => {
+ const own = this.get(x, y);
+ return test(own !== TRANSPARENT ? own : b.get(this.ox + x, this.oy + y));
+ };
+ }
+ return (x, y) => test(this.get(x, y));
+ }
+
+ /** Run `fn` with drawing restricted to `region` (nests by intersection). */
+ clip(region: Region, fn: () => void): void {
+ const prev = this.clipPred, p = regionPred(region);
+ this.clipPred = prev ? (x, y) => prev(x, y) && p(x, y) : p;
+ try { fn(); } finally { this.clipPred = prev; }
+ }
+
+ // ---------------------------------------------------------------- shapes
+
+ px(x: number, y: number, c: string): void {
+ this.plot(x, y, this.color(c));
+ }
+
+ rect(x: number, y: number, w: number, h: number, c: string): void {
+ const col = this.color(c);
+ for (let yy = y; yy < y + h; yy++) for (let xx = x; xx < x + w; xx++) this.plot(xx, yy, col);
+ }
+
+ box(x: number, y: number, w: number, h: number, c: string): void {
+ const col = this.color(c);
+ for (let xx = x; xx < x + w; xx++) { this.plot(xx, y, col); this.plot(xx, y + h - 1, col); }
+ for (let yy = y + 1; yy < y + h - 1; yy++) { this.plot(x, yy, col); this.plot(x + w - 1, yy, col); }
+ }
+
+ /** Bresenham line; width > 1 uses a round brush. */
+ line(x0: number, y0: number, x1: number, y1: number, c: string, width = 1): void {
+ const col = this.color(c);
+ const brush: number[] = [];
+ if (width > 1) {
+ const f = width % 2 === 0 ? 0.5 : 0, r2 = (width / 2) ** 2;
+ const lo = -Math.floor((width - 1) / 2), hi = Math.ceil((width - 1) / 2);
+ for (let oy = lo; oy <= hi; oy++)
+ for (let ox = lo; ox <= hi; ox++) if ((ox - f) ** 2 + (oy - f) ** 2 <= r2) brush.push(ox, oy);
+ } else brush.push(0, 0);
+ x0 = Math.floor(x0); y0 = Math.floor(y0); x1 = Math.floor(x1); y1 = Math.floor(y1);
+ const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0);
+ const sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1;
+ let err = dx + dy;
+ for (;;) {
+ for (let i = 0; i < brush.length; i += 2) this.plot(x0 + brush[i], y0 + brush[i + 1], col);
+ if (x0 === x1 && y0 === y1) break;
+ const e2 = 2 * err;
+ if (e2 >= dy) { err += dy; x0 += sx; }
+ if (e2 <= dx) { err += dx; y0 += sy; }
+ }
+ }
+
+ hline(x: number, y: number, len: number, c: string): void { this.rect(x, y, len, 1, c); }
+ vline(x: number, y: number, len: number, c: string): void { this.rect(x, y, 1, len, c); }
+
+ /** Ellipse centered at (cx, cy); `ring` draws only the 1px border. */
+ ellipse(cx: number, cy: number, rx: number, ry: number, c: string, ring = false): void {
+ const col = this.color(c);
+ const ax = rx + 0.5, ay = ry + 0.5;
+ const inside = (x: number, y: number) => (x / ax) ** 2 + (y / ay) ** 2 <= 1;
+ for (let y = -ry; y <= ry; y++)
+ for (let x = -rx; x <= rx; x++)
+ if (inside(x, y) && (!ring || !(inside(x - 1, y) && inside(x + 1, y) && inside(x, y - 1) && inside(x, y + 1))))
+ this.plot(cx + x, cy + y, col);
+ }
+
+ circ(cx: number, cy: number, r: number, c: string): void { this.ellipse(cx, cy, r, r, c); }
+ ring(cx: number, cy: number, r: number, c: string): void { this.ellipse(cx, cy, r, r, c, true); }
+
+ /** Filled polygon [x0,y0, x1,y1, ...] with vertices on pixel corners. */
+ poly(pts: number[], c: string): void {
+ if (!Array.isArray(pts) || pts.length < 6 || pts.length % 2) throw new PxError("poly needs [x0,y0, x1,y1, x2,y2, ...]");
+ const col = this.color(c), inside = inPoly(pts), b = polyBounds(pts);
+ for (let y = Math.floor(b.y0); y < Math.ceil(b.y1); y++)
+ for (let x = Math.floor(b.x0); x < Math.ceil(b.x1); x++) if (inside(x, y)) this.plot(x, y, col);
+ }
+
+ /** 4-connected flood fill of the region containing (x, y). */
+ fill(x: number, y: number, c: string): void {
+ const col = this.color(c);
+ if (col === null) return;
+ const img = this.img;
+ const sx = this.ox + Math.floor(x), sy = this.oy + Math.floor(y);
+ if (!img.inside(sx, sy)) return;
+ const target = img.get(sx, sy);
+ if (target === col) return;
+ const seen = new Uint8Array(img.w * img.h);
+ const stack = [sx, sy];
+ while (stack.length) {
+ const py = stack.pop()!, px = stack.pop()!;
+ if (!img.inside(px, py)) continue;
+ const i = py * img.w + px;
+ if (seen[i] || img.data[i] !== target) continue;
+ seen[i] = 1;
+ this.plot(px - this.ox, py - this.oy, col);
+ stack.push(px + 1, py, px - 1, py, px, py + 1, px, py - 1);
+ }
+ }
+
+ // ---------------------------------------------------------------- texture
+
+ /** Ordered dither: c2 covers `density` of the area, c1 the rest. */
+ dither(x: number, y: number, w: number, h: number, c1: string, c2: string, density = 0.5): void {
+ const a = this.color(c1), b = this.color(c2);
+ for (let yy = y; yy < y + h; yy++)
+ for (let xx = x; xx < x + w; xx++) this.plot(xx, yy, bayer(xx, yy) < density ? b : a);
+ }
+
+ /** Banded gradient through colors with dithered seams. dir "v" (default) or "h"; soft 0..1. */
+ grad(x: number, y: number, w: number, h: number, colors: string | string[], dir: "v" | "h" = "v", soft = 0.5): void {
+ const cols = colorList(colors).map((c) => this.color(c));
+ const n = cols.length;
+ if (!n) throw new PxError("grad needs at least one color");
+ const len = dir === "h" ? w : h;
+ for (let yy = 0; yy < h; yy++)
+ for (let xx = 0; xx < w; xx++) {
+ const pos = dir === "h" ? xx : yy;
+ const f = len > 1 ? (pos / (len - 1)) * (n - 1) : 0;
+ const i = Math.floor(f);
+ let col: Resolved;
+ if (i >= n - 1) col = cols[n - 1];
+ else {
+ let t = f - i;
+ t = soft > 0 ? (t - 0.5) / soft + 0.5 : t >= 0.5 ? 1 : 0;
+ col = bayer(x + xx, y + yy) < t ? cols[i + 1] : cols[i];
+ }
+ this.plot(x + xx, y + yy, col);
+ }
+ }
+
+ /** Deterministic scatter of colors over `density` of the area; `on` limits it to those keys. */
+ noise(x: number, y: number, w: number, h: number, colors: string | string[], density = 0.1, seed = 1, on?: string): void {
+ const cols = colorList(colors).map((c) => this.color(c));
+ const ok = this.maskAt(on);
+ const r = this.rng(seed);
+ for (let yy = y; yy < y + h; yy++)
+ for (let xx = x; xx < x + w; xx++)
+ if (r() < density) {
+ const pick = cols[Math.floor(r() * cols.length)];
+ if (ok(xx, yy)) this.plot(xx, yy, pick);
+ }
+ }
+
+ /** Apply a color map inside a region `steps` times; density < 1 dithers it. */
+ remap(map: Map<Color, Color>, where?: Region, steps = 1, density = 1): void {
+ const ok = regionPred(where);
+ for (let y = -this.oy; y < this.img.h - this.oy; y++)
+ for (let x = -this.ox; x < this.img.w - this.ox; x++) {
+ if (!ok(x, y) || (density < 1 && bayer(x, y) >= density)) continue;
+ let c = this.get(x, y);
+ for (let i = 0; i < steps; i++) c = map.get(c) ?? c;
+ this.plot(x, y, c);
+ }
+ }
+
+ /** Recolor { m: "M" } inside a region. */
+ recolor(map: Record<string, string>, where?: Region, density = 1): void {
+ this.remap(this.swapMap(map), where, 1, density);
+ }
+
+ /** Step colors darker along the palette ramps inside a region. */
+ shade(where?: Region, steps = 1, density = 1): void {
+ this.remap(this.pal.stepMap(-1), where, steps, density);
+ }
+
+ /** Step colors lighter along the palette ramps inside a region. */
+ light(where?: Region, steps = 1, density = 1): void {
+ this.remap(this.pal.stepMap(1), where, steps, density);
+ }
+
+ swapMap(swap: Record<string, string>): Map<Color, Color> {
+ const m = new Map<Color, Color>();
+ for (const from of Object.keys(swap)) {
+ const a = this.color(from), b = this.color(swap[from]);
+ if (a !== null && b !== null) m.set(a, b);
+ }
+ return m;
+ }
+
+ // ---------------------------------------------------------------- assets
+
+ /** Pick one candidate of `name` and transform it; random choices seeded by (a, b). */
+ asset(name: string, opts: PlaceOpts = {}, a = 0, b = 0): Img {
+ const list = this.res.candidates(name);
+ const r = rng(hash(a, b, (opts.seed ?? 0) + this.seed));
+ let inner = this.seed;
+ if (opts.reseed === true) inner += (hash(a, b, opts.seed ?? 0) % 99991) + 1;
+ else if (typeof opts.reseed === "number") inner += opts.reseed;
+ const pick = list[Math.floor(r() * list.length)];
+ let t = this.t, track = true;
+ if (opts.frame !== undefined || opts.delay || opts.rdelay) {
+ const tl = this.res.timeline(pick, inner);
+ if (tl) {
+ if (opts.frame !== undefined) {
+ t = frameStart(tl, opts.frame);
+ track = false;
+ } else {
+ // Shifts snap to the anim's step so combined timelines stay on a frame grid.
+ let d = opts.delay ?? 0;
+ if (opts.rdelay) d += rng(hash(a, b, (opts.seed ?? 0) + this.seed + 7919))() * tl.loop;
+ t += Math.round(d / tl.step) * tl.step;
+ }
+ }
+ }
+ let src = this.res.image(pick, inner, t, track);
+ const swap = opts.rswap ? opts.rswap[Math.floor(r() * opts.rswap.length)] : opts.swap;
+ if (swap && Object.keys(swap).length) src = src.remap(this.swapMap(swap));
+ if (opts.flip) src = src.flip(opts.flip);
+ if (opts.rflip) {
+ let f = "";
+ for (const ax of opts.rflip) if ((ax === "x" || ax === "y") && r() < 0.5) f += ax;
+ if (f) src = src.flip(f as "x" | "y" | "xy");
+ }
+ if (opts.rot) src = src.rot(opts.rot);
+ return src;
+ }
+
+ /** Draw an image at canvas coords; with a predicate, only onto pixels it accepts. Lamps come along. */
+ put(src: Img, x: number, y: number, ok?: Pred): void {
+ if (src.lamps?.length) {
+ const dx = this.ox + Math.floor(x), dy = this.oy + Math.floor(y);
+ (this.img.lamps ??= []).push(...src.lamps.map((l) => ({ ...l, x: l.x + dx, y: l.y + dy })));
+ }
+ if (!ok && !this.clipPred) {
+ this.img.blit(src, this.ox + x, this.oy + y);
+ return;
+ }
+ for (let yy = 0; yy < src.h; yy++)
+ for (let xx = 0; xx < src.w; xx++) {
+ const c = src.data[yy * src.w + xx];
+ if (c === TRANSPARENT || (ok && !ok(x + xx, y + yy)) || !this.plot(x + xx, y + yy, c)) continue;
+ const i = (this.oy + Math.floor(y) + yy) * this.img.w + this.ox + Math.floor(x) + xx, j = yy * src.w + xx;
+ if (src.norm) {
+ const n = this.img.normals();
+ n.set(src.norm.subarray(j * 3, j * 3 + 3), i * 3);
+ } else if (this.img.norm) this.img.norm[i * 3 + 2] = 0;
+ }
+ }
+
+ stamp(name: string, x = 0, y = 0, opts?: PlaceOpts): void {
+ this.put(this.asset(name, opts, x, y), x, y);
+ }
+
+ tile(name: string, x: number, y: number, cols = 1, rows = 1, opts?: PlaceOpts): void {
+ const step = this.res.image(this.res.candidates(name)[0], 0);
+ for (let r = 0; r < rows; r++)
+ for (let c = 0; c < cols; c++) {
+ const tx = x + c * step.w, ty = y + r * step.h;
+ this.put(this.asset(name, opts, tx, ty), tx, ty);
+ }
+ }
+
+ /** Tile `name` over an area; edge tiles are cut to fit. */
+ pattern(name: string, x: number, y: number, w: number, h: number, opts?: PlaceOpts): void {
+ const step = this.res.image(this.res.candidates(name)[0], 0);
+ for (let ty = y; ty < y + h; ty += step.h)
+ for (let tx = x; tx < x + w; tx += step.w) {
+ let src = this.asset(name, opts, tx, ty);
+ const cw = Math.min(src.w, x + w - tx), ch = Math.min(src.h, y + h - ty);
+ if (cw < src.w || ch < src.h) src = src.sub(0, 0, cw, ch);
+ this.put(src, tx, ty);
+ }
+ }
+
+ /** Character map of tiles: tilemap(`gg\ndd`, { map: { g: "grass" }, size: 16 }). */
+ tilemap(str: string, opts: TilemapOpts): void {
+ if (typeof str !== "string") throw new PxError("tilemap(str, { map, size }) needs the map string first");
+ if (!opts?.map) throw new PxError("tilemap needs { map: { char: assetName } }");
+ const rows = gridRows(str);
+ const x0 = opts.x ?? 0, y0 = opts.y ?? 0;
+ rows.forEach((row, r) => {
+ [...row].forEach((ch, i) => {
+ if (ch === "." || ch === " ") return;
+ const name = opts.map[ch];
+ if (!name) throw new PxError(`tilemap: no tile for '${ch}' (row ${r}, col ${i}); map has: ${Object.keys(opts.map).join(" ")}`);
+ const step = opts.w && opts.h ? null : this.res.image(this.res.candidates(name)[0], 0);
+ const tx = x0 + i * (opts.w ?? opts.size ?? step!.w), ty = y0 + r * (opts.h ?? opts.size ?? step!.h);
+ this.put(this.asset(name, opts, tx, ty), tx, ty);
+ });
+ });
+ }
+
+ /** Brush: `count` random picks of `name` centered at random points in the area. */
+ scatter(name: string, x: number, y: number, w: number, h: number, count: number, opts: ScatterOpts = {}): void {
+ const r = rng(hash(x * 31 + w, y * 17 + h, (opts.seed ?? 0) + this.seed));
+ const ok = this.maskAt(opts.on, opts.below);
+ let placed = 0, tries = 0;
+ while (placed < count && tries < count * 30) {
+ tries++;
+ const cx = x + Math.floor(r() * w), cy = y + Math.floor(r() * h);
+ if (!ok(cx, cy)) continue;
+ const src = this.asset(name, opts, cx, cy);
+ this.put(src, cx - Math.floor(src.w / 2), cy - Math.floor(src.h / 2), opts.clip ? ok : undefined);
+ placed++;
+ }
+ }
+
+ /** Grid string at (x, y): one char per pixel; "." keeps, "_" erases. */
+ grid(x: number, y: number, s: string): void {
+ gridRows(String(s)).forEach((row, r) => {
+ [...row].forEach((ch, i) => {
+ if (ch === "." || ch === " ") return;
+ let c: Resolved;
+ try { c = this.color(ch); } catch (e) {
+ throw new PxError(`${(e as Error).message} at grid row ${r}, col ${i}`);
+ }
+ this.plot(x + i, y + r, c);
+ });
+ });
+ }
+
+ /** Hanging cable sagging `sag` px; `hang` stamps an asset/group under it every `every` px. */
+ wire(x0: number, y0: number, x1: number, y1: number, sag: number, c: string, opts: WireOpts = {}): void {
+ const at = (t: number): [number, number] => [x0 + (x1 - x0) * t, y0 + (y1 - y0) * t + sag * 4 * t * (1 - t)];
+ const n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) + Math.abs(sag) * 2 + 1;
+ let px = x0, py = y0;
+ for (let i = 1; i <= n; i++) {
+ const [fx, fy] = at(i / n);
+ const qx = Math.round(fx), qy = Math.round(fy);
+ this.line(px, py, qx, qy, c);
+ px = qx; py = qy;
+ }
+ if (!opts.hang || x1 === x0) return;
+ const every = opts.every ?? 6, span = Math.abs(x1 - x0), dir = Math.sign(x1 - x0);
+ for (let d = opts.start ?? Math.floor(every / 2); d < span; d += every) {
+ const [, fy] = at(d / span);
+ const hx = x0 + dir * d, hy = Math.round(fy);
+ const src = this.asset(opts.hang, opts, hx, hy);
+ this.put(src, hx - Math.floor(src.w / 2), hy + 1);
+ }
+ }
+
+ /** Light source at (x, y): lights the scene when a lighting() item runs; travels with stamps. */
+ lamp(x: number, y: number, opts: LampOpts = {}): void {
+ const c = this.color(opts.color ?? "#fff");
+ if (c === null || c === TRANSPARENT) throw new PxError(`lamp color must be a visible color, got '${opts.color}'`);
+ const r = opts.r ?? 32;
+ if (!(r > 0)) throw new PxError(`lamp r must be > 0, got ${r}`);
+ (this.img.lamps ??= []).push({ x: this.ox + Math.floor(x), y: this.oy + Math.floor(y), r, color: c, power: opts.power ?? 1, z: opts.z ?? 8 });
+ }
+
+ /** Generate surface normals for this canvas's opaque pixels (see normals.ts). */
+ bump(shape: BumpOpts["shape"] = "dome", opts: BumpOpts = {}): void {
+ const { w, h } = this.img, mask = new Uint8Array(w * h);
+ const keys = this.maskAt(opts.on ?? "*"), inside = opts.where === undefined ? undefined : regionPred(opts.where);
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const cx = x - this.ox, cy = y - this.oy;
+ if (keys(cx, cy) && (!inside || inside(cx, cy)) && (!this.clipPred || this.clipPred(cx, cy))) mask[y * w + x] = 1;
+ }
+ bump(this.img, mask, { ...opts, shape });
+ }
+
+ /** Paint normals with a numpad grid: 8 faces up, 3 down-right, 5 the viewer; qweasdzxc are softer. */
+ normals(x: number, y: number, s: string): void {
+ gridRows(String(s)).forEach((row, r) => {
+ [...row].forEach((ch, i) => {
+ let d;
+ try { d = dirOf(ch); } catch (e) { throw new PxError(`${(e as Error).message} at row ${r}, col ${i}`); }
+ const px = Math.floor(x) + i, py = Math.floor(y) + r;
+ if (d === null || (this.clipPred && !this.clipPred(px, py)) || !this.img.inside(this.ox + px, this.oy + py)) return;
+ const k = (this.oy + py) * this.img.w + this.ox + px;
+ if (d === "none") { if (this.img.norm) this.img.norm[k * 3 + 2] = 0; }
+ else setNormal(this.img.normals(), k, d[0], d[1], d[2]);
+ });
+ });
+ }
+
+ /** Text in the built-in 3x5 font. */
+ text(x: number, y: number, s: string, c: string, opts: TextOpts = {}): void {
+ s = String(s);
+ if (opts.shadow) this.text(x + 1, y + 1, s, opts.shadow, { ...opts, shadow: undefined });
+ const col = this.color(c);
+ const sc = opts.scale ?? 1, gap = opts.gap ?? 1, lead = opts.lead ?? 1;
+ let ly = y;
+ for (const line of s.split("\n")) {
+ const lw = lineWidth(line, opts);
+ let cx = opts.align === "c" ? x - Math.floor(lw / 2) : opts.align === "r" ? x - lw + 1 : x;
+ for (const ch of line) {
+ const rows = glyph(ch);
+ rows.forEach((row, r) => {
+ for (let b = 0; b < row.length; b++)
+ if (row[b] === "#")
+ for (let yy = 0; yy < sc; yy++) for (let xx = 0; xx < sc; xx++) this.plot(cx + b * sc + xx, ly + r * sc + yy, col);
+ });
+ cx += (rows[0].length + gap) * sc;
+ }
+ ly += (5 + lead) * sc;
+ }
+ }
+}
+
+/** Start time (ms) of frame `n` of a timeline. */
+export function frameStart(tl: Timeline, n: number): number {
+ if (!tl.durations) return Math.max(0, Math.floor(n)) * tl.step;
+ const d = tl.durations, k = ((Math.floor(n) % d.length) + d.length) % d.length;
+ let t = 0;
+ for (let i = 0; i < k; i++) t += d[i];
+ return t;
+}
+
+/** Ops callable from art files; each top-level call can be traced as one painting step. */
+export const OPS = [
+ "px", "rect", "box", "line", "hline", "vline", "ellipse", "circ", "ring", "poly", "fill",
+ "dither", "grad", "noise", "recolor", "shade", "light",
+ "stamp", "tile", "pattern", "tilemap", "scatter", "grid", "wire", "text", "lamp", "bump", "normals",
+] as const;
+export type OpName = (typeof OPS)[number];
+
+// Wrap ops so only the outermost call reports to onOp (ring -> ellipse, text -> plot, ...).
+for (const name of OPS) {
+ const proto = Canvas.prototype as unknown as Record<string, (...a: unknown[]) => unknown>;
+ const fn = proto[name];
+ proto[name] = function (this: Canvas, ...args: unknown[]) {
+ this._depth++;
+ let ok = false;
+ try {
+ const r = fn.apply(this, args);
+ ok = true;
+ return r;
+ } finally {
+ this._depth--;
+ if (ok && this._depth === 0 && this.onOp) this.onOp(name, args);
+ }
+ };
+}
diff --git a/src/core/color.ts b/src/core/color.ts
new file mode 100644
index 0000000..e139a61
--- /dev/null
+++ b/src/core/color.ts
@@ -0,0 +1,35 @@
+// Colors are packed 0xRRGGBBAA unsigned integers. 0 is fully transparent.
+export type Color = number;
+
+export const TRANSPARENT: Color = 0;
+
+export function pack(r: number, g: number, b: number, a = 255): Color {
+ return (((r & 255) << 24) | ((g & 255) << 16) | ((b & 255) << 8) | (a & 255)) >>> 0;
+}
+
+export function channels(c: Color): [number, number, number, number] {
+ return [(c >>> 24) & 255, (c >>> 16) & 255, (c >>> 8) & 255, c & 255];
+}
+
+/** "#rgb", "#rgba", "#rrggbb", "#rrggbbaa" (leading # optional). */
+export function parseHex(s: string): Color | undefined {
+ let h = s.startsWith("#") ? s.slice(1) : s;
+ if (!/^[0-9a-fA-F]+$/.test(h)) return undefined;
+ if (h.length === 3 || h.length === 4) h = h.replace(/./g, (d) => d + d);
+ if (h.length === 6) h += "ff";
+ if (h.length !== 8) return undefined;
+ const c = parseInt(h, 16) >>> 0;
+ return (c & 255) === 0 ? TRANSPARENT : c;
+}
+
+export function toHex(c: Color): string {
+ const [r, g, b, a] = channels(c);
+ const h = (n: number) => n.toString(16).padStart(2, "0");
+ return "#" + h(r) + h(g) + h(b) + (a === 255 ? "" : h(a));
+}
+
+/** Darken toward black by k (0..1); result is opaque. */
+export function darken(c: Color, k: number): Color {
+ const [r, g, b] = channels(c);
+ return pack(r * (1 - k), g * (1 - k), b * (1 - k));
+}
diff --git a/src/core/errors.ts b/src/core/errors.ts
new file mode 100644
index 0000000..8b337a2
--- /dev/null
+++ b/src/core/errors.ts
@@ -0,0 +1,74 @@
+/**
+ * Errors carry the art-file location (file:line:col) and the chain of assets/layers/ops
+ * being built, so a message reads like:
+ * shop.px.js:42:5: sprite 'shop' > layer 'front' > rect: unknown color key 'z' (have: k Z z ...)
+ */
+export class PxError extends Error {
+ loc?: string;
+ path: string[];
+ detail: string;
+
+ constructor(detail: string, loc?: string, path: string[] = []) {
+ super(detail);
+ this.name = "PxError";
+ this.detail = detail;
+ this.loc = loc;
+ this.path = path;
+ this.message = this.format();
+ }
+
+ format(): string {
+ const where = this.loc ? this.loc + ": " : "";
+ const path = this.path.length ? this.path.join(" > ") + ": " : "";
+ return where + path + this.detail;
+ }
+
+ /** Prefix a context step (e.g. "layer 'x'"); keeps the innermost location. */
+ within(step: string, loc?: string): this {
+ this.path.unshift(step);
+ if (!this.loc && loc) this.loc = loc;
+ this.message = this.format();
+ return this;
+ }
+}
+
+/** Wrap any thrown value as a PxError, pulling an art-file location out of its stack. */
+export function wrap(e: unknown, locFromStack?: (stack: string) => string | undefined): PxError {
+ if (e instanceof PxError) {
+ if (!e.loc && e.stack && locFromStack) {
+ const loc = locFromStack(e.stack);
+ if (loc) { e.loc = loc; e.message = e.format(); }
+ }
+ return e;
+ }
+ // Errors from the art-file sandbox come from another realm: duck-type them.
+ const isErr = typeof e === "object" && e !== null && "message" in e;
+ const message = isErr ? String((e as Error).message) : String(e);
+ const stack = isErr ? (e as Error).stack : undefined;
+ const loc = stack && locFromStack ? locFromStack(stack) : undefined;
+ return new PxError(message, loc);
+}
+
+/** Levenshtein-based suggestion among candidates. */
+export function didYouMean(name: string, candidates: Iterable<string>): string {
+ let best = "", bestD = Infinity;
+ for (const c of candidates) {
+ const d = distance(name.toLowerCase(), c.toLowerCase());
+ if (d < bestD) { bestD = d; best = c; }
+ }
+ return best && bestD <= Math.max(2, Math.floor(name.length / 3)) ? ` (did you mean '${best}'?)` : "";
+}
+
+function distance(a: string, b: string): number {
+ const prev = Array.from({ length: b.length + 1 }, (_, i) => i);
+ for (let i = 1; i <= a.length; i++) {
+ let diag = prev[0];
+ prev[0] = i;
+ for (let j = 1; j <= b.length; j++) {
+ const tmp = prev[j];
+ prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
+ diag = tmp;
+ }
+ }
+ return prev[b.length];
+}
diff --git a/src/core/font.ts b/src/core/font.ts
new file mode 100644
index 0000000..9994225
--- /dev/null
+++ b/src/core/font.ts
@@ -0,0 +1,54 @@
+// Built-in 3x5 pixel font. "#" = ink, rows separated by "/". Lowercase draws as uppercase.
+const FONT: Record<string, string> = {
+ A: "###/#.#/###/#.#/#.#", B: "##./#.#/##./#.#/##.", C: "###/#../#../#../###",
+ D: "##./#.#/#.#/#.#/##.", E: "###/#../##./#../###", F: "###/#../##./#../#..",
+ G: "###/#../#.#/#.#/###", H: "#.#/#.#/###/#.#/#.#", I: "###/.#./.#./.#./###",
+ J: "..#/..#/..#/#.#/###", K: "#.#/#.#/##./#.#/#.#", L: "#../#../#../#../###",
+ M: "#.#/###/###/#.#/#.#", N: "##./#.#/#.#/#.#/#.#", O: "###/#.#/#.#/#.#/###",
+ P: "###/#.#/###/#../#..", Q: "###/#.#/#.#/###/..#", R: "##./#.#/##./#.#/#.#",
+ S: "###/#../###/..#/###", T: "###/.#./.#./.#./.#.", U: "#.#/#.#/#.#/#.#/###",
+ V: "#.#/#.#/#.#/#.#/.#.", W: "#.#/#.#/###/###/#.#", X: "#.#/#.#/.#./#.#/#.#",
+ Y: "#.#/#.#/###/.#./.#.", Z: "###/..#/.#./#../###",
+ "0": "###/#.#/#.#/#.#/###", "1": "##./.#./.#./.#./###", "2": "###/..#/###/#../###",
+ "3": "###/..#/.##/..#/###", "4": "#.#/#.#/###/..#/..#", "5": "###/#../###/..#/###",
+ "6": "###/#../###/#.#/###", "7": "###/..#/..#/.#./.#.", "8": "###/#.#/###/#.#/###",
+ "9": "###/#.#/###/..#/###",
+ " ": ".../.../.../.../...", ".": "././././#", ",": "../../../.#/#.",
+ "!": "#/#/#/./#", "?": "###/..#/.##/.../.#.", ":": "./#/./#/.", ";": "../.#/../.#/#.",
+ "'": "#/#/././.", '"': "#.#/#.#/.../.../...", "-": ".../.../###/.../...",
+ "+": ".../.#./###/.#./...", "/": "..#/..#/.#./#../#..", "(": ".#/#./#./#./.#",
+ ")": "#./.#/.#/.#/#.", "=": ".../###/.../###/...", "%": "#.#/..#/.#./#../#.#",
+ "#": "#.#/###/#.#/###/#.#", "*": ".../#.#/.#./#.#/...", _: ".../.../.../.../###",
+ "<": "..#/.#./#../.#./..#", ">": "#../.#./..#/.#./#..", "&": ".#./#.#/.#./#.#/.##",
+ "$": ".##/##./.#./.##/##.", "@": "###/#.#/#.#/#../###",
+};
+
+const cache = new Map<string, string[]>();
+
+export function glyph(ch: string): string[] {
+ const k = FONT[ch] ? ch : FONT[ch.toUpperCase()] ? ch.toUpperCase() : "?";
+ let g = cache.get(k);
+ if (!g) {
+ g = FONT[k].split("/");
+ cache.set(k, g);
+ }
+ return g;
+}
+
+export interface FontOpts {
+ scale?: number;
+ gap?: number;
+}
+
+/** Pixel width of a single line. */
+export function lineWidth(line: string, opts: FontOpts = {}): number {
+ const sc = opts.scale ?? 1, gap = opts.gap ?? 1;
+ let w = 0;
+ for (const ch of line) w += (glyph(ch)[0].length + gap) * sc;
+ return line.length ? w - gap * sc : 0;
+}
+
+/** Pixel width of the longest line. */
+export function textWidth(s: string, opts: FontOpts = {}): number {
+ return Math.max(0, ...String(s).split("\n").map((l) => lineWidth(l, opts)));
+}
diff --git a/src/core/glow.ts b/src/core/glow.ts
new file mode 100644
index 0000000..f4c68ce
--- /dev/null
+++ b/src/core/glow.ts
@@ -0,0 +1,79 @@
+// Glow: pixels of the given keys spill a halo onto the opaque pixels around them (flames, potions,
+// moons, neon). Colour mode screens the source colour on top, which leaves the palette like
+// lighting() does; ramp mode steps neighbours lighter along the ramps instead and stays in it.
+import { type Color, TRANSPARENT, channels, pack } from "./color.ts";
+import { PxError } from "./errors.ts";
+import { Img } from "./image.ts";
+import type { GlowOpts } from "./model.ts";
+import type { Palette } from "./palette.ts";
+import { bayer, colorList, regionPred } from "./util.ts";
+
+/**
+ * Return `img` with a halo around every pixel whose color is one of `keys`. `keyed` gives each
+ * pixel's palette color when `img` has left the palette (lit by lighting()); defaults to img.
+ */
+export function applyGlow(img: Img, keys: string | string[], o: GlowOpts, pal: Palette, keyed: Uint32Array = img.data): Img {
+ const src = new Set<Color>();
+ for (const k of colorList(keys)) {
+ const c = pal.resolve(k);
+ if (c !== null && c !== TRANSPARENT) src.add(c);
+ }
+ const r = o.r ?? 6;
+ if (!(r > 0)) throw new PxError(`glow r must be > 0, got ${r}`);
+ const inside = o.where === undefined ? undefined : regionPred(o.where)
+ const strength = o.strength ?? 0.5, bands = Math.max(0, Math.floor(o.bands ?? 0));
+ let tint: Color | undefined;
+ if (o.color !== undefined) {
+ const c = pal.resolve(o.color);
+ if (c === null || c === TRANSPARENT) throw new PxError(`glow color must be a visible color, got '${o.color}'`);
+ tint = c;
+ }
+
+ // Strongest contribution per pixel (max, like lamps), weight falling off as (1 - d/r)^2.
+ const { w, h, data } = img;
+ const weight = new Float32Array(w * h), rgb = new Float32Array(w * h * 3);
+ const R = Math.ceil(r);
+ for (let sy = 0; sy < h; sy++)
+ for (let sx = 0; sx < w; sx++) {
+ const c = keyed[sy * w + sx];
+ if (!src.has(c) || (inside && !inside(sx, sy))) continue;
+ const [cr, cg, cb] = channels(tint ?? c);
+ for (let y = Math.max(0, sy - R); y <= Math.min(h - 1, sy + R); y++)
+ for (let x = Math.max(0, sx - R); x <= Math.min(w - 1, sx + R); x++) {
+ const d = Math.hypot(x - sx, y - sy);
+ if (d > r) continue;
+ let f = (1 - d / (r + 1)) ** 2;
+ if (bands) f = Math.ceil(f * bands) / bands;
+ const i = y * w + x;
+ if (f > weight[i]) weight[i] = f;
+ rgb[i * 3] = Math.max(rgb[i * 3], f * cr);
+ rgb[i * 3 + 1] = Math.max(rgb[i * 3 + 1], f * cg);
+ rgb[i * 3 + 2] = Math.max(rgb[i * 3 + 2], f * cb);
+ }
+ }
+
+ const out = img.copy();
+ const steps = o.ramp;
+ const up = steps ? pal.stepMap(1) : undefined;
+ for (let i = 0; i < data.length; i++) {
+ const c = data[i];
+ if (c === TRANSPARENT || src.has(keyed[i]) || weight[i] === 0) continue;
+ if (up) {
+ // Whole steps near the source, ordered dither on the fractional step: crisp, in palette.
+ const s = weight[i] * steps!, x = i % w, y = (i - x) / w;
+ let n = Math.floor(s) + (bayer(x, y) < s - Math.floor(s) ? 1 : 0), v = c;
+ while (n-- > 0) v = up.get(v) ?? v;
+ out.data[i] = v;
+ continue;
+ }
+ // Screen blend: brightens toward the glow color without ever overshooting white.
+ const [br, bg, bb, a] = channels(c);
+ const scr = (b: number, g: number) => 255 - ((255 - b) * (255 - Math.min(255, g * strength))) / 255;
+ out.data[i] = pack(byte(scr(br, rgb[i * 3])), byte(scr(bg, rgb[i * 3 + 1])), byte(scr(bb, rgb[i * 3 + 2])), a);
+ }
+ return out;
+}
+
+function byte(v: number): number {
+ return Math.min(255, Math.max(0, Math.round(v)));
+}
diff --git a/src/core/image.ts b/src/core/image.ts
new file mode 100644
index 0000000..cdf705b
--- /dev/null
+++ b/src/core/image.ts
@@ -0,0 +1,248 @@
+import { type Color, TRANSPARENT } from "./color.ts";
+
+export type Axis = "x" | "y" | "xy";
+
+/** A light source carried by an image (pixel coords); consumed by lighting(). */
+export interface Lamp {
+ x: number;
+ y: number;
+ /** Reach in pixels through open space. */
+ r: number;
+ color: Color;
+ power: number;
+ /** Height above the picture plane in px (how much it rakes across normal-mapped surfaces). */
+ z: number;
+}
+
+/** RGBA image as packed colors. Out-of-bounds reads are transparent, writes are ignored. */
+export class Img {
+ readonly w: number;
+ readonly h: number;
+ readonly data: Uint32Array;
+ /** Light sources placed in this image; they travel with it through transforms and stamps. */
+ lamps?: Lamp[];
+ /**
+ * Per-pixel surface normals (nx, ny, nz) * 127, ny pointing down the image; nz = 0 = none
+ * (lit flat). Set by bump() / normals(); travels with the pixels like lamps do.
+ */
+ norm?: Int8Array;
+
+ constructor(w: number, h: number, data?: Uint32Array) {
+ w = Math.floor(w);
+ h = Math.floor(h);
+ if (!(w >= 1 && h >= 1)) throw new Error(`image size must be positive, got ${w}x${h}`);
+ if (w * h > 16_777_216) throw new Error(`image too large: ${w}x${h}`);
+ this.w = w;
+ this.h = h;
+ this.data = data ?? new Uint32Array(w * h);
+ }
+
+ inside(x: number, y: number): boolean {
+ return x >= 0 && y >= 0 && x < this.w && y < this.h;
+ }
+
+ get(x: number, y: number): Color {
+ x = Math.floor(x);
+ y = Math.floor(y);
+ return this.inside(x, y) ? this.data[y * this.w + x] : TRANSPARENT;
+ }
+
+ set(x: number, y: number, c: Color): void {
+ x = Math.floor(x);
+ y = Math.floor(y);
+ if (this.inside(x, y)) this.data[y * this.w + x] = c;
+ }
+
+ copy(): Img {
+ const o = new Img(this.w, this.h, this.data.slice());
+ if (this.lamps) o.lamps = this.lamps.map((l) => ({ ...l }));
+ if (this.norm) o.norm = this.norm.slice();
+ return o;
+ }
+
+ /** Normal channel, allocated (all "none") on first use. */
+ normals(): Int8Array {
+ return (this.norm ??= new Int8Array(this.w * this.h * 3));
+ }
+
+ /** Copy pixel i's normal from src pixel j, transforming its x/y (flip: sx/sy = -1, swap = rotate). */
+ private static moveNorm(src: Int8Array, j: number, dst: Int8Array, i: number, sx = 1, sy = 1, rot = 0): void {
+ let nx = src[j * 3], ny = src[j * 3 + 1];
+ if (rot === 90) [nx, ny] = [-ny, nx];
+ else if (rot === 270) [nx, ny] = [ny, -nx];
+ dst[i * 3] = nx * sx;
+ dst[i * 3 + 1] = ny * sy;
+ dst[i * 3 + 2] = src[j * 3 + 2];
+ }
+
+ /** Copy lamps into `o` through a position transform (dropping ones it maps outside). */
+ private moveLamps(o: Img, f: (x: number, y: number) => [number, number]): Img {
+ if (!this.lamps?.length) return o;
+ o.lamps = [];
+ for (const l of this.lamps) {
+ const [x, y] = f(l.x, l.y);
+ if (o.inside(x, y)) o.lamps.push({ ...l, x, y });
+ }
+ return o;
+ }
+
+ fill(c: Color): this {
+ this.data.fill(c);
+ return this;
+ }
+
+ /** Draw src at (dx, dy); transparent source pixels are skipped. */
+ blit(src: Img, dx: number, dy: number): void {
+ dx = Math.floor(dx);
+ dy = Math.floor(dy);
+ for (let y = 0; y < src.h; y++) {
+ const ty = dy + y;
+ if (ty < 0 || ty >= this.h) continue;
+ for (let x = 0; x < src.w; x++) {
+ const c = src.data[y * src.w + x];
+ const tx = dx + x;
+ if (c === TRANSPARENT || tx < 0 || tx >= this.w) continue;
+ const i = ty * this.w + tx;
+ this.data[i] = c;
+ // Normals come along; flat art drawn over a bumped surface clears it.
+ if (src.norm) Img.moveNorm(src.norm, y * src.w + x, this.normals(), i);
+ else if (this.norm) this.norm[i * 3 + 2] = 0;
+ }
+ }
+ }
+
+ flip(axis: Axis): Img {
+ const o = new Img(this.w, this.h);
+ const fx = axis.includes("x"), fy = axis.includes("y");
+ for (let y = 0; y < this.h; y++)
+ for (let x = 0; x < this.w; x++) {
+ const j = (fy ? this.h - 1 - y : y) * this.w + (fx ? this.w - 1 - x : x);
+ o.data[y * this.w + x] = this.data[j];
+ if (this.norm) Img.moveNorm(this.norm, j, o.normals(), y * this.w + x, fx ? -1 : 1, fy ? -1 : 1);
+ }
+ return this.moveLamps(o, (x, y) => [fx ? this.w - 1 - x : x, fy ? this.h - 1 - y : y]);
+ }
+
+ /** Clockwise rotation by a multiple of 90 degrees. */
+ rot(deg: number): Img {
+ const d = ((deg % 360) + 360) % 360;
+ if (d === 0) return this.copy();
+ if (d === 180) return this.flip("xy");
+ if (d !== 90 && d !== 270) throw new Error(`rot must be a multiple of 90, got ${deg}`);
+ const o = new Img(this.h, this.w);
+ for (let y = 0; y < this.h; y++)
+ for (let x = 0; x < this.w; x++) {
+ const c = this.data[y * this.w + x];
+ const [tx, ty] = d === 90 ? [this.h - 1 - y, x] : [y, this.w - 1 - x];
+ o.set(tx, ty, c);
+ if (this.norm) Img.moveNorm(this.norm, y * this.w + x, o.normals(), ty * o.w + tx, 1, 1, d);
+ }
+ return this.moveLamps(o, (x, y) => (d === 90 ? [this.h - 1 - y, x] : [y, this.w - 1 - x]));
+ }
+
+ /** Copy the left half onto the right ("x") or the top onto the bottom ("y"), in place. */
+ mirror(axis: "x" | "y"): void {
+ const n = this.norm;
+ if (axis === "x") {
+ for (let y = 0; y < this.h; y++)
+ for (let x = 0; x < Math.floor(this.w / 2); x++) {
+ this.set(this.w - 1 - x, y, this.get(x, y));
+ if (n) Img.moveNorm(n, y * this.w + x, n, y * this.w + this.w - 1 - x, -1, 1);
+ }
+ } else {
+ for (let y = 0; y < Math.floor(this.h / 2); y++)
+ for (let x = 0; x < this.w; x++) {
+ this.set(x, this.h - 1 - y, this.get(x, y));
+ if (n) Img.moveNorm(n, y * this.w + x, n, (this.h - 1 - y) * this.w + x, 1, -1);
+ }
+ }
+ if (this.lamps) {
+ const half = axis === "x" ? Math.floor(this.w / 2) : Math.floor(this.h / 2);
+ for (const l of [...this.lamps]) {
+ if (axis === "x" && l.x < half) this.lamps.push({ ...l, x: this.w - 1 - l.x });
+ if (axis === "y" && l.y < half) this.lamps.push({ ...l, y: this.h - 1 - l.y });
+ }
+ }
+ }
+
+ /** Bounding box of opaque pixels, or undefined when empty. */
+ bounds(): { x: number; y: number; w: number; h: number } | undefined {
+ let x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1;
+ for (let y = 0; y < this.h; y++)
+ for (let x = 0; x < this.w; x++)
+ if (this.data[y * this.w + x] !== TRANSPARENT) {
+ if (x < x0) x0 = x;
+ if (x > x1) x1 = x;
+ if (y < y0) y0 = y;
+ y1 = y;
+ }
+ return x1 < 0 ? undefined : { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 };
+ }
+
+ sub(x: number, y: number, w: number, h: number): Img {
+ const o = new Img(w, h);
+ for (let yy = 0; yy < h; yy++)
+ for (let xx = 0; xx < w; xx++) {
+ o.data[yy * w + xx] = this.get(x + xx, y + yy);
+ if (this.norm && this.inside(x + xx, y + yy)) Img.moveNorm(this.norm, (y + yy) * this.w + x + xx, o.normals(), yy * w + xx);
+ }
+ return this.moveLamps(o, (lx, ly) => [lx - x, ly - y]);
+ }
+
+ crop(): Img {
+ const b = this.bounds();
+ return b ? this.sub(b.x, b.y, b.w, b.h) : this.copy();
+ }
+
+ pad(n: number): Img {
+ const o = new Img(this.w + 2 * n, this.h + 2 * n);
+ o.blit(this, n, n);
+ return this.moveLamps(o, (x, y) => [x + n, y + n]);
+ }
+
+ /** 1px outline around opaque pixels; grows the canvas by 1 on every side. */
+ outline(c: Color, diagonal = false): Img {
+ const src = this.pad(1);
+ const o = src.copy();
+ const op = (x: number, y: number) => src.get(x, y) !== TRANSPARENT;
+ for (let y = 0; y < src.h; y++)
+ for (let x = 0; x < src.w; x++) {
+ if (op(x, y)) continue;
+ let hit = op(x - 1, y) || op(x + 1, y) || op(x, y - 1) || op(x, y + 1);
+ if (!hit && diagonal) hit = op(x - 1, y - 1) || op(x + 1, y - 1) || op(x - 1, y + 1) || op(x + 1, y + 1);
+ if (hit) o.set(x, y, c);
+ }
+ return o;
+ }
+
+ /** Replace colors through a map. */
+ remap(map: Map<Color, Color>): Img {
+ const o = this.copy();
+ for (let i = 0; i < o.data.length; i++) {
+ const to = map.get(o.data[i]);
+ if (to !== undefined) o.data[i] = to;
+ }
+ return o;
+ }
+
+ /** Nearest-neighbour upscale. */
+ scale(s: number): Img {
+ if (s === 1) return this.copy();
+ const o = new Img(this.w * s, this.h * s);
+ for (let y = 0; y < o.h; y++) {
+ const row = Math.floor(y / s) * this.w;
+ for (let x = 0; x < o.w; x++) o.data[y * o.w + x] = this.data[row + Math.floor(x / s)];
+ }
+ return o;
+ }
+
+ /** FNV-1a over size + pixels, for change detection. */
+ hash(): string {
+ let h = 0x811c9dc5 ^ this.w ^ (this.h << 16);
+ for (let i = 0; i < this.data.length; i++) {
+ h ^= this.data[i];
+ h = Math.imul(h, 0x01000193);
+ }
+ return (h >>> 0).toString(36);
+ }
+}
diff --git a/src/core/index.ts b/src/core/index.ts
new file mode 100644
index 0000000..b74713f
--- /dev/null
+++ b/src/core/index.ts
@@ -0,0 +1,16 @@
+// Platform-independent core: no Node or DOM APIs.
+export * from "./color.ts";
+export * from "./errors.ts";
+export * from "./image.ts";
+export * from "./palette.ts";
+export * from "./model.ts";
+export * from "./canvas.ts";
+export * from "./build.ts";
+export * from "./trace.ts";
+export * from "./project.ts";
+export * from "./render.ts";
+export * from "./light.ts";
+export * from "./glow.ts";
+export * from "./normals.ts";
+export { gridRows, gridSize, rng, hash, bayer, regionPred, globRe, fmtArgs } from "./util.ts";
+export { glyph, textWidth } from "./font.ts";
diff --git a/src/core/light.ts b/src/core/light.ts
new file mode 100644
index 0000000..4e7f235
--- /dev/null
+++ b/src/core/light.ts
@@ -0,0 +1,241 @@
+// Terraria-style lighting: light spreads over a grid of cells from lamps (and the sky). Open cells
+// cost a fixed amount (so `r` is the reach); solid cells keep only a fraction of what enters,
+// so brighter light reaches deeper into blocks while their interiors still go dark. The result
+// multiplies the image's RGB. Pixels with normals (bump / normals) are shaded by the direction each
+// light comes from: facing it brightens, facing away darkens, flat stays as without normals.
+import { type Color, TRANSPARENT, channels, pack } from "./color.ts";
+import { PxError } from "./errors.ts";
+import { Img, type Lamp } from "./image.ts";
+import type { LightingOpts } from "./model.ts";
+import type { Palette } from "./palette.ts";
+import { colorList } from "./util.ts";
+
+export interface LightResult {
+ /** The lit image. */
+ img: Img;
+ /** Light per pixel as an image (for the viewer / debugging). */
+ map: Img;
+}
+
+/** Per-pixel masks (1 = set): solid blocks light, wall stops sky light, unlit ignores lighting. */
+export interface LightMasks {
+ solid: Uint8Array;
+ wall: Uint8Array;
+ unlit?: Uint8Array;
+}
+
+/** Light `img`; lamps are in image pixel coordinates. */
+export function applyLighting(img: Img, masks: LightMasks, lamps: Lamp[], o: LightingOpts, pal: Palette): LightResult {
+ const { solid, wall, unlit } = masks;
+ const cell = Math.max(1, Math.floor(o.cell ?? 4));
+ const gw = Math.ceil(img.w / cell), gh = Math.ceil(img.h / cell), n = gw * gh;
+ // `block` is the loss per 8px (one Terraria tile), so depth doesn't change with the cell size.
+ const keep = (1 - Math.min(0.999, clamp01(o.block ?? 0.4))) ** (cell / 8);
+ const diag = (o.shape ?? "round") === "round";
+
+ // Per-cell solidity (majority of the cell's pixels) and wall coverage.
+ const solidCell = new Uint8Array(n), wallCell = new Uint8Array(n);
+ for (let cy = 0; cy < gh; cy++)
+ for (let cx = 0; cx < gw; cx++) {
+ let s = 0, w = 0, t = 0;
+ for (let y = cy * cell; y < Math.min(img.h, (cy + 1) * cell); y++)
+ for (let x = cx * cell; x < Math.min(img.w, (cx + 1) * cell); x++) {
+ const i = y * img.w + x;
+ s += solid[i];
+ w += wall[i];
+ t++;
+ }
+ solidCell[cy * gw + cx] = s * 2 >= t ? 1 : 0;
+ wallCell[cy * gw + cx] = w * 2 >= t ? 1 : 0;
+ }
+
+ // Light per cell, RGB in 0..(power), combined by max like Terraria.
+ const L = new Float32Array(n * 3);
+ // Normal-mapped images keep every source separately: each pixel needs the light's direction.
+ const relief = img.norm ? Math.max(0, o.relief ?? 1) : 0;
+ const sources: { f: Float32Array; rgb: [number, number, number]; dir: (x: number, y: number) => [number, number, number] }[] = [];
+ const mix = (field: Float64Array, rgb: [number, number, number], dir: (x: number, y: number) => [number, number, number]) => {
+ const eased = relief ? new Float32Array(n) : undefined;
+ for (let i = 0; i < n; i++) {
+ if (field[i] <= 0) continue;
+ const f = field[i], v = f >= 1 ? f : 1 - (1 - f) ** 2; // ease-out: rooms stay bright, edges fall off fast
+ if (eased) eased[i] = v;
+ for (let k = 0; k < 3; k++) L[i * 3 + k] = Math.max(L[i * 3 + k], v * rgb[k]);
+ }
+ if (eased) sources.push({ f: eased, rgb, dir });
+ };
+ const rgbOf = (c: Color, k = 1): [number, number, number] => {
+ const [r, g, b] = channels(c);
+ return [(r / 255) * k, (g / 255) * k, (b / 255) * k];
+ };
+ const color = (spec: string | undefined, what: string): Color => {
+ const c = pal.resolve(spec ?? "#fff");
+ if (c === null || c === TRANSPARENT) throw new PxError(`lighting: ${what} must be a visible color, got '${spec}'`);
+ return c;
+ };
+
+ for (const l of lamps) {
+ const cx = Math.floor(l.x / cell), cy = Math.floor(l.y / cell);
+ if (cx < 0 || cy < 0 || cx >= gw || cy >= gh) continue;
+ const field = spread(gw, gh, solidCell, [cy * gw + cx], l.power, cell / l.r, keep, diag);
+ mix(field, rgbOf(l.color), (x, y) => unit(l.x - x, l.y - y, l.z ?? 8));
+ }
+
+ const sky = o.sky ?? 0;
+ if (sky > 0) {
+ // Cells open to the sky: from the top of each column down to the first solid or wall cell.
+ const open: number[] = [];
+ for (let cx = 0; cx < gw; cx++)
+ for (let cy = 0; cy < gh; cy++) {
+ const i = cy * gw + cx;
+ if (solidCell[i] || wallCell[i]) break;
+ open.push(i);
+ }
+ if (open.length) {
+ const field = spread(gw, gh, solidCell, open, sky, cell / (o.skyReach ?? 24), keep, diag);
+ const [sx, sy] = o.skyDir ?? [0, -1], sd = unit(-sx, -sy, 1);
+ mix(field, rgbOf(color(o.skyColor, "skyColor")), () => sd);
+ }
+ }
+
+ const amb = o.ambient ?? 0;
+ const a = amb > 0 ? rgbOf(color(o.ambientColor, "ambientColor"), amb) : [0, 0, 0];
+ if (amb > 0) for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) L[i * 3 + k] = Math.max(L[i * 3 + k], a[k]);
+
+ // Per-pixel value of a cell array (stride values per cell): blocky or bilinear between cell centers.
+ const sample = (arr: Float32Array, stride: number, x: number, y: number, k: number): number => {
+ if (!o.smooth) return arr[(Math.floor(y / cell) * gw + Math.floor(x / cell)) * stride + k];
+ const fx = Math.min(gw - 1, Math.max(0, (x + 0.5) / cell - 0.5)), fy = Math.min(gh - 1, Math.max(0, (y + 0.5) / cell - 0.5));
+ const x0 = Math.floor(fx), y0 = Math.floor(fy), x1 = Math.min(gw - 1, x0 + 1), y1 = Math.min(gh - 1, y0 + 1);
+ const tx = fx - x0, ty = fy - y0;
+ const g = (cx: number, cy: number) => arr[(cy * gw + cx) * stride + k];
+ return (g(x0, y0) * (1 - tx) + g(x1, y0) * tx) * (1 - ty) + (g(x0, y1) * (1 - tx) + g(x1, y1) * tx) * ty;
+ };
+ const at = (x: number, y: number, k: number) => sample(L, 3, x, y, k);
+
+ // Light on a normal-mapped pixel: each source scaled by how much the surface faces it, relative
+ // to a flat surface (so flat normals match unmapped art); ambient is directionless.
+ const nm = img.norm, lit: [number, number, number] = [0, 0, 0];
+ const shaded = (x: number, y: number, i: number): [number, number, number] => {
+ const nx = nm![i * 3] / 127, ny = nm![i * 3 + 1] / 127, nz = nm![i * 3 + 2] / 127;
+ lit[0] = a[0]; lit[1] = a[1]; lit[2] = a[2];
+ for (const s of sources) {
+ const v = sample(s.f, 1, x, y, 0);
+ if (v <= 0) continue;
+ const [dx, dy, dz] = s.dir(x + 0.5, y + 0.5);
+ const f = v * Math.max(0, 1 + relief * (Math.max(0, nx * dx + ny * dy + nz * dz) - dz));
+ for (let k = 0; k < 3; k++) lit[k] = Math.max(lit[k], f * s.rgb[k]);
+ }
+ return lit;
+ };
+
+ const emit = new Set<Color>();
+ for (const k of colorList(o.emit ?? "")) {
+ const c = pal.resolve(k);
+ if (c !== null) emit.add(c);
+ }
+
+ const out = new Img(img.w, img.h), map = new Img(img.w, img.h);
+ for (let y = 0; y < img.h; y++)
+ for (let x = 0; x < img.w; x++) {
+ const i = y * img.w + x;
+ const [lr, lg, lb] = relief && nm![i * 3 + 2] > 0 ? shaded(x, y, i) : [at(x, y, 0), at(x, y, 1), at(x, y, 2)];
+ map.data[i] = pack(byte(lr * 255), byte(lg * 255), byte(lb * 255));
+ const c = img.data[i];
+ if (c === TRANSPARENT || emit.has(c) || unlit?.[i]) {
+ out.data[i] = c;
+ continue;
+ }
+ const [r, g, b, a] = channels(c);
+ out.data[i] = pack(byte(r * lr), byte(g * lg), byte(b * lb), a);
+ }
+ return { img: out, map };
+}
+
+/**
+ * Max-intensity spread from `sources` (each at `start`): stepping into an open cell costs `air`,
+ * a solid cell keeps only `keep` of the light (so bright light reaches deeper); light below 0.02 stops; diagonals count √2× and can't squeeze between two
+ * solid cells. Every step is monotone, so Dijkstra (max-first, binary heap) is exact.
+ */
+function spread(gw: number, gh: number, solid: Uint8Array, sources: number[], start: number, air: number, keep: number, diag: boolean): Float64Array {
+ const best = new Float64Array(gw * gh);
+ const heap = new MaxHeap();
+ for (const s of sources) {
+ best[s] = start;
+ heap.push(s, start);
+ }
+ const dirs = diag
+ ? [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, Math.SQRT2], [1, -1, Math.SQRT2], [-1, 1, Math.SQRT2], [-1, -1, Math.SQRT2]]
+ : [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1]];
+ while (heap.size) {
+ const [i, v] = heap.pop();
+ if (v < best[i]) continue;
+ const x = i % gw, y = (i - x) / gw;
+ for (const [dx, dy, k] of dirs) {
+ const nx = x + dx, ny = y + dy;
+ if (nx < 0 || ny < 0 || nx >= gw || ny >= gh) continue;
+ if (dx && dy && solid[y * gw + nx] && solid[ny * gw + x]) continue;
+ const j = ny * gw + nx;
+ // Solid cells lose a share of the light, but never less than open space would.
+ const nv = solid[j] ? Math.min(v * (k === 1 ? keep : keep ** k), v - air * k) : v - air * k;
+ if (nv > best[j] && nv > 0.02) {
+ best[j] = nv;
+ heap.push(j, nv);
+ }
+ }
+ }
+ return best;
+}
+
+class MaxHeap {
+ private ids: number[] = [];
+ private vals: number[] = [];
+ get size(): number { return this.ids.length; }
+
+ push(id: number, v: number): void {
+ const { ids, vals } = this;
+ let i = ids.length;
+ ids.push(id);
+ vals.push(v);
+ while (i > 0) {
+ const p = (i - 1) >> 1;
+ if (vals[p] >= v) break;
+ ids[i] = ids[p]; vals[i] = vals[p];
+ i = p;
+ }
+ ids[i] = id; vals[i] = v;
+ }
+
+ pop(): [number, number] {
+ const { ids, vals } = this;
+ const top: [number, number] = [ids[0], vals[0]];
+ const id = ids.pop()!, v = vals.pop()!;
+ if (ids.length) {
+ let i = 0;
+ for (;;) {
+ const l = 2 * i + 1, r = l + 1;
+ let m = i, mv = v;
+ if (l < ids.length && vals[l] > mv) { m = l; mv = vals[l]; }
+ if (r < ids.length && vals[r] > mv) m = r;
+ if (m === i) break;
+ ids[i] = ids[m]; vals[i] = vals[m];
+ i = m;
+ }
+ ids[i] = id; vals[i] = v;
+ }
+ return top;
+ }
+}
+
+function unit(x: number, y: number, z: number): [number, number, number] {
+ const l = Math.hypot(x, y, z) || 1;
+ return [x / l, y / l, z / l];
+}
+
+function clamp01(v: number): number {
+ return Math.min(1, Math.max(0, v));
+}
+
+function byte(v: number): number {
+ return Math.min(255, Math.max(0, Math.round(v)));
+}
diff --git a/src/core/model.ts b/src/core/model.ts
new file mode 100644
index 0000000..364fd56
--- /dev/null
+++ b/src/core/model.ts
@@ -0,0 +1,244 @@
+// The data an art file produces. Definitions are plain data + closures; nothing is drawn
+// until build time, so references between assets are order-independent.
+import type { Palette } from "./palette.ts";
+import type { Canvas } from "./canvas.ts";
+import type { Region } from "./util.ts";
+
+/** A drawing op recorded with where it was written. */
+export interface Op {
+ __op: true;
+ name: string;
+ args: unknown[];
+ loc?: string;
+}
+
+export interface LayerOpts {
+ x?: number;
+ y?: number;
+ hidden?: boolean;
+ /** Blend layer: instead of drawing, step what's below darker/lighter where this layer is opaque. */
+ shade?: boolean | number | Record<string, string>;
+ light?: boolean | number | Record<string, string>;
+ /** Fraction (0..1) of a blend layer's pixels that apply (ordered dither). */
+ density?: number;
+ /** Opaque pixels block light (lighting()). */
+ solid?: boolean;
+ /** Opaque pixels are back walls: they stop sky light from entering but let light pass. */
+ wall?: boolean;
+ /** Pixels this layer leaves visible ignore lighting (skies, backdrops). */
+ unlit?: boolean;
+}
+
+export interface Layer {
+ __layer: true;
+ name: string;
+ opts: LayerOpts;
+ items: Item[];
+ loc?: string;
+}
+
+/** Body items: grid strings, ops, custom functions, layers. */
+export type Item = string | Op | Layer | ((c: Canvas) => void);
+
+export interface AssetOpts {
+ w?: number;
+ h?: number;
+ base?: string;
+ mx?: boolean | "c";
+ my?: boolean | "c";
+ swap?: Record<string, string>;
+ flip?: "x" | "y" | "xy";
+ rot?: 90 | 180 | 270;
+ outline?: string;
+ outline8?: string;
+ crop?: boolean;
+ /** Also export each layer as its own PNG. */
+ layers?: boolean;
+ /** Scene background color. */
+ bg?: string;
+ /** anim: default frame rate (frames per second, default 8). */
+ fps?: number;
+ /** anim: frame count when there are no frame() items (procedural, via c.frame / c.phase). */
+ frames?: number;
+ /** anim: false = play once and hold the last frame (default true). */
+ loop?: boolean;
+}
+
+export type AssetKind = "sprite" | "scene" | "anim";
+
+/** Options of a frame() item inside an anim. */
+export interface FrameOpts {
+ /** Duration in ms (default 1000 / fps). */
+ ms?: number;
+ /** Duration in frames of the anim's fps (2 = twice as long). */
+ hold?: number;
+}
+
+/**
+ * How an asset changes over time. Anims know their own frame durations; anything that places an
+ * anim (sprites, scenes) inherits a combined loop and step.
+ */
+export interface Timeline {
+ /** Loop length in ms. */
+ loop: number;
+ /** Time resolution in ms: frames change at multiples of this. */
+ step: number;
+ /** Own frame durations in ms (anims only). */
+ durations?: number[];
+ /** anim loop: false (holds the last frame). */
+ once?: boolean;
+}
+
+export interface AssetDef {
+ kind: AssetKind;
+ name: string;
+ opts: AssetOpts;
+ items: Item[];
+ pal: Palette;
+ loc?: string;
+}
+
+export interface GroupDef {
+ name: string;
+ members: string[];
+ loc?: string;
+}
+
+export interface SheetOpts {
+ cols?: number;
+ pad?: number;
+}
+
+export interface SheetDef {
+ name: string;
+ entries: string[];
+ opts: SheetOpts;
+ loc?: string;
+}
+
+/** Options for stamp / tile / pattern / tilemap / scatter / wire hangs. */
+export interface PlaceOpts {
+ flip?: "x" | "y" | "xy";
+ rot?: 90 | 180 | 270;
+ swap?: Record<string, string>;
+ /** Random flips per placement. */
+ rflip?: "x" | "y" | "xy";
+ /** Random recolor per placement; {} = keep. */
+ rswap?: Record<string, string>[];
+ seed?: number;
+ /** Rebuild the placed asset with its own random choices (true = derived from position). */
+ reseed?: boolean | number;
+ /** Animated assets: show this frame index, frozen. */
+ frame?: number;
+ /** Animated assets: start this many ms later (desync copies). */
+ delay?: number;
+ /** Animated assets: random start time per placement (true), seeded like other picks. */
+ rdelay?: boolean;
+}
+
+export interface ScatterOpts extends PlaceOpts {
+ /** Center must land on these keys ("*" = any opaque). */
+ on?: string;
+ /** Only paint onto `on` pixels. */
+ clip?: boolean;
+ /** Masks read the composite below the current layer instead of the layer itself. */
+ below?: boolean;
+}
+
+export interface TilemapOpts extends PlaceOpts {
+ map: Record<string, string>;
+ size?: number;
+ w?: number;
+ h?: number;
+ x?: number;
+ y?: number;
+}
+
+export interface WireOpts extends PlaceOpts {
+ hang?: string;
+ every?: number;
+ start?: number;
+}
+
+export interface LampOpts {
+ /** Reach in pixels through open space (default 32). */
+ r?: number;
+ /** Light color: key or "#hex" (default white). */
+ color?: string;
+ /** Brightness multiplier at the source (default 1; > 1 overexposes). */
+ power?: number;
+ /** Height above the picture in px (default 8): lower = more raking light on normal maps. */
+ z?: number;
+}
+
+export interface BumpOpts {
+ /** "dome" (default): blobs bulge; "bevel": edges slope over `w` px; "luma": brighter = higher. */
+ shape?: "dome" | "bevel" | "luma";
+ /** Bevel width in px (default 2). */
+ w?: number;
+ /** Steepness multiplier (default 1). */
+ depth?: number;
+ /** Only these keys ("*" any opaque, default): other keys act as the edges (bevel each brick). */
+ on?: string;
+ /** Only pixels in this region. */
+ where?: Region;
+}
+
+export interface LightingOpts {
+ /** Light-grid cell size in px (default 4): bigger = blockier, Terraria-like. */
+ cell?: number;
+ /** Minimum light everywhere, 0..1 (default 0). */
+ ambient?: number;
+ /** Ambient light color (default white). */
+ ambientColor?: string;
+ /** Sky light level 0..1 for cells open to the sky (default 0 = none). */
+ sky?: number;
+ skyColor?: string;
+ /** How far sky light spreads from open cells, in px (default 24). */
+ skyReach?: number;
+ /** Fraction of light lost per 8px of solid, 0..1 (default 0.4): brighter light reaches deeper. */
+ block?: number;
+ /** Interpolate between cells instead of blocky steps. */
+ smooth?: boolean;
+ /** Keys that ignore lighting (flames, windows, lava). */
+ emit?: string;
+ /** Spread shape: "round" (8 neighbours, default) or "diamond" (4, Terraria-like). */
+ shape?: "round" | "diamond";
+ /** How strongly normal maps (bump / normals) shape the light, 0 = ignore them (default 1). */
+ relief?: number;
+ /** Direction sky light comes from, [dx, dy] (default [0, -1]: straight down). */
+ skyDir?: [number, number];
+}
+
+export interface GlowOpts {
+ /** Only pixels inside this region glow (the halo itself can spread past it). */
+ where?: Region;
+ /** Halo radius in px (default 6). */
+ r?: number;
+ /** Color mode: how strongly the halo brightens what's around, 0..1+ (default 0.5). */
+ strength?: number;
+ /** Color mode: one tint for the halo instead of each glowing pixel's own color. */
+ color?: string;
+ /** Quantize the falloff into this many rings (crisp pixel-art halo); 0 = smooth (default). */
+ bands?: number;
+ /** Ramp mode: step neighbours up to this many shades lighter along the ramps (stays in palette). */
+ ramp?: number;
+}
+
+export interface TextOpts {
+ scale?: number;
+ gap?: number;
+ lead?: number;
+ align?: "l" | "c" | "r";
+ shadow?: string;
+}
+
+export type { Region };
+
+export function isOp(v: unknown): v is Op {
+ return typeof v === "object" && v !== null && (v as Op).__op === true;
+}
+
+export function isLayer(v: unknown): v is Layer {
+ return typeof v === "object" && v !== null && (v as Layer).__layer === true;
+}
diff --git a/src/core/normals.ts b/src/core/normals.ts
new file mode 100644
index 0000000..43e14bc
--- /dev/null
+++ b/src/core/normals.ts
@@ -0,0 +1,131 @@
+// Normal maps: per-pixel surface directions that make lighting() rake across relief (bricks,
+// domes, bevels) instead of lighting everything flat. Generated from shape (bump) or painted
+// with numpad direction grids (normals); stored on the image (Img.norm) so they travel with it.
+import { TRANSPARENT, pack } from "./color.ts";
+import { PxError } from "./errors.ts";
+import { Img } from "./image.ts";
+import type { BumpOpts } from "./model.ts";
+
+/** Write normal (nx, ny, nz) (any length, ny pointing down) for pixel i; nz is kept >= ~0. */
+export function setNormal(n: Int8Array, i: number, nx: number, ny: number, nz: number): void {
+ const len = Math.hypot(nx, ny, nz) || 1;
+ n[i * 3] = Math.round((nx / len) * 127);
+ n[i * 3 + 1] = Math.round((ny / len) * 127);
+ n[i * 3 + 2] = Math.max(1, Math.round((nz / len) * 127)); // 0 is "no normal"
+}
+
+/**
+ * Numpad directions for normals() grids: the way the surface faces. 8 = up, 3 = down-right,
+ * 5 = straight at the viewer; lowercase-style softer tilts use the shifted row (q w e / a s d / z x c).
+ */
+const DIRS: Record<string, [number, number, number]> = {};
+const steep = 1, soft = 0.4;
+for (const [keys, t] of [["789456123", steep], ["qweasdzxc", soft]] as const)
+ [...keys].forEach((ch, k) => {
+ const dx = (k % 3) - 1, dy = Math.floor(k / 3) - 1;
+ DIRS[ch] = [dx * t, dy * t, 1];
+ });
+
+/** Normal for a direction grid char, null = skip ("." / space), "none" = clear ("0"). */
+export function dirOf(ch: string): [number, number, number] | null | "none" {
+ if (ch === "." || ch === " ") return null;
+ if (ch === "0") return "none";
+ const d = DIRS[ch];
+ if (!d) throw new PxError(`normals: unknown direction '${ch}' (numpad 1-9 steep, qweasdzxc soft, 0 clears, . skips)`);
+ return d;
+}
+
+/**
+ * Generate normals over `mask` pixels from a height field:
+ * - "bevel": edges slope down over `w` px, flat top (bricks, panels, buttons)
+ * - "dome": each connected blob bulges like a pillow / sphere (barrels, fruit, rocks)
+ * - "luma": brighter = higher, from the art's own shading (hand-shaded sprites)
+ * Pixels outside the mask (and outside the image) count as height 0 for bevel/dome.
+ */
+export function bump(img: Img, mask: Uint8Array, o: BumpOpts): void {
+ const { w, h } = img, n = w * h;
+ const shape = o.shape ?? "dome", depth = o.depth ?? 1;
+ const ht = new Float32Array(n);
+ if (shape === "luma") {
+ for (let i = 0; i < n; i++) {
+ if (!mask[i]) continue;
+ const c = img.data[i];
+ ht[i] = (0.3 * (c >>> 24) + 0.59 * ((c >>> 16) & 255) + 0.11 * ((c >>> 8) & 255)) / 255 * 4;
+ }
+ } else if (shape === "bevel" || shape === "dome") {
+ const d = distance(mask, w, h);
+ if (shape === "bevel") {
+ const bw = Math.max(1, o.w ?? 2);
+ for (let i = 0; i < n; i++) ht[i] = Math.min(d[i], bw);
+ } else {
+ // Per blob: a circular profile over its own deepest distance.
+ const blob = new Int32Array(n).fill(-1), peak: number[] = [];
+ for (let s = 0; s < n; s++) {
+ if (!mask[s] || blob[s] >= 0) continue;
+ const id = peak.length, stack = [s];
+ let top = 0;
+ blob[s] = id;
+ while (stack.length) {
+ const i = stack.pop()!, x = i % w;
+ top = Math.max(top, d[i]);
+ for (const j of [x > 0 ? i - 1 : -1, x < w - 1 ? i + 1 : -1, i - w, i + w])
+ if (j >= 0 && j < n && mask[j] && blob[j] < 0) { blob[j] = id; stack.push(j); }
+ }
+ peak.push(top);
+ }
+ for (let i = 0; i < n; i++) {
+ if (!mask[i]) continue;
+ const R = peak[blob[i]], t = 1 - d[i] / (R + 0.5);
+ ht[i] = (R + 0.5) * Math.sqrt(Math.max(0, 1 - t * t));
+ }
+ }
+ } else throw new PxError(`bump shape must be "bevel", "dome" or "luma", got '${shape}'`);
+
+ const nm = img.normals();
+ const at = (x: number, y: number, i: number) => {
+ if (x < 0 || y < 0 || x >= w || y >= h) return shape === "luma" ? ht[i] : 0;
+ const j = y * w + x;
+ return mask[j] ? ht[j] : shape === "luma" ? ht[i] : 0;
+ };
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ if (!mask[i]) continue;
+ const gx = (at(x + 1, y, i) - at(x - 1, y, i)) / 2, gy = (at(x, y + 1, i) - at(x, y - 1, i)) / 2;
+ setNormal(nm, i, -gx * depth, -gy * depth, 1);
+ }
+}
+
+/** Chamfer distance (1, √2) from each mask pixel to the nearest non-mask pixel or the border. */
+function distance(mask: Uint8Array, w: number, h: number): Float32Array {
+ const d = new Float32Array(w * h), D = Math.SQRT2;
+ const get = (x: number, y: number) => (x < 0 || y < 0 || x >= w || y >= h ? 0 : d[y * w + x]);
+ for (let i = 0; i < d.length; i++) d[i] = mask[i] ? 1e9 : 0;
+ for (let y = 0; y < h; y++)
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ if (d[i]) d[i] = Math.min(d[i], get(x - 1, y) + 1, get(x, y - 1) + 1, get(x - 1, y - 1) + D, get(x + 1, y - 1) + D);
+ }
+ for (let y = h - 1; y >= 0; y--)
+ for (let x = w - 1; x >= 0; x--) {
+ const i = y * w + x;
+ if (d[i]) d[i] = Math.min(d[i], get(x + 1, y) + 1, get(x, y + 1) + 1, get(x + 1, y + 1) + D, get(x - 1, y + 1) + D);
+ }
+ return d;
+}
+
+/**
+ * The normal map as an image in the common game-engine encoding (Godot, Unity, LDtk...):
+ * RGB = normal * 0.5 + 0.5 with green pointing up; flat (128, 128, 255) where none was set.
+ */
+export function normalImage(img: Img): Img {
+ const out = new Img(img.w, img.h), n = img.norm;
+ for (let i = 0; i < img.data.length; i++) {
+ if (img.data[i] === TRANSPARENT) continue;
+ const has = n && n[i * 3 + 2] > 0;
+ const nx = has ? n![i * 3] / 127 : 0, ny = has ? n![i * 3 + 1] / 127 : 0, nz = has ? n![i * 3 + 2] / 127 : 1;
+ const b = (v: number) => Math.min(255, Math.max(0, Math.round((v * 0.5 + 0.5) * 255)));
+ out.data[i] = pack(b(nx), b(-ny), b(nz), 255);
+ }
+ return out;
+}
diff --git a/src/core/palette.ts b/src/core/palette.ts
new file mode 100644
index 0000000..44ae05f
--- /dev/null
+++ b/src/core/palette.ts
@@ -0,0 +1,145 @@
+import { type Color, parseHex, TRANSPARENT, toHex } from "./color.ts";
+import { PxError, didYouMean } from "./errors.ts";
+
+export const INDEX_KEYS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
+const RESERVED = new Set([".", "_", " ", "#"]);
+
+export const BUILTIN: Record<string, string[]> = {
+ pico8: ["000000", "1d2b53", "7e2553", "008751", "ab5236", "5f574f", "c2c3c7", "fff1e8",
+ "ff004d", "ffa300", "ffec27", "00e436", "29adff", "83769c", "ff77a8", "ffccaa"],
+ sweetie16: ["1a1c2c", "5d275d", "b13e53", "ef7d57", "ffcd75", "a7f070", "38b764", "257179",
+ "29366f", "3b5dc9", "41a6f6", "73eff7", "f4f4f4", "94b0c2", "566c86", "333c57"],
+ db16: ["140c1c", "442434", "30346d", "4e4a4e", "854c30", "346524", "d04648", "757161",
+ "597dce", "d27d2c", "8595a1", "6daa2c", "d2aa99", "6dc2ca", "dad45e", "deeed6"],
+ endesga32: ["be4a2f", "d77643", "ead4aa", "e4a672", "b86f50", "733e39", "3e2731", "a22633",
+ "e43b44", "f77622", "feae34", "fee761", "63c74d", "3e8948", "265c42", "193c3e",
+ "124e89", "0099db", "2ce8f5", "ffffff", "c0cbdc", "8b9bb4", "5a6988", "3a4466",
+ "262b44", "181425", "ff0044", "68386c", "b55088", "f6757a", "e8b796", "c28569"],
+ gray8: ["000000", "242424", "494949", "6d6d6d", "929292", "b6b6b6", "dbdbdb", "ffffff"],
+};
+
+/** What a color spec resolves to: a color, or null for "skip this pixel". */
+export type Resolved = Color | null;
+
+/**
+ * Immutable palette: single-char keys -> colors, plus light/dark ramps.
+ * Ramps are strings of keys from dark to light ("kDdu"); shade() steps left, light() right.
+ */
+export class Palette {
+ readonly keys: ReadonlyMap<string, Color>;
+ readonly list: readonly Color[];
+ readonly order: readonly string[];
+ readonly aliases: ReadonlySet<string>;
+ readonly ramps: readonly string[];
+
+ constructor(keys: Map<string, Color>, list: Color[], order: string[], aliases: Set<string>, ramps: string[]) {
+ this.keys = keys;
+ this.list = list;
+ this.order = order;
+ this.aliases = aliases;
+ this.ramps = ramps;
+ }
+
+ static fromColors(colors: (string | number)[]): Palette {
+ const keys = new Map<string, Color>(), list: Color[] = [], order: string[] = [];
+ colors.forEach((c, i) => {
+ const v = typeof c === "number" ? c >>> 0 : parseHex(c);
+ if (v === undefined) throw new PxError(`bad palette color '${c}'`);
+ list.push(v);
+ const k = INDEX_KEYS[i];
+ if (k) { keys.set(k, v); order.push(k); }
+ });
+ return new Palette(keys, list, order, new Set(), []);
+ }
+
+ static builtin(name: string): Palette {
+ const cols = BUILTIN[name];
+ if (!cols) throw new PxError(`unknown palette '${name}'${didYouMean(name, Object.keys(BUILTIN))} (have: ${Object.keys(BUILTIN).join(", ")})`);
+ return Palette.fromColors(cols);
+ }
+
+ /** Add/override keys: { g: 11 (index), X: "#123456", h: "k" (copy another key) }. */
+ extend(aliases: Record<string, string | number>): Palette {
+ const keys = new Map(this.keys), order = [...this.order], al = new Set(this.aliases);
+ for (const k of Object.keys(aliases)) {
+ const v = aliases[k];
+ if ([...k].length !== 1) throw new PxError(`palette key must be one character, got '${k}'`);
+ if (RESERVED.has(k)) throw new PxError(`palette key '${k}' is reserved (. _ space #)`);
+ let c: Color | undefined;
+ if (typeof v === "number") {
+ c = this.list[v];
+ if (c === undefined) throw new PxError(`palette index ${v} out of range for key '${k}' (0..${this.list.length - 1})`);
+ } else if ([...v].length === 1) {
+ c = keys.get(v);
+ if (c === undefined) throw new PxError(`key '${k}' refers to unknown key '${v}'`);
+ } else {
+ c = parseHex(v);
+ if (c === undefined) throw new PxError(`bad color '${v}' for key '${k}' (use "#rrggbb")`);
+ }
+ if (!keys.has(k)) order.push(k);
+ keys.set(k, c);
+ al.add(k);
+ }
+ return new Palette(keys, [...this.list], order, al, [...this.ramps]);
+ }
+
+ withRamps(ramps: string[]): Palette {
+ for (const r of ramps)
+ for (const k of r) if (!this.keys.has(k)) throw new PxError(`ramp "${r}" uses unknown key '${k}'${didYouMean(k, this.order)}`);
+ return new Palette(new Map(this.keys), [...this.list], [...this.order], new Set(this.aliases), [...this.ramps, ...ramps]);
+ }
+
+ /** Key char, "#hex", "." (skip -> null) or "_" (erase -> transparent). */
+ resolve(spec: unknown): Resolved {
+ if (spec === "." ) return null;
+ if (spec === "_") return TRANSPARENT;
+ if (typeof spec === "number") return spec >>> 0;
+ if (typeof spec !== "string" || spec === "") throw new PxError(`color must be a palette key or "#hex", got ${JSON.stringify(spec)}`);
+ if (spec.startsWith("#")) {
+ const c = parseHex(spec);
+ if (c === undefined) throw new PxError(`bad color '${spec}'`);
+ return c;
+ }
+ const c = this.keys.get(spec);
+ if (c === undefined) {
+ const hint = this.keys.has(spec.toLowerCase()) ? ` (did you mean '${spec.toLowerCase()}'?)`
+ : this.keys.has(spec.toUpperCase()) ? ` (did you mean '${spec.toUpperCase()}'?)` : "";
+ throw new PxError(`unknown color key '${spec}'${hint} (have: ${this.order.join("")})`);
+ }
+ return c;
+ }
+
+ /** Map color -> darker (dir -1) or lighter (dir +1) neighbour along the ramps. */
+ stepMap(dir: -1 | 1): Map<Color, Color> {
+ if (!this.ramps.length) throw new PxError('no ramps defined: add ramps("kDdu", ...) (dark -> light) after pal()');
+ const m = new Map<Color, Color>();
+ for (const r of this.ramps) {
+ const ks = [...r];
+ for (let i = 0; i < ks.length; i++) {
+ const to = ks[i + dir];
+ if (to === undefined) continue;
+ const a = this.keys.get(ks[i])!, b = this.keys.get(to)!;
+ if (!m.has(a)) m.set(a, b);
+ }
+ }
+ return m;
+ }
+
+ /** Color -> key, preferring named aliases over index keys. */
+ reverse(): Map<Color, string> {
+ const r = new Map<Color, string>();
+ for (const k of this.order) {
+ const c = this.keys.get(k)!;
+ const cur = r.get(c);
+ if (cur === undefined || (this.aliases.has(k) && !this.aliases.has(cur))) r.set(c, k);
+ }
+ return r;
+ }
+
+ /** Key -> "#hex" for viewers. */
+ table(): Record<string, string> {
+ const t: Record<string, string> = {};
+ for (const k of this.order) t[k] = toHex(this.keys.get(k)!);
+ return t;
+ }
+}
diff --git a/src/core/project.ts b/src/core/project.ts
new file mode 100644
index 0000000..e9c23d3
--- /dev/null
+++ b/src/core/project.ts
@@ -0,0 +1,377 @@
+// Project: the registry an art file fills in, plus the lazy, cached, cycle-checked resolver.
+import { type BuildCtx, type BuildOut, buildAsset, gcd } from "./build.ts";
+import { OPS } from "./canvas.ts";
+import { PxError, didYouMean, wrap } from "./errors.ts";
+import type { Img } from "./image.ts";
+import {
+ type AssetDef, type AssetKind, type AssetOpts, type GroupDef, type Item, type Layer, type LayerOpts, type Op,
+ type SheetDef, type SheetOpts, type Timeline, isLayer, isOp,
+} from "./model.ts";
+import { Palette } from "./palette.ts";
+import { Trace } from "./trace.ts";
+import { globRe, rng } from "./util.ts";
+
+/**
+ * Op signatures: name:type, "?" marks the first optional argument.
+ * n number, c color, s string, t text (string|number), S colors ("abc" or array),
+ * a point array, r region, o object, b boolean, I items (rest).
+ */
+export const SIGNATURES: Record<string, string> = {
+ px: "x:n y:n c:c",
+ rect: "x:n y:n w:n h:n c:c",
+ box: "x:n y:n w:n h:n c:c",
+ line: "x0:n y0:n x1:n y1:n c:c ?width:n",
+ hline: "x:n y:n len:n c:c",
+ vline: "x:n y:n len:n c:c",
+ ellipse: "cx:n cy:n rx:n ry:n c:c ?ring:b",
+ circ: "cx:n cy:n r:n c:c",
+ ring: "cx:n cy:n r:n c:c",
+ poly: "points:a c:c",
+ fill: "x:n y:n c:c",
+ dither: "x:n y:n w:n h:n c1:c c2:c ?density:n",
+ grad: "x:n y:n w:n h:n colors:S ?dir:s soft:n",
+ noise: "x:n y:n w:n h:n colors:S ?density:n seed:n on:s",
+ recolor: "map:o ?where:r density:n",
+ shade: "?where:r steps:n density:n",
+ light: "?where:r steps:n density:n",
+ stamp: "name:s ?x:n y:n opts:o",
+ tile: "name:s x:n y:n ?cols:n rows:n opts:o",
+ pattern: "name:s x:n y:n w:n h:n ?opts:o",
+ tilemap: "map:s opts:o",
+ scatter: "name:s x:n y:n w:n h:n count:n ?opts:o",
+ grid: "x:n y:n str:s",
+ wire: "x0:n y0:n x1:n y1:n sag:n c:c ?opts:o",
+ text: "x:n y:n str:t c:c ?opts:o",
+ clip: "where:r ...items:I",
+ lamp: "x:n y:n ?opts:o",
+ bump: "?shape:s opts:o",
+ normals: "x:n y:n str:s",
+ lighting: "?opts:o",
+ glow: "keys:S ?opts:o",
+};
+
+/** Allowed option keys of ops whose last argument is an options object. */
+const OP_OPTS: Record<string, string[]> = {
+ lamp: ["r", "color", "power", "z"],
+ bump: ["w", "depth", "on", "where"],
+ lighting: ["cell", "ambient", "ambientColor", "sky", "skyColor", "skyReach", "block", "smooth", "emit", "shape", "relief", "skyDir"],
+ glow: ["where", "r", "strength", "color", "bands", "ramp"],
+};
+
+const ASSET_OPTS: Record<AssetKind, string[]> = {
+ sprite: ["w", "h", "base", "mx", "my", "swap", "flip", "rot", "outline", "outline8", "crop", "layers"],
+ scene: ["w", "h", "bg", "mx", "my", "swap", "flip", "rot", "outline", "outline8", "crop", "layers"],
+ anim: ["w", "h", "base", "mx", "my", "swap", "flip", "rot", "outline", "outline8", "crop", "layers", "fps", "frames", "loop"],
+};
+const FRAME_OPTS = ["ms", "hold"];
+/** Longest loop a combined timeline may have (ms); longer ones are cut. */
+const MAX_LOOP = 60000;
+const LAYER_OPTS = ["x", "y", "hidden", "shade", "light", "density", "solid", "wall", "unlit"];
+const SHEET_OPTS = ["cols", "pad"];
+
+function checkArgs(name: string, args: unknown[]): void {
+ const sig = SIGNATURES[name];
+ if (!sig) return;
+ let optional = false;
+ sig.split(" ").forEach((part, i) => {
+ if (part.startsWith("?")) { optional = true; part = part.slice(1); }
+ const [pname, type] = part.split(":");
+ if (pname.startsWith("...")) return;
+ const v = args[i];
+ if (v === undefined) {
+ if (!optional) throw new PxError(`${name}: missing argument ${i + 1} (${pname}); usage: ${name}(${usage(sig)})`);
+ return;
+ }
+ const bad = (want: string) => {
+ throw new PxError(`${name}: argument ${i + 1} (${pname}) must be ${want}, got ${JSON.stringify(v) ?? typeof v}; usage: ${name}(${usage(sig)})`);
+ };
+ switch (type) {
+ case "n": if (typeof v !== "number" || !Number.isFinite(v)) bad("a number"); break;
+ case "c": if (typeof v !== "string") bad('a color key or "#hex"'); break;
+ case "s": if (typeof v !== "string") bad("a string"); break;
+ case "t": if (typeof v !== "string" && typeof v !== "number") bad("text"); break;
+ case "S": if (typeof v !== "string" && !Array.isArray(v)) bad('colors like "abc" or ["a","b"]'); break;
+ case "a": if (!Array.isArray(v)) bad("an array of numbers"); break;
+ case "o": if (typeof v !== "object" || v === null || Array.isArray(v)) bad("an options object"); break;
+ case "b": if (typeof v !== "boolean") bad("true/false"); break;
+ }
+ });
+}
+
+function usage(sig: string): string {
+ return sig.split(" ").map((p) => p.replace(/:.*/, "").replace(/^\?/, "[")).join(", ") + (sig.includes("?") ? "]" : "");
+}
+
+function checkKeys(what: string, obj: object, allowed: string[], loc?: string): void {
+ for (const k of Object.keys(obj))
+ if (!allowed.includes(k)) throw new PxError(`${what}: unknown option '${k}'${didYouMean(k, allowed)} (allowed: ${allowed.join(", ")})`, loc);
+}
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !isOp(v) && !isLayer(v);
+}
+
+function checkItems(where: string, items: unknown[], loc?: string): Item[] {
+ items.forEach((v, i) => {
+ const ok = typeof v === "string" || typeof v === "function" || isOp(v) || isLayer(v);
+ if (!ok) {
+ const what = Array.isArray(v) ? "an array (use ...spread)" : v === undefined ? "undefined (missing comma or op name?)" : `a ${typeof v}`;
+ throw new PxError(`${where}: item ${i + 1} is ${what}; items are grid strings, ops, functions or layers`, loc);
+ }
+ });
+ return items as Item[];
+}
+
+export interface ProjectOptions {
+ /** Record painting traces for seed-0 builds (live viewer). */
+ trace?: boolean;
+}
+
+export class Project implements BuildCtx {
+ readonly assets = new Map<string, AssetDef>();
+ readonly order: string[] = [];
+ readonly groups = new Map<string, GroupDef>();
+ readonly sheets: SheetDef[] = [];
+ /** Art files loaded so far (absolute paths or virtual names), for locations and watching. */
+ readonly files: string[] = [];
+ pal: Palette = Palette.builtin("pico8");
+ /** Set by a loader to support include(). */
+ includeHook?: (path: string) => void;
+
+ private cache = new Map<string, BuildOut>();
+ /** Timelines gathered from animated assets placed by the builds in progress (innermost last). */
+ private collect: Partial<Timeline>[] = [];
+ private building = new Set<string>();
+ private cands = new Map<string, string[]>();
+ private failed = new Map<string, PxError>();
+ private tracing: boolean;
+
+ constructor(opts: ProjectOptions = {}) {
+ this.tracing = !!opts.trace;
+ }
+
+ // ---------------------------------------------------------------- locations
+
+ addFile(file: string): void {
+ if (!this.files.includes(file)) this.files.push(file);
+ }
+
+ locFromStack(stack: string): string | undefined {
+ for (const line of stack.split("\n")) {
+ for (const f of this.files) {
+ const i = line.indexOf(f + ":");
+ if (i < 0) continue;
+ const m = /^:(\d+):(\d+)/.exec(line.slice(i + f.length));
+ if (m) return `${shortName(f)}:${m[1]}:${m[2]}`;
+ }
+ }
+ return undefined;
+ }
+
+ callerLoc(): string | undefined {
+ const limit = Error.stackTraceLimit;
+ Error.stackTraceLimit = 60;
+ const stack = new Error().stack ?? "";
+ Error.stackTraceLimit = limit;
+ return this.locFromStack(stack);
+ }
+
+ // ---------------------------------------------------------------- DSL
+
+ /** Functions visible to art files. */
+ env(): Record<string, unknown> {
+ const env: Record<string, unknown> = {};
+ const define = (kind: AssetKind, name: unknown, rest: unknown[]) => {
+ const loc = this.callerLoc();
+ if (typeof name !== "string" || !name) throw new PxError(`${kind} needs a name string first`, loc);
+ const prev = this.assets.get(name) ?? this.groups.get(name);
+ if (prev) throw new PxError(`'${name}' is already defined at ${prev.loc}`, loc);
+ const opts = (isPlainObject(rest[0]) ? rest.shift() : {}) as AssetOpts;
+ checkKeys(`${kind} '${name}'`, opts, ASSET_OPTS[kind], loc);
+ const items = checkItems(`${kind} '${name}'`, rest, loc);
+ this.assets.set(name, { kind, name, opts, items, pal: this.pal, loc });
+ this.order.push(name);
+ };
+
+ env.use = (p: unknown) => {
+ if (Array.isArray(p)) this.pal = Palette.fromColors(p as (string | number)[]);
+ else if (typeof p === "string") this.pal = Palette.builtin(p);
+ else throw new PxError('use("pico8") or use(["#000", "#fff", ...])', this.callerLoc());
+ };
+ env.pal = (aliases: Record<string, string | number>) => {
+ try { this.pal = this.pal.extend(aliases); } catch (e) { throw wrap(e).within("pal", this.callerLoc()); }
+ };
+ env.ramps = (...ramps: string[]) => {
+ try { this.pal = this.pal.withRamps(ramps); } catch (e) { throw wrap(e).within("ramps", this.callerLoc()); }
+ };
+ env.sprite = (name: unknown, ...rest: unknown[]) => define("sprite", name, rest);
+ env.anim = (name: unknown, ...rest: unknown[]) => define("anim", name, rest);
+ env.frame = (...args: unknown[]): Op => {
+ const loc = this.callerLoc();
+ if (isPlainObject(args[0])) checkKeys("frame", args[0], FRAME_OPTS, loc);
+ checkItems("frame", isPlainObject(args[0]) ? args.slice(1) : args, loc);
+ return { __op: true, name: "frame", args, loc };
+ };
+ env.scene = (name: unknown, ...rest: unknown[]) => define("scene", name, rest);
+ env.layer = (name: unknown, ...rest: unknown[]): Layer => {
+ const loc = this.callerLoc();
+ if (typeof name !== "string") throw new PxError("layer needs a name string first", loc);
+ const opts = (isPlainObject(rest[0]) ? rest.shift() : {}) as LayerOpts;
+ checkKeys(`layer '${name}'`, opts, LAYER_OPTS, loc);
+ return { __layer: true, name, opts, items: checkItems(`layer '${name}'`, rest, loc), loc };
+ };
+ env.group = (name: unknown, members: unknown) => {
+ const loc = this.callerLoc();
+ if (typeof name !== "string" || !Array.isArray(members) || !members.every((m) => typeof m === "string"))
+ throw new PxError('group("name", ["a", "b*", ...])', loc);
+ const prev = this.assets.get(name) ?? this.groups.get(name);
+ if (prev) throw new PxError(`'${name}' is already defined at ${prev.loc}`, loc);
+ this.groups.set(name, { name, members, loc });
+ };
+ env.sheet = (name: unknown, entries: unknown, opts: SheetOpts = {}) => {
+ const loc = this.callerLoc();
+ if (typeof name !== "string" || !Array.isArray(entries)) throw new PxError('sheet("name", ["a", "b*"], { cols, pad })', loc);
+ checkKeys(`sheet '${name}'`, opts, SHEET_OPTS, loc);
+ this.sheets.push({ name, entries, opts, loc });
+ };
+ env.include = (path: unknown) => {
+ if (typeof path !== "string") throw new PxError('include("other.px.js")', this.callerLoc());
+ if (!this.includeHook) throw new PxError("include() is not available here", this.callerLoc());
+ this.includeHook(path);
+ };
+ env.rng = (seed?: number) => rng(seed);
+
+ for (const name of [...OPS, "clip", "lighting", "glow"]) {
+ env[name] = (...args: unknown[]): Op => {
+ const loc = this.callerLoc();
+ try {
+ checkArgs(name, args);
+ const o = args[args.length - 1];
+ if (OP_OPTS[name] && isPlainObject(o)) checkKeys(name, o, OP_OPTS[name]);
+ } catch (e) { throw wrap(e).within(name, loc); }
+ if (name === "clip") checkItems("clip", args.slice(1), loc);
+ return { __op: true, name, args, loc };
+ };
+ }
+ return env;
+ }
+
+ // ---------------------------------------------------------------- resolving
+
+ candidates(name: string, depth = 0): string[] {
+ const hit = this.cands.get(name);
+ if (hit) return hit;
+ if (typeof name !== "string") throw new PxError(`asset name must be a string, got ${typeof name}`);
+ if (depth > 8) throw new PxError(`group nesting too deep at '${name}'`);
+ let list: string[] = [];
+ const g = this.groups.get(name);
+ if (g) for (const m of g.members) list.push(...this.candidates(m, depth + 1));
+ else if (name.includes("*")) {
+ const re = globRe(name);
+ list = this.order.filter((n) => re.test(n));
+ } else list = [name];
+ if (!list.length) throw new PxError(`'${name}' matches no assets`);
+ this.cands.set(name, list);
+ return list;
+ }
+
+ image(name: string, seed = 0, t = 0, track = true): Img {
+ return this.build(name, seed, t, track).img;
+ }
+
+ timeline(name: string, seed = 0): Timeline | undefined {
+ return this.build(name, seed, 0, false).anim;
+ }
+
+ /**
+ * Build an asset at time t (ms). Still assets ignore t. Unless `track` is false, an animated
+ * result makes the asset being built around this call animated too.
+ */
+ build(name: string, seed = 0, t = 0, track = true): BuildOut {
+ const first = this.buildAt(name, seed, 0);
+ const tl = first.anim;
+ if (tl && track && this.collect.length) {
+ const acc = this.collect[this.collect.length - 1];
+ acc.loop = acc.loop ? Math.min(MAX_LOOP, lcm(acc.loop, tl.loop)) : tl.loop;
+ acc.step = acc.step ? gcd(acc.step, tl.step) : tl.step;
+ }
+ if (!tl || t === 0) return first;
+ const tt = tl.once ? Math.min(Math.max(0, t), tl.loop) : ((t % tl.loop) + tl.loop) % tl.loop;
+ return tt === 0 ? first : this.buildAt(name, seed, tt);
+ }
+
+ /** One full loop of an animated asset as [{ img, ms }]; [] for still assets. */
+ frames(name: string, seed = 0, max = 600): { img: Img; ms: number }[] {
+ const tl = this.build(name, seed).anim;
+ if (!tl) return [];
+ if (tl.durations) {
+ let t = 0;
+ return tl.durations.map((ms) => {
+ const f = { img: this.build(name, seed, t).img, ms };
+ t += ms;
+ return f;
+ });
+ }
+ const n = Math.max(1, Math.min(max, Math.round(tl.loop / tl.step)));
+ return Array.from({ length: n }, (_, i) => ({ img: this.build(name, seed, i * tl.step).img, ms: tl.step }));
+ }
+
+ private buildAt(name: string, seed: number, t: number): BuildOut {
+ const key = (seed === 0 ? name : `${name}@${seed}`) + (t ? `#${t}` : "");
+ const hit = this.cache.get(key);
+ if (hit) return hit;
+ const def = this.assets.get(name);
+ if (!def) {
+ if (this.groups.has(name) || name.includes("*"))
+ throw new PxError(`'${name}' is a group/glob: use it in stamp, tile, pattern, tilemap, scatter or wire hang`);
+ throw new PxError(`unknown asset '${name}'${didYouMean(name, this.order)}`);
+ }
+ const failed = this.failed.get(key);
+ if (failed) throw new PxError(`depends on '${name}', which failed`);
+ if (this.building.has(name)) throw new PxError(`reference cycle through '${name}'`);
+ this.building.add(name);
+ const acc: Partial<Timeline> = {};
+ this.collect.push(acc);
+ try {
+ const out = buildAsset(this, def, seed, this.tracing && seed === 0 && t === 0 ? new Trace() : undefined, t);
+ // Anims keep their own frame timing; other assets are as animated as what they place.
+ if (!out.anim && acc.loop) out.anim = { loop: acc.loop, step: acc.step! };
+ this.cache.set(key, out);
+ return out;
+ } catch (e) {
+ const err = wrap(e, (s) => this.locFromStack(s)).within(`${def.kind} '${name}'`, def.loc);
+ this.failed.set(key, err);
+ throw err;
+ } finally {
+ this.collect.pop();
+ this.building.delete(name);
+ }
+ }
+
+ /** Exported asset names (no "_" prefix), in definition order. */
+ exported(): string[] {
+ return this.order.filter((n) => !n.startsWith("_"));
+ }
+
+ /** Expand a sheet's entries: globs match exported names, groups expand to members. */
+ sheetNames(s: SheetDef): string[] {
+ const out: string[] = [];
+ const add = (n: string) => { if (!out.includes(n)) out.push(n); };
+ for (const e of s.entries) {
+ if (e.includes("*")) {
+ const re = globRe(e);
+ this.exported().filter((n) => re.test(n)).forEach(add);
+ } else if (this.groups.has(e)) this.candidates(e).forEach(add);
+ else add(e);
+ }
+ return out;
+ }
+}
+
+function lcm(a: number, b: number): number {
+ return (a / gcd(a, b)) * b;
+}
+
+function shortName(f: string): string {
+ return f.replace(/^.*[\\/]/, "");
+}
diff --git a/src/core/render.ts b/src/core/render.ts
new file mode 100644
index 0000000..9f5264d
--- /dev/null
+++ b/src/core/render.ts
@@ -0,0 +1,104 @@
+// Derived views of built images: previews for eyes, ASCII for exact checks, sheet packing.
+import { type Color, TRANSPARENT, darken, pack } from "./color.ts";
+import { Img } from "./image.ts";
+import type { Palette } from "./palette.ts";
+
+const LIGHT = pack(0xe4, 0xe4, 0xe4), DARK = pack(0xc8, 0xc8, 0xc8);
+
+/** Auto preview scale: longest side ~768px, clamped to 1..16. */
+export function previewScale(img: Img, max = 768): number {
+ return Math.max(1, Math.min(16, Math.floor(max / Math.max(img.w, img.h))));
+}
+
+/**
+ * Upscaled preview: checkerboard behind transparency (one check per source pixel) and,
+ * at scale >= 6, a pixel grid with every 8th line darker for reading coordinates.
+ */
+export function preview(img: Img, scale = previewScale(img)): Img {
+ const s = scale;
+ const o = new Img(img.w * s, img.h * s);
+ for (let y = 0; y < o.h; y++) {
+ const sy = Math.floor(y / s);
+ for (let x = 0; x < o.w; x++) {
+ const sx = Math.floor(x / s);
+ let c: Color = img.data[sy * img.w + sx];
+ if (c === TRANSPARENT || (c & 255) === 0) c = (sx + sy) % 2 === 0 ? LIGHT : DARK;
+ if (s >= 6 && (x % s === 0 || y % s === 0)) {
+ const major = (x % s === 0 && sx % 8 === 0) || (y % s === 0 && sy % 8 === 0);
+ c = darken(c, major ? 0.45 : 0.18);
+ }
+ o.data[y * o.w + x] = c;
+ }
+ }
+ return o;
+}
+
+/** Text dump with x/y rulers; colors shown as palette keys ("." transparent, "?" unknown). */
+export function ascii(img: Img, pal: Palette): string {
+ const rev = pal.reverse();
+ const tens = " " + Array.from({ length: img.w }, (_, x) => (x % 10 === 0 ? String(Math.floor(x / 10) % 10) : " ")).join("");
+ const ones = " " + Array.from({ length: img.w }, (_, x) => String(x % 10)).join("");
+ const lines = img.w > 10 ? [tens, ones] : [ones];
+ for (let y = 0; y < img.h; y++) {
+ let row = String(y).padStart(3) + " ";
+ for (let x = 0; x < img.w; x++) {
+ const c = img.data[y * img.w + x];
+ row += c === TRANSPARENT ? "." : rev.get(c) ?? "?";
+ }
+ lines.push(row);
+ }
+ return lines.join("\n");
+}
+
+export interface SheetFrame {
+ name: string;
+ img: Img;
+ x: number;
+ y: number;
+ /** Animation frames: duration in ms. */
+ ms?: number;
+}
+
+/** A named run of animation frames in a sheet (Aseprite "frameTags"). */
+export interface FrameTag {
+ name: string;
+ from: number;
+ to: number;
+}
+
+/** Shelf packing: `cols` frames per row, `pad` px between them. */
+export function packSheet(items: { name: string; img: Img; ms?: number }[], cols?: number, pad = 0): { sheet: Img; frames: SheetFrame[] } {
+ if (!items.length) throw new Error("sheet is empty");
+ const perRow = cols ?? Math.ceil(Math.sqrt(items.length));
+ const frames: SheetFrame[] = [];
+ let x = 0, y = 0, rowH = 0, W = 0;
+ items.forEach((it, i) => {
+ if (i > 0 && i % perRow === 0) { x = 0; y += rowH + pad; rowH = 0; }
+ frames.push({ ...it, x, y });
+ W = Math.max(W, x + it.img.w);
+ x += it.img.w + pad;
+ rowH = Math.max(rowH, it.img.h);
+ });
+ const sheet = new Img(W, y + rowH);
+ for (const f of frames) sheet.blit(f.img, f.x, f.y);
+ return { sheet, frames };
+}
+
+/**
+ * TexturePacker "hash" JSON (read by Phaser, Godot importers, etc.). Animation frames add a
+ * `duration` (ms) and `meta.frameTags`, as Aseprite exports them.
+ */
+export function sheetJson(image: string, sheet: Img, frames: SheetFrame[], tags: FrameTag[] = []): string {
+ const out: Record<string, unknown> = {};
+ for (const f of frames) {
+ const { w, h } = f.img;
+ out[f.name] = {
+ frame: { x: f.x, y: f.y, w, h }, rotated: false, trimmed: false,
+ spriteSourceSize: { x: 0, y: 0, w, h }, sourceSize: { w, h },
+ ...(f.ms !== undefined ? { duration: f.ms } : {}),
+ };
+ }
+ const meta: Record<string, unknown> = { app: "pxl", image, format: "RGBA8888", size: { w: sheet.w, h: sheet.h }, scale: "1" };
+ if (tags.length) meta.frameTags = tags.map((t) => ({ ...t, direction: "forward" }));
+ return JSON.stringify({ frames: out, meta }, null, 1) + "\n";
+}
diff --git a/src/core/trace.ts b/src/core/trace.ts
new file mode 100644
index 0000000..8b6ebf6
--- /dev/null
+++ b/src/core/trace.ts
@@ -0,0 +1,65 @@
+import type { Img } from "./image.ts";
+
+/**
+ * One painting step. Either `full` (first frame or size change) or `changes` as a flat
+ * [index, color, index, color, ...] list against the previous frame.
+ */
+export interface Frame {
+ label: string;
+ loc?: string;
+ w: number;
+ h: number;
+ full?: Uint32Array;
+ changes?: Uint32Array;
+}
+
+/** Records the composite image after every painting step of one asset build. */
+export class Trace {
+ frames: Frame[] = [];
+ /** Steps that happened after `max` was reached (folded into the last frame). */
+ dropped = 0;
+ private prev?: Img;
+ private max: number;
+
+ constructor(max = 4000) {
+ this.max = max;
+ }
+
+ record(label: string, loc: string | undefined, img: Img): void {
+ if (this.frames.length >= this.max - 1) {
+ this.dropped++;
+ this.pending = img;
+ return;
+ }
+ this.push(label, loc, img);
+ }
+
+ private pending?: Img;
+
+ /** Make sure the last frame shows the final image. */
+ finish(img: Img): void {
+ if (this.pending || this.dropped) this.push(`… ${this.dropped} more steps`, undefined, this.pending ?? img);
+ this.pending = undefined;
+ const last = this.prev;
+ if (!last || last.w !== img.w || last.h !== img.h || !sameData(last.data, img.data)) this.push("final", undefined, img);
+ }
+
+ private push(label: string, loc: string | undefined, img: Img): void {
+ const prev = this.prev;
+ if (!prev || prev.w !== img.w || prev.h !== img.h) {
+ this.frames.push({ label, loc, w: img.w, h: img.h, full: img.data.slice() });
+ } else {
+ const ch: number[] = [];
+ const a = prev.data, b = img.data;
+ for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) ch.push(i, b[i]);
+ this.frames.push({ label, loc, w: img.w, h: img.h, changes: Uint32Array.from(ch) });
+ }
+ this.prev = img.copy();
+ }
+}
+
+function sameData(a: Uint32Array, b: Uint32Array): boolean {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
+ return true;
+}
diff --git a/src/core/util.ts b/src/core/util.ts
new file mode 100644
index 0000000..a60970e
--- /dev/null
+++ b/src/core/util.ts
@@ -0,0 +1,125 @@
+// Small shared helpers: grids, randomness, regions, dithering.
+
+/** Grid string -> rows: each row trimmed, blank leading/trailing rows dropped. */
+export function gridRows(s: string): string[] {
+ const rows = s.replace(/\r/g, "").split("\n").map((r) => r.trim());
+ while (rows.length && rows[0] === "") rows.shift();
+ while (rows.length && rows[rows.length - 1] === "") rows.pop();
+ return rows;
+}
+
+export function gridSize(rows: string[]): { w: number; h: number } {
+ let w = 0;
+ for (const r of rows) w = Math.max(w, [...r].length);
+ return { w, h: rows.length };
+}
+
+/** sfc32 seeded through splitmix: fast, well distributed, deterministic. Returns f() -> [0, 1). */
+export function rng(seed = 1): () => number {
+ let s = seed >>> 0;
+ const mix = () => {
+ s = (s + 0x9e3779b9) >>> 0;
+ let z = s;
+ z = Math.imul(z ^ (z >>> 16), 0x85ebca6b);
+ z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35);
+ return (z ^ (z >>> 16)) >>> 0;
+ };
+ let a = mix(), b = mix(), c = mix(), d = mix();
+ const next = () => {
+ const t = (((a + b) >>> 0) + d) >>> 0;
+ d = (d + 1) >>> 0;
+ a = b ^ (b >>> 9);
+ b = (c + (c << 3)) >>> 0;
+ c = ((c << 21) | (c >>> 11)) >>> 0;
+ c = (c + t) >>> 0;
+ return t / 4294967296;
+ };
+ for (let i = 0; i < 8; i++) next();
+ return next;
+}
+
+/** Position-based seed: the same placement always makes the same choices. */
+export function hash(a: number, b: number, seed: number): number {
+ let h = Math.imul(Math.floor(a) | 0, 0x9e3779b1) ^ Math.imul(Math.floor(b) | 0, 0x85ebca77) ^ Math.imul(Math.floor(seed) | 0, 0xc2b2ae3d);
+ h = Math.imul(h ^ (h >>> 15), 0x2c1b3c6d);
+ h = Math.imul(h ^ (h >>> 12), 0x297a2d39);
+ return (h ^ (h >>> 15)) >>> 0;
+}
+
+const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
+/** Ordered-dither threshold in (0, 1) for pixel (x, y). */
+export function bayer(x: number, y: number): number {
+ return (BAYER[(((y % 4) + 4) % 4) * 4 + (((x % 4) + 4) % 4)] + 0.5) / 16;
+}
+
+/**
+ * Region -> predicate(x, y). undefined = everywhere; [cx, cy, r] circle; [x, y, w, h] rect;
+ * [x0, y0, x1, y1, x2, y2, ...] polygon (vertices on pixel corners); or a function.
+ */
+export type Region = undefined | null | number[] | ((x: number, y: number) => boolean);
+
+export function regionPred(r: Region): (x: number, y: number) => boolean {
+ if (r == null) return () => true;
+ if (typeof r === "function") return r;
+ if (Array.isArray(r)) {
+ if (r.length === 3) {
+ const [cx, cy, rad] = r, rr = (rad + 0.5) ** 2;
+ return (x, y) => (x - cx) ** 2 + (y - cy) ** 2 <= rr;
+ }
+ if (r.length === 4) {
+ const [x0, y0, w, h] = r;
+ return (x, y) => x >= x0 && y >= y0 && x < x0 + w && y < y0 + h;
+ }
+ if (r.length >= 6 && r.length % 2 === 0) return inPoly(r);
+ }
+ throw new Error("region must be [cx,cy,r], [x,y,w,h], a polygon [x0,y0,x1,y1,x2,y2,...] or a function(x,y)");
+}
+
+/** Even-odd test of pixel centers; vertices sit on pixel corners. */
+export function inPoly(pts: number[]): (x: number, y: number) => boolean {
+ const n = pts.length / 2;
+ return (px, py) => {
+ const x = px + 0.5, y = py + 0.5;
+ let inside = false;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ const xi = pts[2 * i], yi = pts[2 * i + 1], xj = pts[2 * j], yj = pts[2 * j + 1];
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
+ }
+ return inside;
+ };
+}
+
+/** Bounding box of a polygon point list. */
+export function polyBounds(pts: number[]): { x0: number; y0: number; x1: number; y1: number } {
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (let i = 0; i < pts.length; i += 2) {
+ x0 = Math.min(x0, pts[i]); x1 = Math.max(x1, pts[i]);
+ y0 = Math.min(y0, pts[i + 1]); y1 = Math.max(y1, pts[i + 1]);
+ }
+ return { x0, y0, x1, y1 };
+}
+
+/** "abc" or ["a", "b", "c"] -> list of color specs. */
+export function colorList(cols: string | string[]): string[] {
+ return Array.isArray(cols) ? [...cols] : [...cols];
+}
+
+/** Glob with "*" -> RegExp. */
+export function globRe(pattern: string): RegExp {
+ return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$");
+}
+
+/** Compact, readable argument formatting for op labels. */
+export function fmtArgs(args: unknown[]): string {
+ const f = (v: unknown, depth: number): string => {
+ if (typeof v === "string") return v.includes("\n") ? "`" + v.trim().split("\n")[0].trim() + "…`" : JSON.stringify(v);
+ if (typeof v === "function") return "fn";
+ if (Array.isArray(v)) return depth > 1 ? "[…]" : "[" + v.slice(0, 8).map((x) => f(x, depth + 1)).join(",") + (v.length > 8 ? ",…" : "") + "]";
+ if (v && typeof v === "object") {
+ if (depth > 1) return "{…}";
+ return "{" + Object.entries(v).filter(([k]) => !k.startsWith("__")).map(([k, x]) => k + ":" + f(x, depth + 1)).join(",") + "}";
+ }
+ return String(v);
+ };
+ return args.map((a) => f(a, 0)).join(", ");
+}
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 0000000..89cd6df
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,6 @@
+// Node entry: core + loading, output, live server.
+export * from "./core/index.ts";
+export { loadProject, loadSource } from "./node/load.ts";
+export { writeOutputs, writePng, type OutputOptions } from "./node/output.ts";
+export { encodePng } from "./node/png.ts";
+export { serve, type ServeOptions } from "./node/server.ts";
diff --git a/src/node/cli.ts b/src/node/cli.ts
new file mode 100644
index 0000000..68ca05a
--- /dev/null
+++ b/src/node/cli.ts
@@ -0,0 +1,110 @@
+// pxl command line.
+import { dirname, join, resolve } from "node:path";
+import { PxError, wrap } from "../core/errors.ts";
+import { ascii } from "../core/render.ts";
+import { loadProject } from "./load.ts";
+import { writeOutputs } from "./output.ts";
+import { serve } from "./server.ts";
+
+const USAGE = `pxl — pixel-art DSL
+
+ pxl build <art.px.js> [--out DIR] [--only a,b] [--scale N] [--no-preview]
+ Build PNGs (out/sprites, out/scenes, out/anims strips + JSON + GIF, sheets + JSON) and
+ previews (out/_preview; animated assets also get a .gif).
+ pxl serve <art.px.js> [--port 4321] [--out DIR | --no-out] [--no-preview]
+ Live viewer: rebuilds on save and replays each asset's painting steps.
+ pxl ascii <art.px.js> <name>
+ Print an asset as palette keys with x/y rulers (anims: every frame).
+ pxl list <art.px.js>
+ List assets, groups and sheets with their source locations.
+
+Art files may be .js or .ts. Default out dir: <art file dir>/out.`;
+
+interface Args {
+ cmd?: string;
+ file?: string;
+ rest: string[];
+ out?: string | false;
+ only?: string[];
+ scale?: number;
+ preview?: boolean;
+ port?: number;
+}
+
+function parse(argv: string[]): Args {
+ const a: Args = { rest: [] };
+ for (let i = 0; i < argv.length; i++) {
+ const v = argv[i];
+ const val = () => {
+ const x = argv[++i];
+ if (x === undefined) throw new PxError(`${v} needs a value`);
+ return x;
+ };
+ if (v === "--out") a.out = val();
+ else if (v === "--no-out") a.out = false;
+ else if (v === "--only") a.only = val().split(",").map((s) => s.trim()).filter(Boolean);
+ else if (v === "--scale") a.scale = Number(val());
+ else if (v === "--port") a.port = Number(val());
+ else if (v === "--no-preview") a.preview = false;
+ else if (v === "-h" || v === "--help") a.cmd = "help";
+ else if (v.startsWith("--")) throw new PxError(`unknown flag ${v}\n\n${USAGE}`);
+ else if (!a.cmd) a.cmd = v;
+ else if (!a.file) a.file = v;
+ else a.rest.push(v);
+ }
+ return a;
+}
+
+export async function main(argv: string[]): Promise<number> {
+ let a: Args;
+ try { a = parse(argv); } catch (e) { console.error(wrap(e).message); return 2; }
+ if (!a.cmd || a.cmd === "help" || !a.file) {
+ console.log(USAGE);
+ return a.cmd === "help" ? 0 : 2;
+ }
+ const file = resolve(a.file);
+ const outDir = typeof a.out === "string" ? resolve(a.out) : join(dirname(file), "out");
+ try {
+ switch (a.cmd) {
+ case "build": {
+ const p = loadProject(file);
+ const r = writeOutputs(p, outDir, { only: a.only, preview: a.preview, scale: a.scale });
+ for (const l of r.lines) console.log(l);
+ for (const e of r.errors) console.error("error: " + e.message);
+ console.log(`-> ${outDir}${r.errors.length ? ` (${r.errors.length} error${r.errors.length > 1 ? "s" : ""})` : ""}`);
+ return r.errors.length ? 1 : 0;
+ }
+ case "ascii": {
+ const name = a.rest[0];
+ if (!name) throw new PxError("ascii needs an asset name: pxl ascii <file> <name>");
+ const p = loadProject(file);
+ const pal = p.assets.get(name)?.pal ?? p.pal;
+ if (p.assets.get(name)?.kind === "anim")
+ p.frames(name).forEach((f, i) => console.log(`frame ${i} (${f.ms}ms)\n${ascii(f.img, pal)}\n`));
+ else console.log(ascii(p.image(name), pal));
+ return 0;
+ }
+ case "list": {
+ const p = loadProject(file);
+ for (const n of p.order) {
+ const d = p.assets.get(n)!;
+ console.log(`${d.kind.padEnd(6)} ${n.padEnd(24)} ${d.loc ?? ""}`);
+ }
+ for (const g of p.groups.values()) console.log(`${"group".padEnd(6)} ${g.name.padEnd(24)} ${g.loc ?? ""} [${g.members.join(" ")}]`);
+ for (const s of p.sheets) console.log(`${"sheet".padEnd(6)} ${s.name.padEnd(24)} ${s.loc ?? ""}`);
+ return 0;
+ }
+ case "serve": {
+ const s = await serve(file, { port: a.port, out: a.out === false ? false : outDir, preview: a.preview });
+ console.log(`pxl live viewer: ${s.url} (watching ${file}; Ctrl+C to stop)`);
+ return await new Promise<number>(() => {});
+ }
+ default:
+ console.error(`unknown command '${a.cmd}'\n\n${USAGE}`);
+ return 2;
+ }
+ } catch (e) {
+ console.error("error: " + wrap(e).message);
+ return 1;
+ }
+}
diff --git a/src/node/gif.ts b/src/node/gif.ts
new file mode 100644
index 0000000..b315e8f
--- /dev/null
+++ b/src/node/gif.ts
@@ -0,0 +1,203 @@
+// Animated GIF encoder (GIF89a, looping). One global palette for all frames; more than 256
+// colors (lit scenes) are reduced by median cut. Fully transparent pixels become the
+// transparent index. Identical consecutive frames are merged.
+import { TRANSPARENT } from "../core/color.ts";
+import type { Img } from "../core/image.ts";
+
+export interface GifFrame {
+ img: Img;
+ /** Duration in ms (GIF stores centiseconds; minimum 20ms). */
+ ms: number;
+}
+
+export function encodeGif(frames: GifFrame[]): Buffer {
+ if (!frames.length) throw new Error("gif needs at least one frame");
+ const w = Math.max(...frames.map((f) => f.img.w)), h = Math.max(...frames.map((f) => f.img.h));
+ const merged = mergeRepeats(frames);
+
+ // Palette: every opaque color, reduced if needed; index 0 is transparent when any pixel is.
+ const counts = new Map<number, number>();
+ let transparent = false;
+ for (const { img } of merged) {
+ if (img.w < w || img.h < h) transparent = true;
+ for (const c of img.data) {
+ if (isClear(c)) { transparent = true; continue; }
+ const rgb = c >>> 8;
+ counts.set(rgb, (counts.get(rgb) ?? 0) + 1);
+ }
+ }
+ const room = transparent ? 255 : 256;
+ const pal = counts.size <= room ? [...counts.keys()] : medianCut(counts, room);
+ const colors = (transparent ? [0] : []).concat(pal);
+ const base = transparent ? 1 : 0;
+ let bits = 1;
+ while (1 << bits < colors.length) bits++;
+ const exact = new Map<number, number>();
+ pal.forEach((c, i) => exact.set(c, i + base));
+ const indexOf = (rgb: number): number => {
+ let i = exact.get(rgb);
+ if (i === undefined) {
+ i = nearest(pal, rgb) + base;
+ exact.set(rgb, i);
+ }
+ return i;
+ };
+
+ const out: number[] = [];
+ const u16 = (v: number) => out.push(v & 255, (v >> 8) & 255);
+ out.push(...Buffer.from("GIF89a"));
+ u16(w); u16(h);
+ out.push(0x80 | 0x70 | (bits - 1), 0, 0);
+ for (let i = 0; i < 1 << bits; i++) {
+ const c = colors[i] ?? 0;
+ out.push((c >> 16) & 255, (c >> 8) & 255, c & 255);
+ }
+ out.push(0x21, 0xff, 11, ...Buffer.from("NETSCAPE2.0"), 3, 1, 0, 0, 0); // loop forever
+
+ const minSize = Math.max(2, bits);
+ for (const { img, ms } of merged) {
+ const cs = Math.max(2, Math.round(ms / 10));
+ // Restore to background between frames when anything is transparent, so frames don't pile up.
+ out.push(0x21, 0xf9, 4, ((transparent ? 2 : 1) << 2) | (transparent ? 1 : 0));
+ u16(cs);
+ out.push(0, 0);
+ out.push(0x2c);
+ u16(0); u16(0); u16(w); u16(h);
+ out.push(0);
+ const idx = new Uint8Array(w * h);
+ for (let y = 0; y < img.h; y++)
+ for (let x = 0; x < img.w; x++) {
+ const c = img.data[y * img.w + x];
+ idx[y * w + x] = isClear(c) ? 0 : indexOf(c >>> 8);
+ }
+ out.push(minSize);
+ const data = lzw(idx, minSize);
+ for (let i = 0; i < data.length; i += 255) {
+ const n = Math.min(255, data.length - i);
+ out.push(n);
+ for (let j = 0; j < n; j++) out.push(data[i + j]);
+ }
+ out.push(0);
+ }
+ out.push(0x3b);
+ return Buffer.from(out);
+}
+
+function isClear(c: number): boolean {
+ return c === TRANSPARENT || (c & 255) === 0;
+}
+
+function mergeRepeats(frames: GifFrame[]): GifFrame[] {
+ const out: GifFrame[] = [];
+ for (const f of frames) {
+ const prev = out[out.length - 1];
+ if (prev && same(prev.img, f.img)) prev.ms += f.ms;
+ else out.push({ img: f.img, ms: f.ms });
+ }
+ return out;
+}
+
+function same(a: Img, b: Img): boolean {
+ if (a.w !== b.w || a.h !== b.h) return false;
+ for (let i = 0; i < a.data.length; i++) if (a.data[i] !== b.data[i]) return false;
+ return true;
+}
+
+/** LZW with variable code size, clearing the table when it fills (4096 codes). */
+function lzw(index: Uint8Array, minSize: number): number[] {
+ const clear = 1 << minSize, eoi = clear + 1;
+ let size = minSize + 1, next = eoi + 1;
+ let table = new Map<number, number>();
+ const out: number[] = [];
+ let cur = 0, shift = 0;
+ const emit = (code: number) => {
+ cur |= code << shift;
+ shift += size;
+ while (shift >= 8) {
+ out.push(cur & 255);
+ cur >>>= 8;
+ shift -= 8;
+ }
+ };
+ emit(clear);
+ let code = index[0];
+ for (let i = 1; i < index.length; i++) {
+ const k = index[i], key = (code << 8) | k, hit = table.get(key);
+ if (hit !== undefined) {
+ code = hit;
+ continue;
+ }
+ emit(code);
+ if (next === 4096) {
+ emit(clear);
+ table = new Map();
+ size = minSize + 1;
+ next = eoi + 1;
+ } else {
+ if (next >= 1 << size) size++;
+ table.set(key, next++);
+ }
+ code = k;
+ }
+ emit(code);
+ emit(eoi);
+ if (shift > 0) out.push(cur & 255);
+ return out;
+}
+
+/** Median cut over 0xRRGGBB colors weighted by count. */
+function medianCut(counts: Map<number, number>, n: number): number[] {
+ type Box = { cs: number[] };
+ const ch = (c: number, k: number) => (c >> (16 - 8 * k)) & 255;
+ const range = (b: Box) => {
+ let best = 0, axis = 0;
+ for (let k = 0; k < 3; k++) {
+ let lo = 255, hi = 0;
+ for (const c of b.cs) { const v = ch(c, k); if (v < lo) lo = v; if (v > hi) hi = v; }
+ if (hi - lo > best) { best = hi - lo; axis = k; }
+ }
+ return { best, axis };
+ };
+ const boxes: Box[] = [{ cs: [...counts.keys()] }];
+ while (boxes.length < n) {
+ let pick = -1, score = 0, axis = 0;
+ boxes.forEach((b, i) => {
+ if (b.cs.length < 2) return;
+ const r = range(b);
+ let wsum = 0;
+ for (const c of b.cs) wsum += counts.get(c)!;
+ const s = r.best * Math.sqrt(wsum);
+ if (s > score) { score = s; pick = i; axis = r.axis; }
+ });
+ if (pick < 0) break;
+ const b = boxes[pick];
+ b.cs.sort((p, q) => ch(p, axis) - ch(q, axis));
+ let total = 0;
+ for (const c of b.cs) total += counts.get(c)!;
+ let acc = 0, cut = 1;
+ for (let i = 0; i < b.cs.length - 1; i++) {
+ acc += counts.get(b.cs[i])!;
+ if (acc >= total / 2) { cut = i + 1; break; }
+ }
+ boxes.splice(pick, 1, { cs: b.cs.slice(0, cut) }, { cs: b.cs.slice(cut) });
+ }
+ return boxes.map((b) => {
+ let r = 0, g = 0, bl = 0, wsum = 0;
+ for (const c of b.cs) {
+ const wt = counts.get(c)!;
+ r += ch(c, 0) * wt; g += ch(c, 1) * wt; bl += ch(c, 2) * wt; wsum += wt;
+ }
+ return (Math.round(r / wsum) << 16) | (Math.round(g / wsum) << 8) | Math.round(bl / wsum);
+ });
+}
+
+function nearest(pal: number[], rgb: number): number {
+ const r = (rgb >> 16) & 255, g = (rgb >> 8) & 255, b = rgb & 255;
+ let best = 0, bd = Infinity;
+ for (let i = 0; i < pal.length; i++) {
+ const c = pal[i], dr = ((c >> 16) & 255) - r, dg = ((c >> 8) & 255) - g, db = (c & 255) - b;
+ const d = 2 * dr * dr + 4 * dg * dg + 3 * db * db;
+ if (d < bd) { bd = d; best = i; }
+ }
+ return best;
+}
diff --git a/src/node/load.ts b/src/node/load.ts
new file mode 100644
index 0000000..c259a82
--- /dev/null
+++ b/src/node/load.ts
@@ -0,0 +1,68 @@
+// Loads art files (.js or .ts) into a Project by running them in a vm sandbox whose globals
+// are the DSL. Each load gets a fresh context, so reloading after an edit is clean.
+import { readFileSync } from "node:fs";
+import { dirname, isAbsolute, resolve } from "node:path";
+import * as vm from "node:vm";
+import { stripTypeScriptTypes } from "node:module";
+import { PxError, wrap } from "../core/errors.ts";
+import { Project, type ProjectOptions } from "../core/project.ts";
+
+function compile(code: string, file: string): string {
+ // Type stripping keeps every line and column in place, so error locations stay exact.
+ return /\.[cm]?ts$/.test(file) ? stripTypeScriptTypes(code, { mode: "strip" }) : code;
+}
+
+/** Load an art file from disk. Throws PxError with a file:line:col location on failure. */
+export function loadProject(file: string, opts: ProjectOptions = {}): Project {
+ const p = new Project(opts);
+ const ctx = vm.createContext({ ...p.env(), console });
+ const stack: string[] = [];
+ const run = (path: string) => {
+ const abs = resolve(path);
+ if (stack.includes(abs)) throw new PxError(`include cycle: ${[...stack, abs].join(" -> ")}`);
+ let code: string;
+ try { code = readFileSync(abs, "utf8"); } catch {
+ throw new PxError(`cannot read art file '${abs}'`, p.callerLoc());
+ }
+ p.addFile(abs);
+ stack.push(abs);
+ try {
+ vm.runInContext(compile(code, abs), ctx, { filename: abs });
+ } catch (e) {
+ throw syntaxAware(e, abs, p);
+ } finally {
+ stack.pop();
+ }
+ };
+ p.includeHook = (path) => run(isAbsolute(path) ? path : resolve(dirname(stack[stack.length - 1]), path));
+ run(file);
+ return p;
+}
+
+/** Load art source from a string (tests, embedding). `name` appears in error locations. */
+export function loadSource(src: string, name = "art.px.js", opts: ProjectOptions = {}): Project {
+ const p = new Project(opts);
+ const ctx = vm.createContext({ ...p.env(), console });
+ p.addFile(name);
+ try {
+ vm.runInContext(compile(src, name), ctx, { filename: name });
+ } catch (e) {
+ throw syntaxAware(e, name, p);
+ }
+ return p;
+}
+
+function syntaxAware(e: unknown, file: string, p: Project): PxError {
+ const err = wrap(e, (s) => p.locFromStack(s));
+ // SyntaxErrors put the location in the first stack line ("file:line").
+ if (!err.loc && typeof e === "object" && e && "stack" in e) {
+ const m = new RegExp(escape(file) + ":(\\d+)").exec(String((e as Error).stack));
+ if (m) err.loc = `${file.replace(/^.*[\\/]/, "")}:${m[1]}`;
+ err.message = err.format();
+ }
+ return err;
+}
+
+function escape(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
diff --git a/src/node/output.ts b/src/node/output.ts
new file mode 100644
index 0000000..2bf4a29
--- /dev/null
+++ b/src/node/output.ts
@@ -0,0 +1,110 @@
+// Writes build results to disk: PNGs, layer PNGs, sheets + JSON, previews.
+import { mkdirSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { PxError, didYouMean, wrap } from "../core/errors.ts";
+import type { Img } from "../core/image.ts";
+import type { Project } from "../core/project.ts";
+import { type FrameTag, packSheet, preview, previewScale, sheetJson } from "../core/render.ts";
+import { normalImage } from "../core/normals.ts";
+import { encodeGif } from "./gif.ts";
+import { encodePng } from "./png.ts";
+
+export interface OutputOptions {
+ /** Only these assets/sheets (default: everything exported). */
+ only?: string[];
+ /** Write upscaled previews to out/_preview (default true). */
+ preview?: boolean;
+ /** Fixed preview scale (default: auto). */
+ scale?: number;
+}
+
+export interface OutputResult {
+ lines: string[];
+ errors: PxError[];
+}
+
+function write(path: string, data: string | Buffer): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, data);
+}
+
+export function writePng(path: string, img: Img): void {
+ write(path, encodePng(img));
+}
+
+/** Build and write. Each asset fails independently; errors are collected, not thrown. */
+export function writeOutputs(p: Project, out: string, opts: OutputOptions = {}): OutputResult {
+ const lines: string[] = [], errors: PxError[] = [];
+ const sheetNames = new Set(p.sheets.map((s) => s.name));
+ if (opts.only)
+ for (const n of opts.only)
+ if (!p.assets.has(n) && !sheetNames.has(n))
+ errors.push(new PxError(`unknown asset or sheet '${n}'${didYouMean(n, [...p.order, ...sheetNames])}`));
+
+ const want = opts.only ? new Set(opts.only) : undefined;
+ const prev = (name: string, img: Img): string => {
+ if (opts.preview === false) return "";
+ const s = opts.scale ?? previewScale(img);
+ writePng(join(out, "_preview", name + ".png"), preview(img, s));
+ return ` @${s}x`;
+ };
+
+ const names = want ? p.order.filter((n) => want.has(n)) : p.exported();
+ for (const n of names) {
+ const def = p.assets.get(n)!;
+ try {
+ const b = p.build(n);
+ const dir = def.kind === "scene" ? "scenes" : def.kind === "anim" ? "anims" : "sprites";
+ const frames = b.anim ? p.frames(n) : [];
+ let shown = b.img, info = "";
+ if (def.kind === "anim") {
+ // Anims: a horizontal strip of frames + Aseprite-style JSON, plus a GIF.
+ const { sheet, frames: fr } = packSheet(frames.map((f, i) => ({ name: `${n}_${i}`, img: f.img, ms: f.ms })), frames.length);
+ writePng(join(out, dir, n + ".png"), sheet);
+ write(join(out, dir, n + ".json"), sheetJson(n + ".png", sheet, fr, [{ name: n, from: 0, to: fr.length - 1 }]));
+ shown = packSheet(frames.map((f) => ({ name: "", img: f.img })), frames.length, 1).sheet;
+ } else {
+ writePng(join(out, dir, n + ".png"), b.img);
+ if (b.img.norm) writePng(join(out, dir, n + "_n.png"), normalImage(b.img)); // for engine lights
+ }
+ if (frames.length) {
+ write(join(out, dir, n + ".gif"), encodeGif(frames));
+ info = ` (${frames.length} frames, ${b.anim!.loop}ms)`;
+ }
+ if (def.opts.layers) for (const l of b.layers) writePng(join(out, dir, n, l.name + ".png"), l.img);
+ let pv = "";
+ if (opts.preview !== false) {
+ // Previews: anims show every frame side by side; anything animated also gets a GIF.
+ const s = opts.scale ?? Math.max(1, Math.min(previewScale(b.img), Math.floor(2048 / shown.w)));
+ writePng(join(out, "_preview", n + ".png"), preview(shown, s));
+ if (frames.length) write(join(out, "_preview", n + ".gif"), encodeGif(frames.map((f) => ({ img: preview(f.img, s), ms: f.ms }))));
+ pv = ` @${s}x`;
+ }
+ lines.push(`${def.kind} ${n} ${b.img.w}x${b.img.h}${info}${pv}`);
+ } catch (e) {
+ errors.push(wrap(e));
+ }
+ }
+
+ for (const s of p.sheets) {
+ if (want && !want.has(s.name)) continue;
+ try {
+ // Animated entries expand to one frame each (name_0, name_1, ...) with durations and a tag.
+ const items: { name: string; img: Img; ms?: number }[] = [], tags: FrameTag[] = [];
+ for (const name of p.sheetNames(s)) {
+ const fr = p.frames(name);
+ if (!fr.length) { items.push({ name, img: p.image(name) }); continue; }
+ tags.push({ name, from: items.length, to: items.length + fr.length - 1 });
+ fr.forEach((f, i) => items.push({ name: `${name}_${i}`, img: f.img, ms: f.ms }));
+ }
+ if (!items.length) throw new PxError("sheet is empty (no entries matched)");
+ const { sheet, frames } = packSheet(items, s.opts.cols, s.opts.pad);
+ writePng(join(out, s.name + ".png"), sheet);
+ write(join(out, s.name + ".json"), sheetJson(s.name + ".png", sheet, frames, tags));
+ lines.push(`sheet ${s.name} ${sheet.w}x${sheet.h} (${frames.length} frames)${prev(s.name, sheet)}`);
+ } catch (e) {
+ errors.push(wrap(e).within(`sheet '${s.name}'`, s.loc));
+ }
+ }
+ return { lines, errors };
+}
diff --git a/src/node/png.ts b/src/node/png.ts
new file mode 100644
index 0000000..93e4a47
--- /dev/null
+++ b/src/node/png.ts
@@ -0,0 +1,52 @@
+import { crc32, deflateSync } from "node:zlib";
+import { TRANSPARENT } from "../core/color.ts";
+import type { Img } from "../core/image.ts";
+
+function chunk(type: string, data: Buffer): Buffer {
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(data.length, 0);
+ head.write(type, 4, "ascii");
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
+ return Buffer.concat([head, data, crc]);
+}
+
+/** PNG bytes: indexed (with tRNS) when the image has <= 256 colors, RGBA otherwise. */
+export function encodePng(img: Img): Buffer {
+ const { w, h, data } = img;
+ const index = new Map<number, number>();
+ for (let i = 0; i < data.length && index.size <= 256; i++) if (!index.has(data[i])) index.set(data[i], index.size);
+ const indexed = index.size <= 256;
+
+ const rowLen = indexed ? w + 1 : w * 4 + 1;
+ const raw = Buffer.alloc(rowLen * h);
+ for (let y = 0; y < h; y++) {
+ let o = y * rowLen + 1; // filter byte 0
+ for (let x = 0; x < w; x++) {
+ const c = data[y * w + x];
+ if (indexed) raw[o++] = index.get(c)!;
+ else { raw[o++] = c >>> 24; raw[o++] = (c >>> 16) & 255; raw[o++] = (c >>> 8) & 255; raw[o++] = c & 255; }
+ }
+ }
+
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(w, 0);
+ ihdr.writeUInt32BE(h, 4);
+ ihdr[8] = 8;
+ ihdr[9] = indexed ? 3 : 6;
+ const parts = [Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr)];
+ if (indexed) {
+ const colors = [...index.keys()];
+ const plte = Buffer.alloc(colors.length * 3), trns = Buffer.alloc(colors.length);
+ let lastAlpha = -1;
+ colors.forEach((c, i) => {
+ plte[i * 3] = c >>> 24; plte[i * 3 + 1] = (c >>> 16) & 255; plte[i * 3 + 2] = (c >>> 8) & 255;
+ trns[i] = c === TRANSPARENT ? 0 : c & 255;
+ if (trns[i] !== 255) lastAlpha = i;
+ });
+ parts.push(chunk("PLTE", plte));
+ if (lastAlpha >= 0) parts.push(chunk("tRNS", trns.subarray(0, lastAlpha + 1)));
+ }
+ parts.push(chunk("IDAT", deflateSync(raw, { level: 9 })), chunk("IEND", Buffer.alloc(0)));
+ return Buffer.concat(parts);
+}
diff --git a/src/node/server.ts b/src/node/server.ts
new file mode 100644
index 0000000..8d7d2a8
--- /dev/null
+++ b/src/node/server.ts
@@ -0,0 +1,222 @@
+// Live viewer server: watch art files, rebuild with traces, push updates over SSE.
+import { readFileSync, unwatchFile, watchFile } from "node:fs";
+import { createServer, type ServerResponse } from "node:http";
+import { stripTypeScriptTypes } from "node:module";
+import { basename, dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { type PxError, wrap } from "../core/errors.ts";
+import type { BuildOut } from "../core/build.ts";
+import type { AssetDef } from "../core/model.ts";
+import type { Project } from "../core/project.ts";
+import { loadProject } from "./load.ts";
+import { writeOutputs } from "./output.ts";
+
+export interface ServeOptions {
+ port?: number;
+ /** Also write outputs (PNGs, previews) on every build; default `<file dir>/out`. false = off. */
+ out?: string | false;
+ preview?: boolean;
+ log?: (line: string) => void;
+}
+
+interface AssetInfo {
+ name: string;
+ kind: string;
+ part: boolean;
+ w?: number;
+ h?: number;
+ hash?: string;
+ steps?: number;
+ /** Image differs from the previous build. */
+ changed: boolean;
+ /** Its own definition text changed (not just something it uses). */
+ edited: boolean;
+ error?: ErrInfo;
+}
+
+interface ErrInfo {
+ message: string;
+ loc?: string;
+}
+
+interface State {
+ version: number;
+ file: string;
+ time: string;
+ ms: number;
+ error?: ErrInfo;
+ assets: AssetInfo[];
+ sheets: string[];
+ errors: ErrInfo[];
+}
+
+const here = dirname(fileURLToPath(import.meta.url));
+const viewerDir = join(here, "..", "viewer");
+
+function errInfo(e: PxError): ErrInfo {
+ return { message: e.message, loc: e.loc };
+}
+
+/** Text fingerprint of an asset's own definition (items, options, palette), ignoring locations. */
+function fingerprint(def: AssetDef): string {
+ return JSON.stringify([def.opts, def.items, def.pal.table(), def.pal.ramps], (k, v) =>
+ k === "loc" ? undefined : typeof v === "function" ? String(v) : v);
+}
+
+function b64(a: Uint32Array): string {
+ return Buffer.from(a.buffer, a.byteOffset, a.byteLength).toString("base64");
+}
+
+export function serve(file: string, opts: ServeOptions = {}): Promise<{ url: string; close: () => void }> {
+ const abs = resolve(file);
+ const out = opts.out === false ? undefined : opts.out ?? join(dirname(abs), "out");
+ const log = opts.log ?? ((l: string) => console.log(l));
+ const clients = new Set<ServerResponse>();
+ let project: Project | undefined;
+ let state: State = { version: 0, file: basename(abs), time: "", ms: 0, assets: [], sheets: [], errors: [] };
+ const hashes = new Map<string, string>();
+ const fps = new Map<string, string>();
+ let watched = new Set<string>();
+ let timer: NodeJS.Timeout | undefined;
+
+ const broadcast = () => {
+ const msg = `event: build\ndata: ${JSON.stringify(state)}\n\n`;
+ for (const c of clients) c.write(msg);
+ };
+
+ const rebuild = () => {
+ const t0 = performance.now();
+ const next: State = { version: state.version + 1, file: basename(abs), time: new Date().toLocaleTimeString(), ms: 0, assets: [], sheets: [], errors: [] };
+ try {
+ project = loadProject(abs, { trace: true });
+ } catch (e) {
+ project = undefined;
+ next.error = errInfo(wrap(e));
+ }
+ if (project) {
+ for (const name of project.order) {
+ const def = project.assets.get(name)!;
+ const fp = fingerprint(def);
+ const info: AssetInfo = { name, kind: def.kind, part: name.startsWith("_"), changed: false, edited: fps.size > 0 && fps.get(name) !== fp };
+ fps.set(name, fp);
+ try {
+ const b = project.build(name);
+ info.w = b.img.w;
+ info.h = b.img.h;
+ // Animated assets: every frame counts, so an edit to frame 3 still refreshes the viewer.
+ info.hash = b.anim ? project.frames(name).map((f) => f.img.hash() + f.ms).join("|") : b.img.hash();
+ info.steps = b.trace?.frames.length ?? 0;
+ info.changed = hashes.get(name) !== info.hash;
+ hashes.set(name, info.hash);
+ } catch (e) {
+ info.error = errInfo(wrap(e));
+ info.changed = true;
+ hashes.delete(name);
+ }
+ next.assets.push(info);
+ }
+ next.sheets = project.sheets.map((s) => s.name);
+ if (out) {
+ const r = writeOutputs(project, out, { preview: opts.preview });
+ // asset failures are already listed per asset; keep the rest (sheets, unknown names)
+ next.errors = r.errors.filter((e) => !next.assets.some((a) => a.error?.message === e.message)).map(errInfo);
+ }
+ watch(project.files);
+ } else watch([abs]);
+ next.ms = Math.round(performance.now() - t0);
+ state = next;
+ const bad = next.error ? 1 : next.assets.filter((a) => a.error).length + next.errors.length;
+ const changed = next.assets.filter((a) => a.changed && !a.error).map((a) => a.name);
+ log(`[pxl] v${next.version} ${next.ms}ms: ${next.assets.length} assets, ${bad} error(s)` +
+ (changed.length && state.version > 1 ? `, changed: ${changed.slice(0, 8).join(" ")}${changed.length > 8 ? " …" : ""}` : "") +
+ (next.error ? `\n ${next.error.message}` : ""));
+ broadcast();
+ };
+
+ const schedule = () => {
+ clearTimeout(timer);
+ timer = setTimeout(rebuild, 60);
+ };
+
+ // Polling watch: survives editors that replace files on save.
+ function watch(files: string[]) {
+ const nextSet = new Set(files.filter((f) => !f.startsWith("<")));
+ for (const f of watched) if (!nextSet.has(f)) unwatchFile(f);
+ for (const f of nextSet) if (!watched.has(f)) watchFile(f, { interval: 150 }, (a, b) => { if (a.mtimeMs !== b.mtimeMs) schedule(); });
+ watched = nextSet;
+ }
+
+ const assetPayload = (name: string, withFrames: boolean) => {
+ if (!project) return undefined;
+ const def = project.assets.get(name);
+ if (!def) return undefined;
+ let b: BuildOut;
+ try { b = project.build(name); } catch { return undefined; }
+ return {
+ name, kind: def.kind, w: b.img.w, h: b.img.h, loc: def.loc,
+ palette: def.pal.table(),
+ layers: b.layers.map((l) => l.name),
+ image: b64(b.img.data),
+ anim: b.anim ? project.frames(name, 0, 240).map((f) => ({ ms: f.ms, image: b64(f.img.data) })) : undefined,
+ frames: (withFrames ? b.trace?.frames ?? [] : []).map((f) => ({
+ label: f.label, loc: f.loc, w: f.w, h: f.h,
+ full: f.full ? b64(f.full) : undefined,
+ changes: f.changes ? b64(f.changes) : undefined,
+ })),
+ };
+ };
+
+ const server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://x");
+ try {
+ if (url.pathname === "/") {
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+ res.end(readFileSync(join(viewerDir, "index.html")));
+ } else if (url.pathname === "/app.js") {
+ const src = readFileSync(join(viewerDir, "app.ts"), "utf8");
+ res.writeHead(200, { "content-type": "text/javascript; charset=utf-8" });
+ res.end(stripTypeScriptTypes(src, { mode: "strip" }));
+ } else if (url.pathname === "/events") {
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
+ res.write(`event: build\ndata: ${JSON.stringify(state)}\n\n`);
+ clients.add(res);
+ req.on("close", () => clients.delete(res));
+ } else if (url.pathname === "/api/state") {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(state));
+ } else if (url.pathname === "/api/asset") {
+ const p = assetPayload(url.searchParams.get("name") ?? "", url.searchParams.get("frames") !== "0");
+ res.writeHead(p ? 200 : 404, { "content-type": "application/json" });
+ res.end(JSON.stringify(p ?? { error: "not found" }));
+ } else {
+ res.writeHead(404);
+ res.end("not found");
+ }
+ } catch (e) {
+ res.writeHead(500);
+ res.end(String(e));
+ }
+ });
+
+ const ping = setInterval(() => { for (const c of clients) c.write(": ping\n\n"); }, 15000);
+
+ return new Promise((ok, fail) => {
+ server.on("error", fail);
+ server.listen(opts.port ?? 4321, "127.0.0.1", () => {
+ const addr = server.address();
+ const port = typeof addr === "object" && addr ? addr.port : opts.port;
+ const url = `http://127.0.0.1:${port}/`;
+ rebuild();
+ ok({
+ url,
+ close: () => {
+ clearInterval(ping);
+ clearTimeout(timer);
+ for (const f of watched) unwatchFile(f);
+ for (const c of clients) c.end();
+ server.close();
+ },
+ });
+ });
+ });
+}
diff --git a/src/viewer/app.ts b/src/viewer/app.ts
new file mode 100644
index 0000000..bc7995d
--- /dev/null
+++ b/src/viewer/app.ts
@@ -0,0 +1,441 @@
+// pxl live viewer. Served type-stripped as /app.js; no imports, no build step.
+
+interface ErrInfo { message: string; loc?: string }
+interface AssetInfo { name: string; kind: string; part: boolean; w?: number; h?: number; hash?: string; steps?: number; changed: boolean; edited: boolean; error?: ErrInfo }
+interface State { version: number; file: string; time: string; ms: number; error?: ErrInfo; assets: AssetInfo[]; sheets: string[]; errors: ErrInfo[] }
+interface FrameJ { label: string; loc?: string; w: number; h: number; full?: string; changes?: string }
+interface AssetJ { name: string; kind: string; w: number; h: number; loc?: string; palette: Record<string, string>; layers: string[]; image: string; frames: FrameJ[]; anim?: { ms: number; image: string }[] }
+interface Frame { label: string; loc?: string; w: number; h: number; full?: Uint32Array; changes?: Uint32Array }
+interface Pic { w: number; h: number; data: Uint32Array }
+interface Loaded { j: AssetJ; hash?: string; frames: Frame[]; final: Pic; marks: Map<number, Pic>; rev: Map<number, string>; anim: { ms: number; pic: Pic }[] }
+
+const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
+const view = $<HTMLCanvasElement>("view");
+const g = view.getContext("2d")!;
+const slider = $<HTMLInputElement>("slider");
+
+let state: State | undefined;
+let sel: string | undefined;
+let cur: Loaded | undefined;
+let step = 0;
+let playing = false;
+let zoom = 0; // 0 = fit
+let pan = { x: 0, y: 0 };
+let hover: { x: number; y: number } | undefined;
+const thumbs = new Map<string, string>(); // name -> hash rendered
+
+// ---------------------------------------------------------------- decoding
+
+function u32(b64: string): Uint32Array {
+ const bin = atob(b64);
+ const u8 = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);
+ return new Uint32Array(u8.buffer);
+}
+
+function toImageData(p: Pic): ImageData {
+ const id = new ImageData(p.w, p.h);
+ const d = id.data;
+ for (let i = 0; i < p.data.length; i++) {
+ const c = p.data[i];
+ d[i * 4] = c >>> 24; d[i * 4 + 1] = (c >>> 16) & 255; d[i * 4 + 2] = (c >>> 8) & 255; d[i * 4 + 3] = c & 255;
+ }
+ return id;
+}
+
+function hex(c: number): string {
+ return "#" + (c >>> 8).toString(16).padStart(6, "0") + ((c & 255) === 255 ? "" : (c & 255).toString(16).padStart(2, "0"));
+}
+
+/** Image after step n, rebuilt from the nearest checkpoint. */
+function picAt(a: Loaded, n: number): Pic {
+ if (!a.frames.length) return a.final;
+ n = Math.max(0, Math.min(n, a.frames.length - 1));
+ let k = n;
+ while (k > 0 && !a.marks.has(k)) k--;
+ let pic = a.marks.get(k);
+ if (!pic) {
+ const f = a.frames[0];
+ pic = { w: f.w, h: f.h, data: f.full ? f.full.slice() : new Uint32Array(f.w * f.h) };
+ a.marks.set(0, { ...pic, data: pic.data.slice() });
+ } else pic = { ...pic, data: pic.data.slice() };
+ for (let i = k + 1; i <= n; i++) {
+ const f = a.frames[i];
+ if (f.full) pic = { w: f.w, h: f.h, data: f.full.slice() };
+ else if (f.changes) for (let j = 0; j < f.changes.length; j += 2) pic.data[f.changes[j]] = f.changes[j + 1];
+ if (i % 32 === 0 && !a.marks.has(i)) a.marks.set(i, { ...pic, data: pic.data.slice() });
+ }
+ return pic;
+}
+
+// ---------------------------------------------------------------- loading
+
+async function fetchAsset(name: string, frames: boolean): Promise<AssetJ | undefined> {
+ const r = await fetch(`/api/asset?name=${encodeURIComponent(name)}&frames=${frames ? 1 : 0}`);
+ return r.ok ? (r.json() as Promise<AssetJ>) : undefined;
+}
+
+async function select(name: string, opts: { play?: boolean; keepStep?: boolean } = {}): Promise<void> {
+ const info = state?.assets.find((a) => a.name === name);
+ sel = name;
+ localStorage.setItem("pxl.sel", name);
+ renderList();
+ if (!info || info.error) {
+ cur = undefined;
+ renderSteps();
+ draw();
+ return;
+ }
+ const j = await fetchAsset(name, true);
+ if (!j || sel !== name) return;
+ const frames: Frame[] = j.frames.map((f) => ({ label: f.label, loc: f.loc, w: f.w, h: f.h, full: f.full ? u32(f.full) : undefined, changes: f.changes ? u32(f.changes) : undefined }));
+ const rev = new Map<number, string>();
+ for (const [k, v] of Object.entries(j.palette)) {
+ const c = parseInt(v.slice(1).padEnd(8, "f"), 16) >>> 0;
+ if (!rev.has(c) || /[A-Za-z]/.test(k)) rev.set(c, k);
+ }
+ const prevStep = step, prevLen = cur?.frames.length ?? 0;
+ const anim = (j.anim ?? []).map((f) => ({ ms: f.ms, pic: { w: j.w, h: j.h, data: u32(f.image) } }));
+ cur = { j, hash: info.hash, frames, final: { w: j.w, h: j.h, data: u32(j.image) }, marks: new Map(), rev, anim };
+ animAt = 0;
+ slider.max = String(Math.max(0, frames.length - 1));
+ step = opts.play ? 0 : opts.keepStep && prevStep < prevLen - 1 ? Math.min(prevStep, frames.length - 1) : frames.length - 1;
+ renderSteps();
+ renderPalette();
+ setStep(step);
+ if (opts.play) play(true);
+}
+
+// ---------------------------------------------------------------- list
+
+function renderList(): void {
+ const box = $("assets");
+ const q = ($<HTMLInputElement>("filter")).value.trim().toLowerCase();
+ box.innerHTML = "";
+ if (!state) return;
+ const groups: [string, AssetInfo[]][] = [
+ ["scenes", state.assets.filter((a) => a.kind === "scene")],
+ ["anims", state.assets.filter((a) => a.kind === "anim" && !a.part)],
+ ["sprites", state.assets.filter((a) => a.kind === "sprite" && !a.part)],
+ ["parts", state.assets.filter((a) => a.part)],
+ ];
+ for (const [title, list] of groups) {
+ const shown = list.filter((a) => !q || a.name.toLowerCase().includes(q));
+ if (!shown.length) continue;
+ const h = document.createElement("div");
+ h.className = "sect";
+ h.textContent = `${title} · ${shown.length}`;
+ box.append(h);
+ for (const a of shown) {
+ const row = document.createElement("div");
+ row.className = "row" + (a.name === sel ? " sel" : "");
+ const cv = document.createElement("canvas");
+ cv.width = 32; cv.height = 32;
+ cv.dataset.name = a.name;
+ const meta = document.createElement("div");
+ meta.innerHTML = `<div class="nm"></div><div class="sz">${a.error ? "error" : `${a.w}×${a.h} · ${a.steps} steps`}</div>`;
+ (meta.firstChild as HTMLElement).textContent = a.name;
+ row.append(cv, meta);
+ if (a.error || (a.changed && state.version > 1)) {
+ const dot = document.createElement("span");
+ dot.className = "dot " + (a.error ? "err" : "new");
+ row.append(dot);
+ }
+ row.onclick = () => select(a.name);
+ box.append(row);
+ paintThumb(cv, a);
+ }
+ }
+}
+
+const thumbCache = new Map<string, Pic>();
+async function paintThumb(cv: HTMLCanvasElement, a: AssetInfo): Promise<void> {
+ if (a.error || !a.hash) return;
+ let pic = thumbs.get(a.name) === a.hash ? thumbCache.get(a.name) : undefined;
+ if (!pic) {
+ const j = await fetchAsset(a.name, false);
+ if (!j) return;
+ pic = { w: j.w, h: j.h, data: u32(j.image) };
+ thumbs.set(a.name, a.hash);
+ thumbCache.set(a.name, pic);
+ }
+ const off = new OffscreenCanvas(pic.w, pic.h);
+ off.getContext("2d")!.putImageData(toImageData(pic), 0, 0);
+ const c = cv.getContext("2d")!;
+ c.imageSmoothingEnabled = false;
+ const s = Math.min(32 / pic.w, 32 / pic.h);
+ const w = pic.w * s, h = pic.h * s;
+ c.clearRect(0, 0, 32, 32);
+ c.drawImage(off, (32 - w) / 2, (32 - h) / 2, w, h);
+}
+
+// ---------------------------------------------------------------- steps panel
+
+function renderSteps(): void {
+ const ol = $("steps");
+ ol.innerHTML = "";
+ if (!cur) return;
+ const frag = document.createDocumentFragment();
+ cur.frames.forEach((f, i) => {
+ const li = document.createElement("li");
+ const none = f.changes && f.changes.length === 0;
+ li.className = none ? "none" : "";
+ li.title = (f.loc ? f.loc + "\n" : "") + f.label + (none ? "\n(no visible change)" : "");
+ li.innerHTML = `<span class="i">${i}</span><span class="l"></span>`;
+ (li.lastChild as HTMLElement).textContent = f.label;
+ li.onclick = () => { play(false); setStep(i); };
+ frag.append(li);
+ });
+ ol.append(frag);
+}
+
+function renderPalette(): void {
+ const box = $("pal");
+ box.innerHTML = "";
+ if (!cur) return;
+ for (const [k, v] of Object.entries(cur.j.palette)) {
+ const s = document.createElement("span");
+ s.style.background = v;
+ s.textContent = k;
+ s.title = `${k} ${v}`;
+ box.append(s);
+ }
+}
+
+function setStep(n: number): void {
+ if (!cur) return draw();
+ step = Math.max(0, Math.min(n, Math.max(0, cur.frames.length - 1)));
+ slider.value = String(step);
+ const ol = $("steps");
+ ol.querySelector(".cur")?.classList.remove("cur");
+ const li = ol.children[step] as HTMLElement | undefined;
+ if (li) { li.classList.add("cur"); li.scrollIntoView({ block: "nearest" }); }
+ const f = cur.frames[step];
+ const info = $("stepinfo");
+ info.innerHTML = f
+ ? `step <b>${step}</b>/${cur.frames.length - 1} · <b></b> <span style="opacity:.7"></span>`
+ : `${cur.j.name} (no steps)`;
+ if (f) {
+ (info.children[1] as HTMLElement).textContent = f.label;
+ (info.children[2] as HTMLElement).textContent = f.loc ? `@ ${f.loc}` : "";
+ }
+ draw();
+}
+
+// ---------------------------------------------------------------- drawing
+
+function draw(): void {
+ const dpr = window.devicePixelRatio || 1;
+ const W = Math.floor(view.clientWidth * dpr), H = Math.floor(view.clientHeight * dpr);
+ if (view.width !== W || view.height !== H) { view.width = W; view.height = H; }
+ g.setTransform(1, 0, 0, 1, 0, 0);
+ g.clearRect(0, 0, W, H);
+ showError();
+ if (!cur) { $("hud").textContent = ""; return; }
+
+ const pic = animating() ? cur.anim[animAt].pic : picAt(cur, step);
+ const fit = Math.max(1, Math.min(48, Math.floor(Math.min((W - 40) / pic.w, (H - 40) / pic.h))));
+ const z = zoom || fit;
+ const ox = Math.floor((W - pic.w * z) / 2 + pan.x * dpr), oy = Math.floor((H - pic.h * z) / 2 + pan.y * dpr);
+
+ // checkerboard, one check per pixel
+ for (let y = 0; y < pic.h; y++)
+ for (let x = 0; x < pic.w; x++) {
+ g.fillStyle = (x + y) % 2 ? "#2a2735" : "#33303f";
+ g.fillRect(ox + x * z, oy + y * z, z, z);
+ }
+ const off = new OffscreenCanvas(pic.w, pic.h);
+ off.getContext("2d")!.putImageData(toImageData(pic), 0, 0);
+ g.imageSmoothingEnabled = false;
+ g.drawImage(off, ox, oy, pic.w * z, pic.h * z);
+
+ if (($<HTMLInputElement>("gridtog")).checked && z >= 6) {
+ g.beginPath();
+ for (let x = 0; x <= pic.w; x++) if (x % 8) { g.moveTo(ox + x * z + 0.5, oy); g.lineTo(ox + x * z + 0.5, oy + pic.h * z); }
+ for (let y = 0; y <= pic.h; y++) if (y % 8) { g.moveTo(ox, oy + y * z + 0.5); g.lineTo(ox + pic.w * z, oy + y * z + 0.5); }
+ g.strokeStyle = "rgba(0,0,0,.22)"; g.lineWidth = 1; g.stroke();
+ g.beginPath();
+ for (let x = 0; x <= pic.w; x += 8) { g.moveTo(ox + x * z + 0.5, oy); g.lineTo(ox + x * z + 0.5, oy + pic.h * z); }
+ for (let y = 0; y <= pic.h; y += 8) { g.moveTo(ox, oy + y * z + 0.5); g.lineTo(ox + pic.w * z, oy + y * z + 0.5); }
+ g.strokeStyle = "rgba(0,0,0,.5)"; g.stroke();
+ }
+
+ // highlight what the current step changed: tint + bounding box
+ const f = cur.frames[step];
+ if (($<HTMLInputElement>("hl")).checked && f?.changes && f.changes.length && step < cur.frames.length - 1 + (playing ? 1 : 0)) {
+ let x0 = Infinity, y0 = Infinity, x1 = -1, y1 = -1;
+ g.fillStyle = "rgba(255,180,84,.42)";
+ for (let j = 0; j < f.changes.length; j += 2) {
+ const i = f.changes[j], x = i % f.w, y = Math.floor(i / f.w);
+ g.fillRect(ox + x * z, oy + y * z, z, z);
+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
+ }
+ g.strokeStyle = "#ffb454"; g.lineWidth = Math.max(1, dpr);
+ g.strokeRect(ox + x0 * z - 1.5, oy + y0 * z - 1.5, (x1 - x0 + 1) * z + 3, (y1 - y0 + 1) * z + 3);
+ }
+
+ $("hud").textContent = `${cur.j.kind} ${cur.j.name} · ${pic.w}×${pic.h} · ${z}×${zoom ? "" : " (fit)"}` +
+ (cur.anim.length ? ` · frame ${animating() ? animAt : 0}/${cur.anim.length - 1}` : "");
+ inspect(pic, ox, oy, z, dpr);
+}
+
+function inspect(pic: Pic, ox: number, oy: number, z: number, dpr: number): void {
+ const box = $("inspect");
+ if (!hover) { box.textContent = "hover the image"; return; }
+ const x = Math.floor((hover.x * dpr - ox) / z), y = Math.floor((hover.y * dpr - oy) / z);
+ if (x < 0 || y < 0 || x >= pic.w || y >= pic.h) { box.textContent = "hover the image"; return; }
+ const c = pic.data[y * pic.w + x];
+ const key = c === 0 ? "." : cur?.rev.get(c) ?? "?";
+ box.innerHTML = `<span class="sw"></span><span>x <b>${x}</b> y <b>${y}</b><br>${c === 0 ? "transparent" : hex(c)} · key <b></b></span>`;
+ (box.firstChild as HTMLElement).style.background = c === 0 ? "transparent" : hex(c);
+ (box.querySelector("b:last-child") as HTMLElement).textContent = key;
+}
+
+function showError(): void {
+ const el = $("err");
+ const info = state?.assets.find((a) => a.name === sel);
+ const err = state?.error ?? info?.error ?? (state?.errors.length ? state.errors[0] : undefined);
+ el.style.display = err ? "block" : "none";
+ if (err) el.textContent = err.message;
+}
+
+// ---------------------------------------------------------------- playback
+
+let last = 0, acc = 0;
+function play(on: boolean): void {
+ playing = on;
+ $("play").textContent = on ? "⏸" : "▶";
+ if (on && cur && step >= cur.frames.length - 1) setStep(0);
+ last = performance.now();
+ acc = 0;
+ if (on) requestAnimationFrame(tick);
+}
+
+function tick(t: number): void {
+ if (!playing || !cur) return;
+ const sp = ($<HTMLSelectElement>("speed")).value;
+ const n = cur.frames.length;
+ const rate = sp === "auto" ? Math.max(8, n / 3) : Number(sp); // auto: whole build in ~3s
+ acc += ((t - last) / 1000) * rate;
+ last = t;
+ if (acc >= 1) {
+ const adv = Math.floor(acc);
+ acc -= adv;
+ if (step + adv >= n - 1) { setStep(n - 1); play(false); return; }
+ setStep(step + adv);
+ }
+ requestAnimationFrame(tick);
+}
+
+// ---------------------------------------------------------------- animation
+// Animated assets loop through their frames once the painting replay has reached the end.
+
+let animAt = 0, animTimer = 0;
+function animating(): boolean {
+ return !!cur && cur.anim.length > 1 && $<HTMLInputElement>("animtog").checked && !playing && step >= cur.frames.length - 1;
+}
+
+function animTick(): void {
+ clearTimeout(animTimer);
+ if (animating()) {
+ animAt = (animAt + 1) % cur!.anim.length;
+ draw();
+ }
+ const ms = cur?.anim[animAt]?.ms ?? 100;
+ animTimer = window.setTimeout(animTick, Math.max(20, ms));
+}
+animTick();
+
+// ---------------------------------------------------------------- events
+
+function connect(): void {
+ const es = new EventSource("/events");
+ es.addEventListener("build", (ev) => onBuild(JSON.parse((ev as MessageEvent).data) as State));
+ es.onerror = () => { const s = $("status"); s.textContent = "disconnected"; s.className = "pill bad"; };
+}
+
+function onBuild(s: State): void {
+ const first = !state;
+ state = s;
+ $("file").textContent = s.file;
+ const bad = s.error ? 1 : s.assets.filter((a) => a.error).length + s.errors.length;
+ const st = $("status");
+ st.textContent = bad ? `${bad} error${bad > 1 ? "s" : ""}` : "ok";
+ st.className = "pill " + (bad ? "bad" : "ok");
+ $("buildinfo").textContent = `v${s.version} · ${s.ms}ms · ${s.time}`;
+ renderList();
+
+ const follow = ($<HTMLInputElement>("follow")).checked;
+ const changed = s.assets.filter((a) => a.changed);
+ if (first) {
+ const want = localStorage.getItem("pxl.sel");
+ const pick = s.assets.find((a) => a.name === want) ?? s.assets.find((a) => a.kind === "scene") ?? s.assets.find((a) => !a.part) ?? s.assets[0];
+ if (pick) select(pick.name);
+ else draw();
+ return;
+ }
+ if (follow && changed.length) {
+ // follow what was edited (errors first), else the selected asset, else the first changed one
+ const edited = s.assets.filter((a) => a.edited);
+ const target = edited.find((a) => a.error) ?? edited.find((a) => a.name === sel) ?? edited.find((a) => !a.part) ?? edited[0]
+ ?? changed.find((a) => a.name === sel) ?? changed.find((a) => !a.part) ?? changed[0];
+ select(target.name, { play: !target.error });
+ } else if (sel) {
+ const info = s.assets.find((a) => a.name === sel);
+ if (!info) draw();
+ else if (info.hash !== cur?.hash || info.error) select(sel, { keepStep: true });
+ else draw();
+ }
+}
+
+slider.oninput = () => { play(false); setStep(Number(slider.value)); };
+$("play").onclick = () => play(!playing);
+$("first").onclick = () => { play(false); setStep(0); };
+$("last").onclick = () => { play(false); setStep(Infinity); };
+$("prev").onclick = () => { play(false); setStep(step - 1); };
+$("next").onclick = () => { play(false); setStep(step + 1); };
+$("filter").oninput = renderList;
+for (const id of ["gridtog", "hl", "animtog"]) $(id).onchange = draw;
+
+const stage = $("stage");
+stage.addEventListener("wheel", (e) => {
+ e.preventDefault();
+ if (!cur) return;
+ const dpr = window.devicePixelRatio || 1;
+ const pic = picAt(cur, step);
+ const fit = Math.max(1, Math.min(48, Math.floor(Math.min((view.width - 40) / pic.w, (view.height - 40) / pic.h))));
+ const z = zoom || fit;
+ zoom = Math.max(1, Math.min(64, e.deltaY < 0 ? Math.ceil(z * 1.25) : Math.floor(z / 1.25)));
+ void dpr;
+ draw();
+}, { passive: false });
+let drag: { x: number; y: number; px: number; py: number } | undefined;
+stage.addEventListener("mousedown", (e) => { drag = { x: e.clientX, y: e.clientY, px: pan.x, py: pan.y }; });
+window.addEventListener("mouseup", () => { drag = undefined; });
+stage.addEventListener("mousemove", (e) => {
+ const r = stage.getBoundingClientRect();
+ hover = { x: e.clientX - r.left, y: e.clientY - r.top };
+ if (drag) pan = { x: drag.px + e.clientX - drag.x, y: drag.py + e.clientY - drag.y };
+ draw();
+});
+stage.addEventListener("mouseleave", () => { hover = undefined; draw(); });
+window.addEventListener("resize", draw);
+window.addEventListener("keydown", (e) => {
+ if ((e.target as HTMLElement).tagName === "INPUT" && (e.target as HTMLInputElement).type === "text") return;
+ if (e.key === " ") { e.preventDefault(); play(!playing); }
+ else if (e.key === "ArrowLeft") { play(false); setStep(step - 1); }
+ else if (e.key === "ArrowRight") { play(false); setStep(step + 1); }
+ else if (e.key === "Home") { play(false); setStep(0); }
+ else if (e.key === "End") { play(false); setStep(Infinity); }
+ else if (e.key === "f") { zoom = 0; pan = { x: 0, y: 0 }; draw(); }
+ else if (e.key === "g") { const t = $<HTMLInputElement>("gridtog"); t.checked = !t.checked; draw(); }
+ else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
+ e.preventDefault();
+ const names = [...document.querySelectorAll<HTMLCanvasElement>("#assets canvas")].map((c) => c.dataset.name!);
+ const i = names.indexOf(sel ?? "");
+ const n = names[Math.max(0, Math.min(names.length - 1, i + (e.key === "ArrowUp" ? -1 : 1)))];
+ if (n) select(n);
+ }
+});
+
+connect();
diff --git a/src/viewer/index.html b/src/viewer/index.html
new file mode 100644
index 0000000..ce21fb3
--- /dev/null
+++ b/src/viewer/index.html
@@ -0,0 +1,110 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>pxl live</title>
+<style>
+ :root {
+ --bg: #15131c; --panel: #1d1a27; --panel2: #24202f; --line: #322d40; --text: #e8e4f0; --dim: #9a93ab;
+ --accent: #ffb454; --accent2: #6fd3c1; --bad: #ff6b7a; --ok: #7bd88f;
+ --mono: ui-monospace, "Cascadia Code", "SF Mono", Consolas, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.4 system-ui, sans-serif; }
+ body { display: grid; grid-template: "head head head" 44px "list main side" 1fr / 230px 1fr 290px; }
+ header { grid-area: head; display: flex; align-items: center; gap: 14px; padding: 0 14px; background: var(--panel); border-bottom: 1px solid var(--line); }
+ header .logo { font: 700 15px var(--mono); color: var(--accent); letter-spacing: 1px; }
+ header .file { font-family: var(--mono); color: var(--dim); }
+ .pill { padding: 2px 9px; border-radius: 99px; font: 600 11px var(--mono); background: var(--panel2); color: var(--dim); }
+ .pill.ok { color: var(--ok); } .pill.bad { color: var(--bad); } .pill.busy { color: var(--accent); }
+ header .grow { flex: 1; }
+ label.tog { display: flex; gap: 6px; align-items: center; color: var(--dim); cursor: pointer; user-select: none; }
+ #list { grid-area: list; background: var(--panel); border-right: 1px solid var(--line); display: flex; flex-direction: column; min-height: 0; }
+ #filter { margin: 10px; padding: 6px 9px; border-radius: 6px; border: 1px solid var(--line); background: var(--bg); color: var(--text); font: 12px var(--mono); }
+ #assets { overflow: auto; flex: 1; padding: 0 6px 10px; }
+ .sect { font: 600 10px var(--mono); text-transform: uppercase; letter-spacing: 1px; color: var(--dim); margin: 12px 6px 4px; }
+ .row { display: flex; align-items: center; gap: 8px; padding: 4px 6px; border-radius: 6px; cursor: pointer; position: relative; }
+ .row:hover { background: var(--panel2); }
+ .row.sel { background: #3a3150; }
+ .row canvas { width: 32px; height: 32px; image-rendering: pixelated; background: #0e0d13; border-radius: 4px; flex: none; }
+ .row .nm { font: 12px var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .row .sz { font: 10px var(--mono); color: var(--dim); }
+ .row .dot { position: absolute; right: 8px; width: 7px; height: 7px; border-radius: 9px; }
+ .row .dot.err { background: var(--bad); }
+ .row .dot.new { background: var(--accent); animation: fade 2.5s forwards; }
+ @keyframes fade { to { opacity: 0; } }
+ main { grid-area: main; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
+ #stage { flex: 1; position: relative; overflow: hidden; background: #0e0d13; cursor: crosshair; }
+ #view { position: absolute; inset: 0; width: 100%; height: 100%; }
+ #err { position: absolute; left: 16px; right: 16px; bottom: 16px; display: none; padding: 12px 14px; border-radius: 8px;
+ background: #2b1720ee; border: 1px solid var(--bad); color: #ffd3d8; font: 12px/1.5 var(--mono); white-space: pre-wrap; }
+ #hud { position: absolute; left: 12px; top: 10px; font: 11px var(--mono); color: var(--dim); pointer-events: none; }
+ #timeline { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: var(--panel); border-top: 1px solid var(--line); }
+ #timeline button { background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 4px 9px; cursor: pointer; font: 12px var(--mono); }
+ #timeline button:hover { border-color: var(--accent); }
+ #slider { flex: 1; accent-color: var(--accent); }
+ #speed { background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 6px; font: 12px var(--mono); }
+ #stepinfo { padding: 6px 12px 9px; background: var(--panel); font: 12px var(--mono); color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ #stepinfo b { color: var(--text); font-weight: 600; }
+ #side { grid-area: side; background: var(--panel); border-left: 1px solid var(--line); display: flex; flex-direction: column; min-height: 0; }
+ #side h3 { margin: 12px 12px 6px; font: 600 10px var(--mono); text-transform: uppercase; letter-spacing: 1px; color: var(--dim); }
+ #steps { list-style: none; margin: 0; padding: 0 6px; overflow: auto; flex: 1; font: 11px var(--mono); }
+ #steps li { padding: 3px 6px; border-radius: 4px; cursor: pointer; display: flex; gap: 6px; }
+ #steps li:hover { background: var(--panel2); }
+ #steps li.cur { background: #3a3150; color: var(--accent); }
+ #steps li .i { color: var(--dim); min-width: 30px; text-align: right; }
+ #steps li .l { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
+ #steps li.none .l { opacity: .45; }
+ #inspect { margin: 0 12px; font: 12px var(--mono); min-height: 38px; display: flex; gap: 8px; align-items: center; }
+ #inspect .sw { width: 26px; height: 26px; border-radius: 5px; border: 1px solid var(--line); flex: none; }
+ #pal { display: flex; flex-wrap: wrap; gap: 3px; padding: 0 12px 12px; }
+ #pal span { width: 22px; height: 22px; border-radius: 4px; font: 10px var(--mono); display: grid; place-items: center; text-shadow: 0 0 3px #000, 0 0 2px #000; color: #fff; }
+ kbd { font: 10px var(--mono); background: var(--panel2); border: 1px solid var(--line); border-radius: 4px; padding: 0 4px; }
+ .keys { padding: 8px 12px 12px; color: var(--dim); font-size: 11px; line-height: 1.9; }
+</style>
+</head>
+<body>
+<header>
+ <span class="logo">pxl</span>
+ <span class="file" id="file">…</span>
+ <span class="pill" id="status">connecting</span>
+ <span class="pill" id="buildinfo"></span>
+ <span class="grow"></span>
+ <label class="tog"><input type="checkbox" id="follow" checked> follow edits</label>
+ <label class="tog"><input type="checkbox" id="gridtog" checked> grid</label>
+ <label class="tog"><input type="checkbox" id="hl" checked> highlight step</label>
+ <label class="tog"><input type="checkbox" id="animtog" checked> animate</label>
+</header>
+<section id="list">
+ <input id="filter" placeholder="filter assets…" spellcheck="false">
+ <div id="assets"></div>
+</section>
+<main>
+ <div id="stage"><canvas id="view"></canvas><div id="hud"></div><div id="err"></div></div>
+ <div id="timeline">
+ <button id="first" title="first step (Home)">⏮</button>
+ <button id="prev" title="previous step (←)">◀</button>
+ <button id="play" title="play / pause (space)">▶</button>
+ <button id="next" title="next step (→)">▶|</button>
+ <button id="last" title="last step (End)">⏭</button>
+ <input type="range" id="slider" min="0" max="0" value="0">
+ <select id="speed" title="steps per second">
+ <option value="auto">auto</option><option value="4">4/s</option><option value="12">12/s</option>
+ <option value="30">30/s</option><option value="120">120/s</option>
+ </select>
+ </div>
+ <div id="stepinfo">&nbsp;</div>
+</main>
+<section id="side">
+ <h3>Painting steps</h3>
+ <ol id="steps"></ol>
+ <h3>Pixel</h3>
+ <div id="inspect">hover the image</div>
+ <h3>Palette</h3>
+ <div id="pal"></div>
+ <div class="keys"><kbd>space</kbd> play <kbd>←</kbd><kbd>→</kbd> step <kbd>↑</kbd><kbd>↓</kbd> asset <kbd>wheel</kbd> zoom <kbd>drag</kbd> pan <kbd>f</kbd> fit</div>
+</section>
+<script type="module" src="/app.js"></script>
+</body>
+</html>
diff --git a/test/anim.test.ts b/test/anim.test.ts
new file mode 100644
index 0000000..a3279ba
--- /dev/null
+++ b/test/anim.test.ts
@@ -0,0 +1,153 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { failure, keys, PAL } from "./helpers.ts";
+import { loadSource } from "../src/node/load.ts";
+import { writeOutputs } from "../src/node/output.ts";
+import { encodeGif } from "../src/node/gif.ts";
+import { Img } from "../src/core/image.ts";
+import { pack, TRANSPARENT } from "../src/core/color.ts";
+
+const BLINK = `anim("blink", { fps: 4, w: 3, h: 1 }, rect(0, 0, 3, 1, "r"),
+ frame(), frame(px(1, 0, "w")), frame({ hold: 2 }, px(1, 0, "g")))`;
+const load = (body: string) => loadSource(PAL + BLINK + "\n" + body, "t.px.js");
+const frameKeys = (p: ReturnType<typeof load>, name: string) => p.frames(name).map((f) => keys({ ...p, image: () => f.img } as never, name));
+
+test("anim: frame() items are patches over the shared items, with durations", () => {
+ const p = load("");
+ const fr = p.frames("blink");
+ assert.deepEqual(fr.map((f) => f.ms), [250, 250, 500]);
+ assert.deepEqual(frameKeys(p, "blink"), ["rrr", "rwr", "rgr"]);
+ assert.deepEqual(p.timeline("blink"), { loop: 1000, step: 250, durations: [250, 250, 500], once: false });
+});
+
+test("anim: procedural frames see c.frame / c.frames / c.phase", () => {
+ const p = loadSource(PAL + `anim("dot", { frames: 4, fps: 10, w: 4, h: 1 }, (c) => c.px(Math.round(c.phase * c.frames), 0, "w"))`, "t.px.js");
+ assert.deepEqual(frameKeys(p, "dot"), ["w...", ".w..", "..w.", "...w"]);
+ assert.equal(p.timeline("dot")!.step, 100);
+});
+
+test("anim: scenes that place anims animate; delay shifts, frame freezes", () => {
+ const p = load(`scene("s", { w: 11, h: 1, bg: "k" }, stamp("blink", 0, 0), stamp("blink", 4, 0, { delay: 250 }), stamp("blink", 8, 0, { frame: 1 }))
+scene("still", { w: 3, h: 1 }, stamp("blink", 0, 0, { frame: 2 }))`);
+ assert.deepEqual(p.timeline("s"), { loop: 1000, step: 250 });
+ assert.deepEqual(frameKeys(p, "s"), ["rrrkrwrkrwr", "rwrkrgrkrwr", "rgrkrgrkrwr", "rgrkrrrkrwr"]);
+ assert.equal(p.timeline("still"), undefined, "a frozen frame doesn't animate the scene");
+ assert.equal(keys(p, "still"), "rgr");
+});
+
+test("anim: loop false holds the last frame; anims combine to the lcm of their loops", () => {
+ const p = loadSource(PAL + `anim("a", { fps: 10, loop: false, w: 1, h: 1 }, frame(px(0, 0, "r")), frame(px(0, 0, "w")))
+anim("b", { fps: 10, w: 1, h: 1 }, frame(px(0, 0, "g")), frame(px(0, 0, "k")), frame(px(0, 0, "w")))
+scene("s", { w: 2, h: 1 }, stamp("a", 0, 0), stamp("b", 1, 0))`, "t.px.js");
+ assert.equal(keys({ ...p, image: () => p.image("a", 0, 5000) } as never, "a"), "w");
+ assert.deepEqual(p.timeline("s"), { loop: 600, step: 100 });
+});
+
+test("anim: frame() is only for anims; options are validated", () => {
+ assert.match(failure(PAL + 'sprite("s", { w: 2, h: 2 }, frame(px(0, 0, "r")))', "s").message, /only goes inside an anim/);
+ assert.match(failure(PAL + 'anim("a", { w: 2, h: 2 }, frame({ msec: 3 }))').message, /unknown option 'msec'/);
+ assert.match(failure(PAL + 'anim("a", { w: 2, h: 2, fsp: 3 })').message, /unknown option 'fsp'/);
+});
+
+test("anim: build writes a strip, Aseprite-style JSON, GIFs and animated sheets", () => {
+ const dir = mkdtempSync(join(tmpdir(), "pxl-anim-"));
+ try {
+ const p = load(`sheet("all", ["blink"])`);
+ const r = writeOutputs(p, dir);
+ assert.deepEqual(r.errors, []);
+ const j = JSON.parse(readFileSync(join(dir, "anims", "blink.json"), "utf8"));
+ assert.deepEqual(Object.values(j.frames).map((f: any) => f.duration), [250, 250, 500]);
+ assert.deepEqual(j.meta.frameTags, [{ name: "blink", from: 0, to: 2, direction: "forward" }]);
+ assert.ok(readFileSync(join(dir, "anims", "blink.gif")).subarray(0, 6).toString() === "GIF89a");
+ assert.ok(readFileSync(join(dir, "_preview", "blink.gif")).length > 0);
+ const s = JSON.parse(readFileSync(join(dir, "all.json"), "utf8"));
+ assert.deepEqual(Object.keys(s.frames), ["blink_0", "blink_1", "blink_2"]);
+ assert.equal(s.meta.frameTags[0].to, 2);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("gif: frames decode back to the same pixels and delays", () => {
+ const a = new Img(5, 3), b = new Img(5, 3);
+ a.fill(pack(255, 0, 0));
+ b.fill(pack(0, 0, 255));
+ a.data[0] = TRANSPARENT;
+ b.data[7] = pack(255, 255, 255);
+ const g = decodeGif(encodeGif([{ img: a, ms: 120 }, { img: a, ms: 80 }, { img: b, ms: 50 }]));
+ assert.equal(g.frames.length, 2, "repeated frames merge");
+ assert.deepEqual(g.frames.map((f) => f.delay), [20, 5]);
+ assert.equal(g.frames[0].rgba[0], -1, "transparent pixel");
+ assert.deepEqual(g.frames[0].rgba[1], 0xff0000);
+ assert.deepEqual(g.frames[1].rgba[7], 0xffffff);
+ assert.deepEqual(g.frames[1].rgba[8], 0x0000ff);
+});
+
+test("gif: many colors are reduced to one palette and still decode", () => {
+ const img = new Img(40, 40);
+ for (let i = 0; i < img.data.length; i++) img.data[i] = pack(i % 256, (i * 7) % 256, (i * 13) % 256);
+ const g = decodeGif(encodeGif([{ img, ms: 100 }]));
+ assert.equal(g.frames[0].rgba.length, 1600);
+});
+
+/** Minimal GIF decoder for the tests: global palette, full-frame images. */
+function decodeGif(buf: Buffer) {
+ assert.equal(buf.subarray(0, 6).toString(), "GIF89a");
+ const w = buf.readUInt16LE(6), h = buf.readUInt16LE(8), flags = buf[10];
+ let p = 13;
+ const gct: number[] = [];
+ if (flags & 0x80) for (let i = 0; i < 2 << (flags & 7); i++, p += 3) gct.push((buf[p] << 16) | (buf[p + 1] << 8) | buf[p + 2]);
+ const frames: { delay: number; rgba: number[] }[] = [];
+ let delay = 0, trans = -1;
+ while (buf[p] !== 0x3b) {
+ if (buf[p] === 0x21) {
+ const label = buf[p + 1];
+ p += 2;
+ if (label === 0xf9) { delay = buf.readUInt16LE(p + 2); trans = buf[p + 1] & 1 ? buf[p + 4] : -1; }
+ while (buf[p]) p += buf[p] + 1;
+ p++;
+ } else if (buf[p] === 0x2c) {
+ p += 10;
+ const min = buf[p++];
+ const data: number[] = [];
+ while (buf[p]) { for (let i = 1; i <= buf[p]; i++) data.push(buf[p + i]); p += buf[p] + 1; }
+ p++;
+ const idx = unlzw(data, min, w * h);
+ frames.push({ delay, rgba: idx.map((i) => (i === trans ? -1 : gct[i])) });
+ } else throw new Error("bad block " + buf[p]);
+ }
+ return { w, h, frames };
+}
+
+function unlzw(data: number[], min: number, n: number): number[] {
+ const clear = 1 << min, eoi = clear + 1, out: number[] = [];
+ let size = min + 1, dict: number[][] = [], prev: number[] | undefined, bit = 0;
+ const reset = () => { dict = []; for (let i = 0; i < clear; i++) dict[i] = [i]; dict[clear] = []; dict[eoi] = []; size = min + 1; prev = undefined; };
+ reset();
+ while (out.length < n) {
+ let code = 0;
+ for (let i = 0; i < size; i++, bit++) code |= ((data[bit >> 3] >> (bit & 7)) & 1) << i;
+ if (code === clear) { reset(); continue; }
+ if (code === eoi) break;
+ const entry = code < dict.length ? dict[code] : [...prev!, prev![0]];
+ out.push(...entry);
+ if (prev) dict.push([...prev, entry[0]]);
+ prev = entry;
+ if (dict.length === 1 << size && size < 12) size++;
+ }
+ return out;
+}
+
+test("gif: big noisy frames survive LZW table resets exactly", () => {
+ const img = new Img(200, 150);
+ let s = 7;
+ for (let i = 0; i < img.data.length; i++) {
+ s = (s * 1103515245 + 12345) >>> 0;
+ img.data[i] = pack((s >>> 16) % 16 * 16, 0, 0);
+ }
+ const g = decodeGif(encodeGif([{ img, ms: 100 }]));
+ for (let i = 0; i < img.data.length; i++) assert.equal(g.frames[0].rgba[i], img.data[i] >>> 8);
+});
diff --git a/test/core.test.ts b/test/core.test.ts
new file mode 100644
index 0000000..1b1e217
--- /dev/null
+++ b/test/core.test.ts
@@ -0,0 +1,127 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { art, failure, PAL } from "./helpers.ts";
+import { loadSource } from "../src/node/load.ts";
+
+const eq = (a: string, b: string) => assert.equal(a, b);
+
+test("grid: trimmed rows, short rows padded", () => {
+ eq(art(PAL + 'sprite("a", `\n rr\n r\n`)', "a"), "rr\nr.");
+});
+
+test("mirror even, odd and vertical", () => {
+ eq(art(PAL + 'sprite("a", { mx: true }, "rw")', "a"), "rwwr");
+ eq(art(PAL + 'sprite("a", { mx: "c", my: "c" }, "r.\\n.w")', "a"), "r.r\n.w.\nr.r");
+});
+
+test("outline grows the canvas; outline8 adds diagonals", () => {
+ eq(art(PAL + 'sprite("a", { outline: "k" }, "r")', "a"), ".k.\nkrk\n.k.");
+ eq(art(PAL + 'sprite("a", { outline8: "k" }, "r")', "a"), "kkk\nkrk\nkkk");
+});
+
+test("variants: swap, flip, rot", () => {
+ const base = PAL + 'sprite("a", "rw\\nr.");';
+ eq(art(base + 'sprite("b", { base: "a", swap: { r: "g" } })', "b"), "gw\ng.");
+ eq(art(base + 'sprite("b", { base: "a", flip: "x" })', "b"), "wr\n.r");
+ eq(art(base + 'sprite("b", { base: "a", rot: 90 })', "b"), "rr\n.w");
+});
+
+test("overlay keeps with '.', erases with '_'", () => {
+ eq(art(PAL + 'sprite("a", "rrr"); sprite("b", { base: "a" }, "._w")', "b"), "r.w");
+});
+
+test("stamps resolve lazily and use the host palette for swaps", () => {
+ eq(art(PAL + 'sprite("b", { w: 3, h: 1 }, stamp("_p", 1, 0)); sprite("_p", "w")', "b"), ".w.");
+ eq(art(PAL + 'sprite("_p", "r"); sprite("b", { w: 2, h: 1 }, stamp("_p", 0, 0, { swap: { r: "g" } }), px(1, 0, "r"))', "b"), "gr");
+});
+
+test("primitives", () => {
+ eq(art(PAL + 'sprite("a", { w: 4, h: 3 }, box(0, 0, 4, 3, "r"))', "a"), "rrrr\nr..r\nrrrr");
+ eq(art(PAL + 'sprite("a", { w: 4, h: 4 }, line(0, 0, 3, 3, "r"))', "a"), "r...\n.r..\n..r.\n...r");
+ eq(art(PAL + 'sprite("a", { w: 5, h: 3 }, line(1, 1, 3, 1, "r", 3))', "a"), "rrrrr\nrrrrr\nrrrrr");
+ eq(art(PAL + 'sprite("a", { w: 5, h: 5 }, circ(2, 2, 2, "r"))', "a"), ".rrr.\nrrrrr\nrrrrr\nrrrrr\n.rrr.");
+ eq(art(PAL + 'sprite("a", { w: 5, h: 5 }, ring(2, 2, 2, "r"))', "a"), ".rrr.\nr...r\nr...r\nr...r\n.rrr.");
+ eq(art(PAL + 'sprite("a", { w: 4, h: 2 }, dither(0, 0, 4, 2, "r", "w"))', "a"), "wrwr\nrwrw");
+ eq(art(PAL + 'sprite("a", "r.r\\nrrr", fill(1, 0, "w"))', "a"), "rwr\nrrr");
+ eq(art(PAL + 'sprite("a", { w: 4, h: 4 }, poly([0, 0, 4, 0, 0, 4], "r"))', "a"), "rrr.\nrr..\nr...\n....");
+});
+
+test("clip restricts any op to a region (half shapes)", () => {
+ eq(art(PAL + 'sprite("a", { w: 5, h: 3 }, clip([0, 0, 5, 2], circ(2, 2, 2, "r")))', "a"), ".rrr.\nrrrrr\n.....");
+ eq(art(PAL + 'sprite("_p", "ww"); sprite("a", { w: 2, h: 1 }, clip([0, 0, 1, 1], stamp("_p", 0, 0)))', "a"), "w.");
+});
+
+test("function items get the canvas", () => {
+ eq(art(PAL + 'sprite("a", { w: 3, h: 1 }, (c) => { for (let x = 0; x < 3; x += 2) c.px(x, 0, "r") })', "a"), "r.r");
+});
+
+test("tile, pattern and tilemap", () => {
+ const base = PAL + 'sprite("_a", "r"); sprite("_b", "w");';
+ eq(art(base + 'sprite("t", { w: 3, h: 1 }, tile("_a", 0, 0, 3, 1))', "t"), "rrr");
+ eq(art(base + 'sprite("_ab", "rw"); sprite("t", { w: 3, h: 1 }, pattern("_ab", 0, 0, 3, 1))', "t"), "rwr");
+ eq(art(base + 'sprite("t", { w: 3, h: 2 }, tilemap("ab\\n.a", { map: { a: "_a", b: "_b" } }))', "t"), "rw.\n.r.");
+});
+
+test("groups and globs: stable random picks, weighting", () => {
+ const base = PAL + 'sprite("_a", "r"); sprite("_b", "w"); group("g", ["_a", "_b"]);';
+ const a = art(base + 'sprite("t", { w: 40, h: 1 }, tile("g", 0, 0, 40, 1))', "t");
+ assert.equal(a, art(base + 'sprite("t", { w: 40, h: 1 }, tile("g", 0, 0, 40, 1))', "t"));
+ assert.ok(a.includes("r") && a.includes("w"), a);
+ const g = art(base + 'sprite("t", { w: 40, h: 1 }, tile("_*", 0, 0, 40, 1))', "t");
+ assert.ok(g.includes("r") && g.includes("w"), g);
+ eq(art(base + 'group("only", ["_a", "_a"]); sprite("t", { w: 5, h: 1 }, tile("only", 0, 0, 5, 1))', "t"), "rrrrr");
+});
+
+test("scatter: count, on-mask, clip, below", () => {
+ const a = art(PAL + 'sprite("_d", "w"); sprite("t", { w: 10, h: 10 }, rect(0, 0, 5, 10, "r"), scatter("_d", 0, 0, 10, 10, 12, { on: "r", seed: 3 }))', "t");
+ assert.ok((a.match(/w/g) ?? []).length > 4);
+ for (const row of a.split("\n")) eq(row.slice(5), ".....");
+ eq(art(PAL + 'sprite("_d", "www\\nwww\\nwww"); sprite("t", { w: 6, h: 3 }, rect(0, 0, 3, 3, "r"), scatter("_d", 2, 1, 1, 1, 1, { on: "r", clip: true }))', "t"),
+ "rww...\nrww...\nrww...");
+ // below: a layer's brush can see the composite under it
+ eq(art(PAL + 'sprite("_d", "w"); sprite("t", { w: 4, h: 1 }, rect(0, 0, 2, 1, "r"), layer("x", scatter("_d", 0, 0, 4, 1, 20, { on: "r", below: true })))', "t"), "ww..");
+});
+
+test("layers: order, offset, hidden, blend, inferred size, outline after", () => {
+ eq(art(PAL + 'sprite("a", { w: 4, h: 1 }, rect(0, 0, 4, 1, "w"), layer("l", { x: 1 }, px(0, 0, "r")), px(1, 0, "g"), layer("h", { hidden: true }, px(3, 0, "r")))', "a"), "wgww");
+ eq(art(PAL + 'ramps("rw"); sprite("a", { w: 3, h: 1 }, rect(0, 0, 3, 1, "w"), layer("s", { shade: true }, px(2, 0, "k")))', "a"), "wwr");
+ eq(art(PAL + 'sprite("a", { outline: "k" }, layer("l", "r"))', "a"), ".k.\nkrk\n.k.");
+ eq(art(PAL + 'ramps("rw"); scene("s", { w: 4, h: 1, bg: "w" }, layer("l", { shade: true, density: 0.5 }, rect(0, 0, 4, 1, "k")))', "s"), "rwrw");
+});
+
+test("ramps: shade/light step along, regions and density", () => {
+ const base = PAL + 'ramps("krw");';
+ eq(art(base + 'sprite("a", { w: 5, h: 1 }, rect(0, 0, 5, 1, "w"), shade([2, 0, 1]))', "a"), "wrrrw");
+ eq(art(base + 'sprite("a", { w: 3, h: 1 }, rect(0, 0, 3, 1, "w"), shade(undefined, 2))', "a"), "kkk");
+ eq(art(base + 'sprite("a", { w: 2, h: 1 }, rect(0, 0, 2, 1, "r"), light())', "a"), "ww");
+ eq(art(base + 'sprite("a", { w: 4, h: 2 }, rect(0, 0, 4, 2, "w"), shade(undefined, 1, 0.5))', "a"), "rwrw\nwrwr");
+ eq(art(base + 'sprite("a", { w: 2, h: 1 }, rect(0, 0, 2, 1, "w"), recolor({ w: "g" }, [0, 0, 1, 1]))', "a"), "gw");
+});
+
+test("wire with hangs, text", () => {
+ eq(art(PAL + 'sprite("_b", "w"); sprite("a", { w: 9, h: 4 }, wire(0, 0, 8, 0, 2, "r", { hang: "_b", every: 4, start: 4 }))', "a"),
+ "r.......r\n.rr...rr.\n..rrrrr..\n....w....");
+ eq(art(PAL + 'sprite("a", { w: 3, h: 5 }, text(0, 0, "L", "r"))', "a"), "r..\nr..\nr..\nr..\nrrr");
+});
+
+test("reseed rebuilds a placed asset with fresh random choices", () => {
+ const src = PAL + 'sprite("_a", "r"); sprite("_b", "w"); group("g", ["_a", "_b"]);' +
+ 'sprite("cell", { w: 8, h: 1 }, tile("g", 0, 0, 8, 1));' +
+ 'sprite("t", { w: 8, h: 6 }, tile("cell", 0, 0, 1, 6, { reseed: true }))';
+ const rows = art(src, "t").split("\n");
+ assert.ok(new Set(rows).size > 1, rows.join("\n"));
+});
+
+test("sheets expand globs (exported only) and groups", () => {
+ const p = loadSource(PAL + 'sprite("s1", "rr"); sprite("s2", "r"); sprite("_x", "r"); group("g", ["_x"]); sheet("sh", ["s*", "g"], { pad: 1 })');
+ assert.deepEqual(p.sheetNames(p.sheets[0]), ["s1", "s2", "_x"]);
+});
+
+test("trace records each top-level op, layer and post step", () => {
+ const p = loadSource(PAL + 'sprite("a", { w: 3, h: 1, outline: "k" },\n rect(0, 0, 3, 1, "r"),\n (c) => { c.px(0, 0, "w"); c.px(2, 0, "w") })', "t.px.js", { trace: true });
+ const frames = p.build("a").trace!.frames;
+ assert.deepEqual(frames.map((f) => f.label), ['rect(0, 0, 3, 1, "r")', 'px(0, 0, "w")', 'px(2, 0, "w")', "outline k"]);
+ assert.equal(frames[0].loc, "t.px.js:2:3");
+ assert.equal(frames[1].loc, "t.px.js:3:14");
+ assert.equal(frames[3].w, 5); // outline frame shows the grown image
+});
diff --git a/test/errors.test.ts b/test/errors.test.ts
new file mode 100644
index 0000000..2955527
--- /dev/null
+++ b/test/errors.test.ts
@@ -0,0 +1,59 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { failure, PAL } from "./helpers.ts";
+
+const has = (msg: string, ...parts: string[]) => {
+ for (const p of parts) assert.ok(msg.includes(p), `expected "${p}" in:\n${msg}`);
+};
+
+test("unknown color key: location, path, case hint, available keys", () => {
+ const e = failure(PAL + 'sprite("a", { w: 2, h: 2 },\n rect(0, 0, 2, 2, "R"))', "a");
+ assert.equal(e.loc, "t.px.js:2:3");
+ has(e.message, "sprite 'a' > rect", "unknown color key 'R'", "did you mean 'r'");
+});
+
+test("grid errors point at row and column", () => {
+ has(failure(PAL + 'sprite("a", "rr\\nrz")', "a").message, "unknown color key 'z'", "row 1, col 1");
+});
+
+test("op argument checks at definition time, with usage", () => {
+ const e = failure(PAL + 'sprite("a", { w: 1, h: 1 },\n rect(0, 0, 1, "r"))');
+ assert.equal(e.loc, "t.px.js:2:3");
+ has(e.message, "rect: argument 4 (h) must be a number", "usage: rect(x, y, w, h, c)");
+ has(failure(PAL + 'sprite("a", { w: 1, h: 1 }, px(0, 0))').message, "px: missing argument 3 (c)");
+});
+
+test("unknown options get suggestions", () => {
+ has(failure(PAL + 'sprite("a", { outlin: "k" }, "r")').message, "unknown option 'outlin'", "did you mean 'outline'");
+ has(failure(PAL + 'sprite("a", "r", layer("l", { hiden: true }))').message, "unknown option 'hiden'", "did you mean 'hidden'");
+});
+
+test("unknown assets get suggestions; cycles and groups-as-base are caught", () => {
+ has(failure(PAL + 'sprite("slime", "r"); sprite("a", { w: 1, h: 1 }, stamp("slme", 0, 0))', "a").message, "unknown asset 'slme'", "did you mean 'slime'");
+ has(failure(PAL + 'sprite("a", { base: "b" }); sprite("b", { base: "a" })', "a").message, "reference cycle");
+ has(failure(PAL + 'sprite("_a", "r"); group("g", ["_a"]); sprite("a", { base: "g" })', "a").message, "is a group/glob");
+ has(failure(PAL + 'group("g", ["nope*"]); sprite("a", { w: 1, h: 1 }, stamp("g", 0, 0))', "a").message, "matches no assets");
+});
+
+test("definition mistakes: duplicates, bad items, nested layers, missing size", () => {
+ has(failure(PAL + 'sprite("a", "r");\nsprite("a", "r")').message, "'a' is already defined at t.px.js:1:");
+ has(failure(PAL + 'sprite("a", { w: 1, h: 1 }, [rect(0, 0, 1, 1, "r")])').message, "item 1 is an array");
+ has(failure(PAL + 'sprite("a", { w: 1, h: 1 }, layer("x", layer("y")))', "a").message, "can't be nested");
+ has(failure(PAL + 'sprite("a", { w: 1 })', "a").message, "no size");
+});
+
+test("runtime errors inside functions point at the art file line", () => {
+ const e = failure(PAL + 'sprite("a", { w: 1, h: 1 }, (c) => {\n c.px(0, 0, "nope")\n})', "a");
+ assert.equal(e.loc, "t.px.js:2:5");
+ has(e.message, "sprite 'a' > function", "unknown color key 'nope'");
+});
+
+test("syntax errors report the line", () => {
+ const e = failure(PAL + 'sprite("a", "r"\nsprite("b", "r")');
+ assert.ok(e.loc?.startsWith("t.px.js:"), e.message);
+});
+
+test("ramps validate their keys", () => {
+ has(failure(PAL + 'ramps("krX")').message, "ramps", "unknown key 'X'");
+ has(failure(PAL + 'sprite("a", { w: 1, h: 1 }, shade())', "a").message, "no ramps defined");
+});
diff --git a/test/glow.test.ts b/test/glow.test.ts
new file mode 100644
index 0000000..3349813
--- /dev/null
+++ b/test/glow.test.ts
@@ -0,0 +1,59 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { failure, keys, PAL } from "./helpers.ts";
+import { loadSource } from "../src/node/load.ts";
+
+// Black 20x5 strip with one red "flame" pixel at (10, 2).
+const strip = (glow: string) =>
+ loadSource(PAL + `scene("s", { w: 20, h: 5, bg: "k" }, px(10, 2, "r"), ${glow})`, "t.px.js");
+const red = (p: ReturnType<typeof loadSource>, x: number, y: number) => p.image("s").get(x, y) >>> 24;
+
+test("glow: a halo in the source color that falls off with distance", () => {
+ const p = strip('glow("r", { r: 6, strength: 1 })');
+ const pal = p.assets.get("s")!.pal;
+ assert.equal(p.image("s").get(10, 2), pal.resolve("r"), "the glowing pixel itself is untouched");
+ assert.ok(red(p, 11, 2) > red(p, 13, 2) && red(p, 13, 2) > red(p, 15, 2), "falls off");
+ assert.equal(p.image("s").get(17, 2), pal.resolve("k"), "nothing beyond r");
+ assert.equal((p.image("s").get(11, 2) >>> 16) & 255, 0, "red source, no green in the halo");
+});
+
+test("glow: color tints the halo, bands make crisp rings, transparent pixels stay empty", () => {
+ const tinted = strip('glow("r", { r: 4, color: "g", strength: 1 })');
+ assert.ok(((tinted.image("s").get(11, 2) >>> 16) & 255) > 0, "green tint");
+ const banded = strip('glow("r", { r: 6, bands: 2, strength: 1 })');
+ assert.equal(red(banded, 11, 2), red(banded, 12, 2), "same band");
+ const p = loadSource(PAL + `sprite("s", { w: 5, h: 1 }, px(0, 0, "r"), px(4, 0, "k"), glow("r", { r: 4 }))`, "t.px.js");
+ assert.equal(keys(p, "s").slice(0, 4), "r...", "no halo painted onto transparent pixels");
+ assert.notEqual(keys(p, "s")[4], "k", "but opaque neighbours are lit");
+});
+
+test("glow: ramp mode steps neighbours lighter and stays in the palette", () => {
+ const src = 'use("pico8"); pal({ k: 0, d: 5, m: 6, w: 7, y: 10 }); ramps("kdmw"); ' +
+ 'scene("s", { w: 9, h: 1, bg: "k" }, px(4, 0, "y"), glow("y", { r: 3, ramp: 3 }))';
+ const p = loadSource(src, "t.px.js");
+ const row = keys(p, "s");
+ assert.match(row, /^[kdmw]{4}y[kdmw]{4}$/, "every pixel is a palette key");
+ assert.notEqual(row[3], "k", "next to the source is lit");
+ assert.equal(row[0], "k", "beyond the radius is unlit");
+});
+
+test("glow: only directly in a sprite or scene; options are validated", () => {
+ assert.match(failure(PAL + 'scene("s", { w: 4, h: 4 }, layer("a", glow("r")))', "s").message, /directly in a sprite or scene/);
+ assert.match(failure(PAL + 'scene("s", { w: 4, h: 4 }, glow("r", { radius: 3 }))', "s").message, /radius/);
+ assert.match(failure(PAL + 'scene("s", { w: 4, h: 4 }, glow("r", { r: 0 }))', "s").message, /r must be > 0/);
+});
+
+test("glow: where limits which pixels glow", () => {
+ const p = loadSource(PAL + `scene("s", { w: 30, h: 1, bg: "k" }, px(2, 0, "r"), px(27, 0, "r"), glow("r", { where: [0, 0, 10, 1], r: 3 }))`, "t.px.js");
+ const pal = p.assets.get("s")!.pal;
+ assert.notEqual(p.image("s").get(3, 0), pal.resolve("k"), "inside: glows");
+ assert.equal(p.image("s").get(26, 0), pal.resolve("k"), "outside: no halo");
+});
+
+test("glow: after lighting(), lit pixels still glow by their palette key", () => {
+ const src = PAL + `scene("s", { w: 20, h: 1, bg: "k" }, px(10, 0, "r"), lamp(10, 0, { r: 4, color: "#888" }),
+ lighting({ cell: 1 }), glow("r", { r: 4, strength: 1 }))`;
+ const p = loadSource(src, "t.px.js");
+ assert.ok(red(p, 12, 0) > 0, "halo around the dimmed red pixel");
+ assert.ok(red(p, 10, 0) < 255, "the lit source keeps its lit color");
+});
diff --git a/test/helpers.ts b/test/helpers.ts
new file mode 100644
index 0000000..3ea30b9
--- /dev/null
+++ b/test/helpers.ts
@@ -0,0 +1,40 @@
+import { TRANSPARENT } from "../src/core/color.ts";
+import { PxError } from "../src/core/errors.ts";
+import type { Project } from "../src/core/project.ts";
+import { loadSource } from "../src/node/load.ts";
+
+/** Palette prelude on line 1 (no newline), so test sources keep their own line numbers. */
+export const PAL = 'use("pico8"); pal({ k: 0, r: 8, w: 7, g: 11 }); ';
+
+/** Build `name` from source and return its pixels as palette-key rows. */
+export function art(src: string, name: string, trace = false): string {
+ const p = loadSource(src, "t.px.js", { trace });
+ return keys(p, name);
+}
+
+export function keys(p: Project, name: string): string {
+ const img = p.image(name);
+ const rev = p.assets.get(name)!.pal.reverse();
+ const rows: string[] = [];
+ for (let y = 0; y < img.h; y++) {
+ let r = "";
+ for (let x = 0; x < img.w; x++) {
+ const c = img.data[y * img.w + x];
+ r += c === TRANSPARENT ? "." : rev.get(c) ?? "?";
+ }
+ rows.push(r);
+ }
+ return rows.join("\n");
+}
+
+/** The error thrown while loading + building `name`. */
+export function failure(src: string, name?: string): PxError {
+ try {
+ const p = loadSource(src, "t.px.js");
+ if (name) p.image(name);
+ } catch (e) {
+ if (e instanceof PxError) return e;
+ throw new Error("expected a PxError, got " + String(e));
+ }
+ throw new Error("expected a failure");
+}
diff --git a/test/light.test.ts b/test/light.test.ts
new file mode 100644
index 0000000..670ef2a
--- /dev/null
+++ b/test/light.test.ts
@@ -0,0 +1,64 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { failure, PAL } from "./helpers.ts";
+import { loadSource } from "../src/node/load.ts";
+
+// White room 40x8 at cell 1 so values are easy to reason about.
+const room = (body: string, lighting = "lighting({ cell: 1 })") =>
+ loadSource(PAL + `scene("s", { w: 40, h: 8, bg: "w" }, ${body}, ${lighting})`, "t.px.js");
+const red = (p: ReturnType<typeof loadSource>, x: number, y: number) => p.image("s").get(x, y) >>> 24;
+
+test("lighting: lamps light nearby pixels, falling off to black", () => {
+ const p = room('lamp(2, 4, { r: 20 })');
+ assert.equal(red(p, 2, 4), 255);
+ assert.ok(red(p, 10, 4) > red(p, 18, 4));
+ assert.equal(red(p, 30, 4), 0);
+});
+
+test("lighting: solid layers block light, but their edge catches some", () => {
+ const p = room('layer("wall", { solid: true }, rect(10, 0, 6, 8, "w")), lamp(2, 4, { r: 40 })', "lighting({ cell: 1, block: 0.9 })");
+ const open = room('lamp(2, 4, { r: 40 })');
+ assert.ok(red(p, 20, 4) < red(open, 20, 4) / 2, "light behind the wall is much dimmer");
+ assert.ok(red(p, 10, 4) > 100, "edge of the block is lit");
+ assert.ok(red(p, 14, 4) < red(p, 10, 4) / 2, "light fades inside the block");
+});
+
+test("lighting: brighter light reaches deeper into blocks", () => {
+ const wall = 'layer("wall", { solid: true }, rect(6, 0, 30, 8, "w"))';
+ const dim = room(`${wall}, lamp(2, 4, { r: 40, power: 0.5 })`), bright = room(`${wall}, lamp(2, 4, { r: 40, power: 2 })`);
+ assert.equal(red(dim, 26, 4), 0);
+ assert.ok(red(bright, 26, 4) > 0);
+});
+
+test("lighting: lamps travel with stamps, flips and mirroring", () => {
+ const src = PAL + `
+sprite("torch", { mx: true }, "r.", lamp(0, 0, { r: 6 }))
+scene("s", { w: 40, h: 4, bg: "w" }, stamp("torch", 30, 0), lighting({ cell: 1 }))`;
+ const p = loadSource(src, "t.px.js");
+ assert.equal(p.image("torch").lamps!.length, 2, "mirror duplicates the lamp");
+ assert.equal(p.image("s").get(30, 0) >>> 24, 255);
+ assert.equal(p.image("s").get(33, 0) >>> 24, 255, "mirrored lamp lights the right end");
+ assert.equal(p.image("s").get(5, 0) >>> 24, 0);
+ assert.equal(p.image("s").lamps, undefined, "lighting consumes lamps");
+});
+
+test("lighting: sky lights open columns, walls keep it out, unlit layers are skipped", () => {
+ const p = loadSource(PAL + `
+scene("s", { w: 8, h: 8, bg: "w" },
+ layer("bg", { unlit: true }, rect(0, 0, 2, 8, "r")),
+ layer("back", { wall: true }, rect(4, 0, 4, 8, "g")),
+ lighting({ cell: 1, sky: 1, skyReach: 2 }))`, "t.px.js");
+ const img = p.image("s"), pal = p.assets.get("s")!.pal;
+ assert.equal(img.get(0, 7), pal.resolve("r"), "unlit layer untouched");
+ assert.equal(img.get(2, 7), pal.resolve("w"), "open column fully sky-lit");
+ assert.equal(img.get(7, 4) >>> 8 & 255, 0, "deep behind the wall is dark");
+});
+
+test("lighting: emit keys ignore it; options are validated", () => {
+ const p = room('rect(0, 0, 4, 4, "r")', 'lighting({ cell: 1, emit: "r" })');
+ assert.equal(p.image("s").get(1, 1), p.assets.get("s")!.pal.resolve("r"));
+ assert.equal(p.image("s").get(20, 6) >>> 24, 0);
+ assert.match(failure(PAL + 'lighting({ cel: 2 })').message, /unknown option 'cel'.*did you mean 'cell'/);
+ assert.match(failure(PAL + 'lamp(1, 1, { radius: 3 })').message, /unknown option 'radius'/);
+ assert.match(failure(PAL + 'sprite("a", { w: 2, h: 2 }, layer("l", lighting()))', "a").message, /lighting\(\) goes directly/);
+});
diff --git a/test/node.test.ts b/test/node.test.ts
new file mode 100644
index 0000000..e5d968a
--- /dev/null
+++ b/test/node.test.ts
@@ -0,0 +1,112 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { crc32, inflateSync } from "node:zlib";
+import { Img } from "../src/core/image.ts";
+import { pack } from "../src/core/color.ts";
+import { encodePng } from "../src/node/png.ts";
+import { main } from "../src/node/cli.ts";
+import { serve } from "../src/node/server.ts";
+
+function chunks(buf: Buffer): { type: string; data: Buffer; crcOk: boolean }[] {
+ const out = [];
+ let o = 8;
+ while (o < buf.length) {
+ const len = buf.readUInt32BE(o), type = buf.toString("ascii", o + 4, o + 8);
+ const data = buf.subarray(o + 8, o + 8 + len);
+ out.push({ type, data, crcOk: (crc32(buf.subarray(o + 4, o + 8 + len)) >>> 0) === buf.readUInt32BE(o + 8 + len) });
+ o += 12 + len;
+ }
+ return out;
+}
+
+test("png: indexed with transparency, valid CRCs, inflatable", () => {
+ const img = new Img(2, 2);
+ img.set(0, 0, pack(255, 0, 0));
+ img.set(1, 1, pack(0, 0, 255, 128));
+ const c = chunks(encodePng(img));
+ assert.deepEqual(c.map((x) => x.type), ["IHDR", "PLTE", "tRNS", "IDAT", "IEND"]);
+ assert.ok(c.every((x) => x.crcOk));
+ assert.equal(inflateSync(c[3].data).length, 2 * 3);
+});
+
+test("png: RGBA when more than 256 colors", () => {
+ const img = new Img(20, 20);
+ for (let i = 0; i < 400; i++) img.data[i] = pack(i % 256, Math.floor(i / 256), 7);
+ const c = chunks(encodePng(img));
+ assert.equal(c[0].data[9], 6);
+ assert.equal(inflateSync(c.find((x) => x.type === "IDAT")!.data).length, 20 * (20 * 4 + 1));
+});
+
+function tmpArt(src: string): { dir: string; file: string } {
+ const dir = mkdtempSync(join(tmpdir(), "pxl-"));
+ const file = join(dir, "a.px.js");
+ writeFileSync(file, src);
+ return { dir, file };
+}
+
+test("cli build writes sprites, previews, layered exports and sheets", async () => {
+ const { dir, file } = tmpArt(`use("pico8")
+sprite("dot", { outline: "0" }, "8")
+sprite("lay", { w: 2, h: 1, layers: true }, layer("a", px(0, 0, "7")), layer("b", px(1, 0, "8")))
+sprite("_part", "7")
+sheet("all", ["*"], { pad: 1 })`);
+ const log = console.log;
+ const lines: string[] = [];
+ console.log = (s: string) => lines.push(s);
+ try { assert.equal(await main(["build", file]), 0); } finally { console.log = log; }
+ for (const p of ["sprites/dot.png", "sprites/lay.png", "sprites/lay/a.png", "sprites/lay/b.png", "_preview/dot.png", "all.png", "all.json"])
+ assert.ok(existsSync(join(dir, "out", p)), p);
+ assert.ok(!existsSync(join(dir, "out", "sprites", "_part.png")));
+ const json = JSON.parse(readFileSync(join(dir, "out", "all.json"), "utf8"));
+ assert.deepEqual(Object.keys(json.frames), ["dot", "lay"]);
+ assert.deepEqual(json.frames.dot.frame, { x: 0, y: 0, w: 3, h: 3 });
+ assert.ok(lines.some((l) => l.startsWith("sprite dot 3x3")));
+});
+
+test("cli build reports per-asset errors and still writes the rest", async () => {
+ const { dir, file } = tmpArt(`use("pico8")\nsprite("good", "8")\nsprite("bad", "z")`);
+ const err = console.error, log = console.log;
+ const errors: string[] = [];
+ console.error = (s: string) => errors.push(s);
+ console.log = () => {};
+ try { assert.equal(await main(["build", file]), 1); } finally { console.error = err; console.log = log; }
+ assert.ok(existsSync(join(dir, "out", "sprites", "good.png")));
+ assert.ok(errors.some((e) => e.includes("a.px.js:3:1") && e.includes("unknown color key 'z'")), errors.join("\n"));
+});
+
+test("server: state, asset frames, rebuild on change", async () => {
+ const { file } = tmpArt(`use("pico8")\nsprite("a", { w: 2, h: 1 }, px(0, 0, "8"), px(1, 0, "7"))`);
+ const logs: string[] = [];
+ const s = await serve(file, { port: 0, out: false, log: (l) => logs.push(l) });
+ try {
+ const state = await (await fetch(s.url + "api/state")).json();
+ assert.equal(state.assets[0].name, "a");
+ const a = await (await fetch(s.url + "api/asset?name=a")).json();
+ assert.deepEqual(a.frames.map((f: { label: string }) => f.label), ['px(0, 0, "8")', 'px(1, 0, "7")']);
+ assert.equal(a.frames[1].loc, "a.px.js:2:44");
+ const html = await (await fetch(s.url)).text();
+ assert.ok(html.includes("/app.js"));
+ const js = await (await fetch(s.url + "app.js")).text();
+ assert.ok(js.includes("EventSource") && !js.includes("interface AssetInfo"));
+
+ writeFileSync(file, `use("pico8")\nsprite("a", { w: 1, h: 1 }, px(0, 0, "9"))`);
+ const t0 = Date.now();
+ let v = 1;
+ while (Date.now() - t0 < 5000) {
+ await new Promise((r) => setTimeout(r, 100));
+ const st = await (await fetch(s.url + "api/state")).json();
+ v = st.version;
+ if (v > 1) {
+ assert.equal(st.assets[0].w, 1);
+ assert.equal(st.assets[0].edited, true);
+ break;
+ }
+ }
+ assert.ok(v > 1, "rebuild did not happen");
+ } finally {
+ s.close();
+ }
+});
diff --git a/test/normals.test.ts b/test/normals.test.ts
new file mode 100644
index 0000000..350c06a
--- /dev/null
+++ b/test/normals.test.ts
@@ -0,0 +1,80 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { failure, PAL } from "./helpers.ts";
+import { loadSource } from "../src/node/load.ts";
+import { normalImage } from "../src/core/normals.ts";
+
+const load = (body: string) => loadSource(PAL + body, "t.px.js");
+/** Normal x/y of a pixel as signs (-1, 0, 1); null when it has none. */
+const dir = (p: ReturnType<typeof load>, name: string, x: number, y: number) => {
+ const img = p.image(name), i = y * img.w + x, n = img.norm;
+ if (!n || n[i * 3 + 2] === 0) return null;
+ return [Math.sign(n[i * 3]), Math.sign(n[i * 3 + 1])];
+};
+
+test("bump: bevel slopes edges outward and leaves the top flat; dome peaks in the middle", () => {
+ const p = load(`
+sprite("b", { w: 8, h: 8 }, rect(0, 0, 8, 8, "w"), bump("bevel", { w: 2 }))
+sprite("d", { w: 9, h: 9 }, circ(4, 4, 4, "w"), bump("dome"))`);
+ assert.deepEqual(dir(p, "b", 0, 4), [-1, 0], "left edge faces left");
+ assert.deepEqual(dir(p, "b", 4, 7), [0, 1], "bottom edge faces down");
+ assert.deepEqual(dir(p, "b", 4, 4), [0, 0], "top is flat");
+ assert.deepEqual(dir(p, "d", 4, 4), [0, 0]);
+ assert.deepEqual(dir(p, "d", 8, 4), [1, 0]);
+ assert.deepEqual(dir(p, "d", 4, 0), [0, -1]);
+});
+
+test("bump: `on` keys bevel each region separately", () => {
+ const p = load(`sprite("s", { w: 9, h: 3 }, rect(0, 0, 9, 3, "r"), vline(4, 0, 3, "k"), bump("bevel", { on: "r", w: 1 }))`);
+ assert.deepEqual(dir(p, "s", 3, 1), [1, 0], "brick edge next to the mortar faces it");
+ assert.deepEqual(dir(p, "s", 5, 1), [-1, 0]);
+ assert.equal(dir(p, "s", 4, 1), null, "mortar gets no normal");
+});
+
+test("normals: numpad grid; flips, rotations and mirroring turn the normals with the pixels", () => {
+ const p = load(`
+sprite("a", "rr", normals(0, 0, "69"))
+sprite("fx", { base: "a", flip: "x" })
+sprite("r90", { base: "a", rot: 90 })
+sprite("m", { mx: true }, "r", normals(0, 0, "4"))`);
+ assert.deepEqual(dir(p, "a", 0, 0), [1, 0]);
+ assert.deepEqual(dir(p, "a", 1, 0), [1, -1]);
+ assert.deepEqual(dir(p, "fx", 1, 0), [-1, 0]);
+ assert.deepEqual(dir(p, "fx", 0, 0), [-1, -1]);
+ assert.deepEqual(dir(p, "r90", 0, 0), [0, 1], "right turns to down");
+ assert.deepEqual(dir(p, "m", 1, 0), [1, 0], "mirrored half faces the other way");
+ assert.match(failure(PAL + 'sprite("x", "r", normals(0, 0, "Z"))', "x").message, /unknown direction 'Z'.*row 0, col 0/);
+});
+
+test("normals: stamped art carries them; flat art drawn over clears them", () => {
+ const p = load(`
+sprite("n", "r", normals(0, 0, "6"))
+scene("s", { w: 4, h: 1 }, stamp("n", 1, 0), stamp("n", 2, 0, { flip: "x" }), stamp("n", 3, 0), px(3, 0, "w"))`);
+ assert.deepEqual(dir(p, "s", 1, 0), [1, 0]);
+ assert.deepEqual(dir(p, "s", 2, 0), [-1, 0]);
+ assert.deepEqual(dir(p, "s", 3, 0), [1, 0], "ops on the same canvas keep the normals under them");
+ const q = load(`
+sprite("n", "r", normals(0, 0, "6"))
+scene("s", { w: 2, h: 1 }, stamp("n", 0, 0), layer("top", px(0, 0, "w")))`);
+ assert.equal(dir(q, "s", 0, 0), null, "a flat layer on top clears them");
+});
+
+test("lighting: surfaces facing the lamp get brighter, facing away darker, flat unchanged; relief 0 ignores normals", () => {
+ const src = (relief: number) => `
+scene("s", { w: 20, h: 1, bg: "w" }, normals(8, 0, "456"), lamp(0, 0, { r: 40, z: 4 }), lighting({ cell: 1, relief: ${relief} }))
+scene("ref", { w: 20, h: 1, bg: "w" }, lamp(0, 0, { r: 40, z: 4 }), lighting({ cell: 1 }))`;
+ const p = load(src(1)), red = (q: typeof p, name: string, x: number) => q.image(name).get(x, 0) >>> 24;
+ assert.ok(red(p, "s", 8) > red(p, "ref", 8), "facing the lamp (4 = left) is brighter");
+ assert.ok(red(p, "s", 10) < red(p, "ref", 10), "facing away is darker");
+ assert.ok(Math.abs(red(p, "s", 9) - red(p, "ref", 9)) <= 1, "flat normal matches unmapped art");
+ const off = load(src(0));
+ for (const x of [8, 9, 10]) assert.equal(red(off, "s", x), red(off, "ref", x));
+});
+
+test("normal map image: engine encoding with green up, flat where unset", () => {
+ const p = load(`sprite("a", "rrr", normals(0, 0, "8.."))`);
+ const img = normalImage(p.image("a"));
+ const [r, g, b] = [img.get(0, 0) >>> 24, (img.get(0, 0) >>> 16) & 255, (img.get(0, 0) >>> 8) & 255];
+ assert.ok(g > 200 && Math.abs(r - 128) <= 1 && b > 128, "up-facing is green");
+ assert.equal(img.get(1, 0) >>> 8, (128 << 16) | (128 << 8) | 255, "unset = flat");
+});
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..70e5254
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,18 @@
+{
+ "compilerOptions": {
+ "target": "es2023",
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "lib": ["es2023", "dom"],
+ "types": ["node"],
+ "strict": true,
+ "noEmit": true,
+ "allowImportingTsExtensions": true,
+ "erasableSyntaxOnly": true,
+ "verbatimModuleSyntax": true,
+ "noUncheckedIndexedAccess": false,
+ "noImplicitOverride": true,
+ "skipLibCheck": true
+ },
+ "include": ["src", "test", "types"]
+}
diff --git a/types/pxl.d.ts b/types/pxl.d.ts
new file mode 100644
index 0000000..a418b4e
--- /dev/null
+++ b/types/pxl.d.ts
@@ -0,0 +1,132 @@
+// Editor support for art files. In a .px.ts file add:
+// /// <reference path="<pxl>/types/pxl.d.ts" />
+// The DSL functions are globals while an art file runs.
+export {};
+
+declare global {
+ type PxColor = string;
+ type PxRegion = undefined | null | number[] | ((x: number, y: number) => boolean);
+ interface PxOp { readonly __op: true }
+ interface PxLayer { readonly __layer: true }
+ type PxItem = string | PxOp | PxLayer | ((c: PxCanvas) => void);
+
+ interface PxPlace {
+ flip?: "x" | "y" | "xy"; rot?: 90 | 180 | 270; swap?: Record<string, PxColor>;
+ rflip?: "x" | "y" | "xy"; rswap?: Record<string, PxColor>[]; seed?: number; reseed?: boolean | number;
+ /** Animated assets: freeze on frame n / start later (ms) / random start. */
+ frame?: number; delay?: number; rdelay?: boolean;
+ }
+ interface PxScatter extends PxPlace { on?: string; clip?: boolean; below?: boolean }
+ interface PxTilemap extends PxPlace { map: Record<string, string>; size?: number; w?: number; h?: number; x?: number; y?: number }
+ interface PxWire extends PxPlace { hang?: string; every?: number; start?: number }
+ interface PxText { scale?: number; gap?: number; lead?: number; align?: "l" | "c" | "r"; shadow?: PxColor }
+ interface PxAssetOpts {
+ w?: number; h?: number; base?: string; mx?: boolean | "c"; my?: boolean | "c"; swap?: Record<string, PxColor>;
+ flip?: "x" | "y" | "xy"; rot?: 90 | 180 | 270; outline?: PxColor; outline8?: PxColor; crop?: boolean; layers?: boolean;
+ }
+ interface PxSceneOpts extends PxAssetOpts { w: number; h: number; bg?: PxColor }
+ interface PxAnimOpts extends PxAssetOpts { fps?: number; frames?: number; loop?: boolean }
+ interface PxFrame { ms?: number; hold?: number }
+ interface PxLayerOpts {
+ x?: number; y?: number; hidden?: boolean; density?: number; solid?: boolean; wall?: boolean; unlit?: boolean;
+ shade?: boolean | number | Record<string, PxColor>; light?: boolean | number | Record<string, PxColor>;
+ }
+
+ interface PxLamp { r?: number; color?: PxColor; power?: number; z?: number }
+ interface PxBump { w?: number; depth?: number; on?: string; where?: PxRegion }
+ type PxBumpShape = "dome" | "bevel" | "luma";
+ interface PxLighting {
+ cell?: number; ambient?: number; ambientColor?: PxColor; sky?: number; skyColor?: PxColor; skyReach?: number;
+ block?: number; smooth?: boolean; emit?: string; shape?: "round" | "diamond";
+ relief?: number; skyDir?: [number, number];
+ }
+ interface PxGlow { where?: PxRegion; r?: number; strength?: number; color?: PxColor; bands?: number; ramp?: number }
+
+ interface PxCanvas {
+ readonly w: number; readonly h: number; readonly seed: number;
+ /** Time in ms; inside an anim also the frame index, frame count and frame / frames. */
+ readonly t: number; readonly frame: number; readonly frames: number; readonly phase: number;
+ is(x: number, y: number, keys: string): boolean;
+ key(x: number, y: number): string;
+ get(x: number, y: number): number;
+ rng(seed?: number): () => number;
+ clip(where: PxRegion, fn: () => void): void;
+ px(x: number, y: number, c: PxColor): void;
+ rect(x: number, y: number, w: number, h: number, c: PxColor): void;
+ box(x: number, y: number, w: number, h: number, c: PxColor): void;
+ line(x0: number, y0: number, x1: number, y1: number, c: PxColor, width?: number): void;
+ hline(x: number, y: number, len: number, c: PxColor): void;
+ vline(x: number, y: number, len: number, c: PxColor): void;
+ circ(cx: number, cy: number, r: number, c: PxColor): void;
+ ring(cx: number, cy: number, r: number, c: PxColor): void;
+ ellipse(cx: number, cy: number, rx: number, ry: number, c: PxColor, ring?: boolean): void;
+ poly(points: number[], c: PxColor): void;
+ fill(x: number, y: number, c: PxColor): void;
+ dither(x: number, y: number, w: number, h: number, c1: PxColor, c2: PxColor, density?: number): void;
+ grad(x: number, y: number, w: number, h: number, colors: string | string[], dir?: "v" | "h", soft?: number): void;
+ noise(x: number, y: number, w: number, h: number, colors: string | string[], density?: number, seed?: number, on?: string): void;
+ shade(where?: PxRegion, steps?: number, density?: number): void;
+ light(where?: PxRegion, steps?: number, density?: number): void;
+ recolor(map: Record<string, PxColor>, where?: PxRegion, density?: number): void;
+ stamp(name: string, x?: number, y?: number, opts?: PxPlace): void;
+ tile(name: string, x: number, y: number, cols?: number, rows?: number, opts?: PxPlace): void;
+ pattern(name: string, x: number, y: number, w: number, h: number, opts?: PxPlace): void;
+ tilemap(map: string, opts: PxTilemap): void;
+ scatter(name: string, x: number, y: number, w: number, h: number, count: number, opts?: PxScatter): void;
+ grid(x: number, y: number, str: string): void;
+ wire(x0: number, y0: number, x1: number, y1: number, sag: number, c: PxColor, opts?: PxWire): void;
+ text(x: number, y: number, str: string | number, c: PxColor, opts?: PxText): void;
+ lamp(x: number, y: number, opts?: PxLamp): void;
+ bump(shape?: PxBumpShape, opts?: PxBump): void;
+ normals(x: number, y: number, str: string): void;
+ }
+
+ function use(palette: "pico8" | "sweetie16" | "db16" | "endesga32" | "gray8" | (string | number)[]): void;
+ function pal(keys: Record<string, string | number>): void;
+ function ramps(...darkToLight: string[]): void;
+ function sprite(name: string, opts: PxAssetOpts, ...items: PxItem[]): void;
+ function sprite(name: string, ...items: PxItem[]): void;
+ function scene(name: string, opts: PxSceneOpts, ...items: PxItem[]): void;
+ function anim(name: string, opts: PxAnimOpts, ...items: PxItem[]): void;
+ function anim(name: string, ...items: PxItem[]): void;
+ function frame(opts: PxFrame, ...items: PxItem[]): PxOp;
+ function frame(...items: PxItem[]): PxOp;
+ function layer(name: string, opts: PxLayerOpts, ...items: PxItem[]): PxLayer;
+ function layer(name: string, ...items: PxItem[]): PxLayer;
+ function group(name: string, members: string[]): void;
+ function sheet(name: string, entries: string[], opts?: { cols?: number; pad?: number }): void;
+ function include(path: string): void;
+ function rng(seed?: number): () => number;
+ function clip(where: PxRegion, ...items: PxItem[]): PxOp;
+
+ function px(x: number, y: number, c: PxColor): PxOp;
+ function rect(x: number, y: number, w: number, h: number, c: PxColor): PxOp;
+ function box(x: number, y: number, w: number, h: number, c: PxColor): PxOp;
+ function line(x0: number, y0: number, x1: number, y1: number, c: PxColor, width?: number): PxOp;
+ function hline(x: number, y: number, len: number, c: PxColor): PxOp;
+ function vline(x: number, y: number, len: number, c: PxColor): PxOp;
+ function circ(cx: number, cy: number, r: number, c: PxColor): PxOp;
+ function ring(cx: number, cy: number, r: number, c: PxColor): PxOp;
+ function ellipse(cx: number, cy: number, rx: number, ry: number, c: PxColor, ring?: boolean): PxOp;
+ function poly(points: number[], c: PxColor): PxOp;
+ function fill(x: number, y: number, c: PxColor): PxOp;
+ function dither(x: number, y: number, w: number, h: number, c1: PxColor, c2: PxColor, density?: number): PxOp;
+ function grad(x: number, y: number, w: number, h: number, colors: string | string[], dir?: "v" | "h", soft?: number): PxOp;
+ function noise(x: number, y: number, w: number, h: number, colors: string | string[], density?: number, seed?: number, on?: string): PxOp;
+ function shade(where?: PxRegion, steps?: number, density?: number): PxOp;
+ function light(where?: PxRegion, steps?: number, density?: number): PxOp;
+ function recolor(map: Record<string, PxColor>, where?: PxRegion, density?: number): PxOp;
+ function stamp(name: string, x?: number, y?: number, opts?: PxPlace): PxOp;
+ function tile(name: string, x: number, y: number, cols?: number, rows?: number, opts?: PxPlace): PxOp;
+ function pattern(name: string, x: number, y: number, w: number, h: number, opts?: PxPlace): PxOp;
+ function tilemap(map: string, opts: PxTilemap): PxOp;
+ function scatter(name: string, x: number, y: number, w: number, h: number, count: number, opts?: PxScatter): PxOp;
+ function grid(x: number, y: number, str: string): PxOp;
+ function wire(x0: number, y0: number, x1: number, y1: number, sag: number, c: PxColor, opts?: PxWire): PxOp;
+ function text(x: number, y: number, str: string | number, c: PxColor, opts?: PxText): PxOp;
+ function lamp(x: number, y: number, opts?: PxLamp): PxOp;
+ function bump(shape?: PxBumpShape, opts?: PxBump): PxOp;
+ function normals(x: number, y: number, str: string): PxOp;
+ function lighting(opts?: PxLighting): PxOp;
+ function glow(keys: string | string[], opts?: PxGlow): PxOp;
+}