diff --git a/bun.lock b/bun.lock index b55fe49..0cf2b28 100644 --- a/bun.lock +++ b/bun.lock @@ -50,6 +50,7 @@ }, "devDependencies": { "@biomejs/biome": "^1.9.4", + "@types/bun": "^1.3.14", "typescript": "^5.6.3", "vite": "^5.4.10", "vite-plugin-wasm": "^3.3.0", @@ -277,6 +278,8 @@ "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.4", "", { "os": "win32", "cpu": "x64" }, "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q=="], + "@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + "@types/earcut": ["@types/earcut@3.0.0", "", {}, "sha512-k/9fOUGO39yd2sCjrbAJvGDEQvRwRnQIZlBz43roGwUZo5SHAmyVvSFyaVVZkicRVCaDXPKlbxrUcBuJoSWunQ=="], "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], @@ -299,6 +302,8 @@ "bullmq": ["bullmq@5.81.3", "", { "dependencies": { "cron-parser": "4.9.0", "ioredis": "5.11.1", "msgpackr": "2.0.5", "node-abort-controller": "3.1.1", "semver": "7.8.5", "tslib": "2.8.1" }, "peerDependencies": { "redis": ">=5.0.0" }, "optionalPeers": ["redis"] }, "sha512-Q7uEH2G92rVjX3Yl2qw3+6VEO15uxehC6DfeTHQBQTehddcRDSDuquD9zuvDjxiCffXsPUaBwrRlvlbVcgKs7g=="], + "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], + "cjs-module-lexer": ["cjs-module-lexer@1.4.3", "", {}, "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q=="], "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], diff --git a/docs/adr/0009-textures-are-text.md b/docs/adr/0009-textures-are-text.md new file mode 100644 index 0000000..e495e26 --- /dev/null +++ b/docs/adr/0009-textures-are-text.md @@ -0,0 +1,146 @@ +# 9. Textures are text, and the browser is the only parser + +Status: proposed + +## Context + +Every visual in `web/` today is a vector drawn at runtime with pixi.js +`Graphics` — `drawBuilding` (`main.ts:225`) hand-codes roof polygons per +building, and pips are circles (`main.ts:473`). There is no bitmap art +anywhere in the project and no pipeline for adding any. That has worked +because there has been exactly one building type worth drawing; the service +map already lists farm and tavern as built and "the rest is the plan" for +workplaces, and each new one currently means someone hand-writing more +polygon code. + +That does not scale, and not primarily for a performance reason. An agent +working in this repo can generate and edit text fluently and cannot produce +raster art at all — no eyes, no mouse, no Aseprite. A binary sprite (PNG, +texture atlas) dropped into a PR is also unreviewable the way the rest of +this codebase is reviewable: it does not diff, a reviewer cannot read *what +changed* from the diff, and git cannot merge two edits to it. The project +already treats "can this be reviewed as text" as load-bearing — `proto/` for +contracts, the event log for world history — and rendering assets are the +one visual surface still outside that discipline. + +The want is concrete: a workplace or pip should be able to ship a distinct, +textured look — grass, wood grain, ale foam, an idle-vs-working animation — +authored the same way an agent authors everything else here, and reviewed +the same way. + +## Decision + +### 1. A texture is a plain-text grid, with a palette header + +A monospace character grid, one line per row, preceded by a header mapping +each character to a color: + +``` +palette + . #00000000 + g #4a7c2f + G #5c9636 +grid + ..gg.. + .gGGg. + ..gg.. +``` + +Any character not declared in the palette is a format error, not a +transparent-by-default pixel — an agent that mistypes a glyph should get a +loud failure, not a silently wrong texture. + +### 2. Animation is multiple frames in one file, not multiple files + +A second section, `frames`, holds an ordered list of grids and an `fps`. +One texture — one visual concept ("tavern, idle") — stays one file whether +it is static or animated, so a diff that adds motion to an existing texture +is a diff to one file, not a rename plus new siblings. + +### 3. One parser, one owner: `web/src` + +The grid is parsed to an off-screen ``, one filled rect per cell, +then handed to pixi as a `Texture`. Nothing outside `web/` ever reads this +format. This is not a contract between services — no `.proto`, no `gen/` — +because it carries no simulation semantics: `sim-core` does not know a +building has a roof texture, only that it is a building. Keeping a second +parser anywhere (say, a native client down the line) would be the same +mistake rule 4 forbids for domain rules, for a different reason: a format +with two readers drifts, and a rendering glitch becomes a cross-language bug +hunt instead of a one-file fix. + +### 4. Cell size is a render-time constant, not baked into the file + +A texture file declares a grid, not a pixel size. `web/src` decides how many +device pixels a cell occupies, so the same tavern texture can be drawn at +different zoom levels or a future minimap without a second asset. + +### 5. Files live under `web/assets/textures/`, validated like code + +`{building-or-pip}.{state}.txt`, e.g. `tavern.idle.txt`, +`tavern.working.txt`, `pip.walking.txt`. No manifest service, no registry — +the loader lists the directory. A test wired into `web`'s `make test` (bun +test) rejects a malformed file before it reaches the renderer: non-rectangular +rows, a glyph missing from its palette, or animation frames whose dimensions +disagree with each other. The same bar `make proto-lint` holds contracts to — +a bad file fails the build, not the demo. + +## Why not real bitmap assets (PNG / Aseprite / a sprite sheet) + +The obvious alternative, and rejected for the reason this ADR exists: an +agent cannot produce or meaningfully edit one, and it does not diff. This +project would still need a human artist, which defeats the point of a +generative pipeline agents can drive end to end. + +## Why not procedural/shader-generated textures (noise, WGSL) + +More expressive, and premature. There is no shader stage in the renderer +today — pixi is being used purely through `Graphics` — and the actual need +right now is "give ten building types a distinguishable look an agent can +author," not photorealism. Nothing here forecloses adding shaders later; it +just is not the next thing to build. + +## Why not keep pure vector polygons + +Fine for a building's silhouette — the roof math in `drawBuilding` is not +going away — but it does not extend to surface detail (grass texture, wood +grain, foam) without every such detail becoming more hand-written polygon +code per building type. Text grids and vector shapes are complementary, not +competing: a building keeps its polygon frame and gains a texture fill. + +## Why not a shared package parsed by more than one client + +There is exactly one client (`web/`). A shared `pips/textures` package +parsed by both a hypothetical native client and the browser is solving a +problem that does not exist yet — add it the day a second consumer does. + +## Consequences + +- `web/src` gains a parser module and a canvas-to-`Texture` conversion; small, + but it is new surface area with its own tests. +- Texture count grows per building/pip state, and per animation — the + filename convention (`{subject}.{state}.txt`) is the only index; if that + stops being enough (states composing, e.g. "working + injured"), revisit + before it grows organically into an unreadable naming scheme. +- Pixel-art-scale rendering is now a deliberate style, not a placeholder to + be embarrassed about. Later polish should stay inside that constraint — + sharper cells, better palettes — rather than quietly mixing in traditional + art assets, which would bring back the diffability problem this ADR exists + to avoid. +- `web/` needs its own `CLAUDE.md` (every other service has one) documenting + the format for an agent that is about to author a texture, since the spec + lives in this ADR and an ADR is not where an agent should have to look + mid-task. + +## Next steps + +1. Write the format spec precisely (header syntax, `frames`/`fps` syntax, + escaping) as `web/assets/textures/FORMAT.md` — this ADR sets the shape, + not the grammar. +2. `web/src/textures.ts` — parser, validator, canvas/`Texture` conversion. +3. A validation test in `web` wired into `make test`, covering the failure + modes in decision §5. +4. Convert one existing procedural asset (the tavern's wall face is the + smallest useful target) to prove the pipeline before touching the rest. +5. Add `web/CLAUDE.md` documenting the convention for agents authoring new + textures. diff --git a/web/CLAUDE.md b/web/CLAUDE.md new file mode 100644 index 0000000..ca7405b --- /dev/null +++ b/web/CLAUDE.md @@ -0,0 +1,45 @@ +# web + +The browser client. Connects to `world-gateway` over Connect (see ADR 0003), +renders the world with pixi.js in 2:1 isometric projection, and runs the same +WASM build of `sim-core` locally for client-side prediction — see the header +comment in `src/main.ts` before touching the render loop. + +## Textures + +ADR 0009: sprite/roof textures are plain text, not binary images, so an agent +can author or edit one directly. The grammar is `assets/textures/FORMAT.md`; +`src/textures.ts` is the only parser and the only place that format should +ever be read from — don't write a second reader. + +Quick shape: + +``` +palette + . #00000000 + g #4a7c2f +grid + .g. + ggg + .g. +``` + +- One file per `{subject}.{state}`, e.g. `tavern.idle.txt`. No manifest — the + loader in `main.ts` globs `assets/textures/*.txt` at build time + (`import.meta.glob`). +- Every glyph used in `grid`/`frames` must have a `palette` entry, or parsing + fails loudly. That is deliberate — a malformed texture should error, not + silently render a hole. +- `frames fps=N` replaces `grid` for an animation; frames must all share one + file's dimensions. +- `parseTexture`/`frameToCanvas`/`texturesFromParsed` in `src/textures.ts` are + plain functions with no pixi or DOM globals at module scope, so + `textures.test.ts` runs under `bun test` without a browser. Keep it that + way — if a change needs `document` or a pixi import at module load time, + it belongs in `main.ts`, not `textures.ts`. +- Cell size (pixels per glyph) is chosen at the call site in `main.ts`, not + stored in the file — the same texture can render at different zoom levels. + +Before shipping a new texture, run `bun test` (validates every file under +`assets/textures/`) and look at it in the running app — a texture that +parses can still look wrong at the chosen cell size. diff --git a/web/assets/textures/FORMAT.md b/web/assets/textures/FORMAT.md new file mode 100644 index 0000000..b1a467f --- /dev/null +++ b/web/assets/textures/FORMAT.md @@ -0,0 +1,62 @@ +# Texture format + +See ADR 0009 for why this exists. This is the grammar. + +A texture file is plain text, split into sections by lines that name the +section: `palette`, then either `grid` (static) or `frames` (animated). +Leading/trailing blank lines and `#`-comment lines are ignored. + +## `palette` + +One glyph-to-color mapping per line, indented, glyph then a CSS hex color: + +``` +palette + . #00000000 + g #4a7c2f + G #5c9636 +``` + +- The glyph is exactly one character. Whitespace cannot be a glyph — use a + dedicated character (conventionally `.`) for "empty". +- Colors are `#rrggbb` or `#rrggbbaa`. `#00000000` is fully transparent. +- Every glyph used anywhere in `grid` or `frames` below must appear here. + An unknown glyph is a parse error, not a transparent pixel. + +## `grid` (static texture) + +``` +grid + ..gg.. + .gGGg. + ..gg.. +``` + +Every row must have the same length. A ragged grid is a parse error. + +## `frames` (animation) + +``` +frames fps=4 + --- 0 --- + ..gg.. + .gGGg. + ..gg.. + --- 1 --- + ..GG.. + .Ggga. + ..GG.. +``` + +- `frames` takes one required key: `fps`, an integer greater than 0. +- Each frame starts with a `--- ---` marker, indices `0..n-1` in + order. The marker is discarded; the index is documentation, not read back. +- Every frame's grid must have the same dimensions as the first frame. A + texture that grows or shrinks mid-animation is a parse error. + +A file has exactly one of `grid` or `frames`, never both. + +## Naming and location + +`web/assets/textures/{subject}.{state}.txt`, e.g. `tavern.idle.txt`, +`pip.walking.txt`. The loader lists the directory; there is no manifest. diff --git a/web/assets/textures/roof.shingle.txt b/web/assets/textures/roof.shingle.txt new file mode 100644 index 0000000..287f9e8 --- /dev/null +++ b/web/assets/textures/roof.shingle.txt @@ -0,0 +1,17 @@ +# The roof fill for drawBuilding(), replacing the flat #3d4a60 with a shingled +# texture. Colors are picked to sit inside the existing building palette +# (see main.ts: 0x3d4a60 base, 0x2b3444/0x212938 walls, 0x5b6b86 stroke). +palette + . #3d4a60 + o #2f3a4c + H #5b6b86 + +grid + HHHHHHHH + H......o + o......o + oooooooo + o......o + o......o + oooooooo + o......o diff --git a/web/package.json b/web/package.json index 352841d..ab2c37d 100644 --- a/web/package.json +++ b/web/package.json @@ -17,6 +17,7 @@ }, "devDependencies": { "@biomejs/biome": "^1.9.4", + "@types/bun": "^1.3.14", "typescript": "^5.6.3", "vite": "^5.4.10", "vite-plugin-wasm": "^3.3.0" diff --git a/web/src/main.ts b/web/src/main.ts index ecf5be1..48ea86e 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -15,14 +15,35 @@ * itself, which keeps the renderer developable without a cluster. */ -import { Application, Container, Graphics, Text } from "pixi.js"; +import { Application, Container, Graphics, Text, type Texture } from "pixi.js"; import init, { SimHandle, pip_stride, workplace_stride, } from "./sim-wasm/sim_wasm.js"; +import { parseTexture, texturesFromParsed } from "./textures"; import { type WorldClient, connect, join, streamDeltas } from "./world"; +/** + * Every `.txt` under `assets/textures/`, inlined at build time. ADR 0009: + * these are agent-authored text files, not binary assets, so a build-time + * glob is enough — there is no server to list a directory against. + */ +const TEXTURE_SOURCES = import.meta.glob("../assets/textures/*.txt", { + query: "?raw", + import: "default", + eager: true, +}) as Record; + +/** Rasterizes a shipped texture file, keyed by filename, at `cellPx` per glyph. */ +function loadTexture(fileName: string, cellPx: number): Texture[] { + const path = Object.keys(TEXTURE_SOURCES).find((p) => + p.endsWith(`/${fileName}`), + ); + if (!path) throw new Error(`texture not found: ${fileName}`); + return texturesFromParsed(parseTexture(TEXTURE_SOURCES[path]), cellPx); +} + // --- world constants -------------------------------------------------------- const MILLI_PER_TILE = 1000; @@ -222,7 +243,7 @@ const isoDepth = (tileX: number, tileY: number) => tileX + tileY; * Redrawn each tick rather than tinted, because `occupants` changes and Pixi's * Graphics has no cheap way to resize a filled rectangle in place. */ -function drawBuilding(g: Graphics, b: Building) { +function drawBuilding(g: Graphics, b: Building, roofTexture: Texture) { const cx = toTile(b.x); const cy = toTile(b.y); const h = BUILDING_TILES / 2; @@ -242,7 +263,7 @@ function drawBuilding(g: Graphics, b: Building) { // door: it is exactly the position the core walks pips to. g.poly([roof[3], roof[2], corners[2], corners[3]]).fill({ color: 0x2b3444 }); g.poly([roof[2], roof[1], corners[1], corners[2]]).fill({ color: 0x212938 }); - g.poly(roof).fill({ color: 0x3d4a60 }); + g.poly(roof).fill({ texture: roofTexture }); g.poly(roof).stroke({ color: 0x5b6b86, width: 1 }); // Occupancy, as a band rising up the left wall. @@ -285,6 +306,10 @@ function drawGrid(parent: Container) { async function main() { await init(); + // 4px per glyph: roof.shingle.txt is 8x8, so this lands at 32x32 — the same + // scale as ISO_TILE_W, close enough that the shingle rows read at this zoom. + const [roofTexture] = loadTexture("roof.shingle.txt", 4); + const app = new Application(); await app.init({ background: "#11131a", resizeTo: window, antialias: true }); document.body.appendChild(app.canvas); @@ -449,7 +474,7 @@ async function main() { blocks.set(id, block); } - drawBuilding(block.body, b); + drawBuilding(block.body, b, roofTexture); const centre = isoProject(toTile(b.x), toTile(b.y)); block.label.position.set( centre.x, diff --git a/web/src/textures.test.ts b/web/src/textures.test.ts new file mode 100644 index 0000000..e99be09 --- /dev/null +++ b/web/src/textures.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, test } from "bun:test"; +import { readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; +import { TextureFormatError, parseTexture } from "./textures"; + +const TEXTURES_DIR = join(import.meta.dir, "..", "assets", "textures"); + +const VALID_STATIC = ` +palette + . #00000000 + g #4a7c2f +grid + .g. + ggg + .g. +`; + +const VALID_ANIMATED = ` +palette + . #00000000 + g #4a7c2f +frames fps=4 + --- 0 --- + .g + g. + --- 1 --- + g. + .g +`; + +describe("parseTexture", () => { + test("parses a static grid", () => { + const parsed = parseTexture(VALID_STATIC); + expect(parsed.kind).toBe("static"); + if (parsed.kind !== "static") return; + expect(parsed.width).toBe(3); + expect(parsed.height).toBe(3); + expect(parsed.palette.get("g")).toBe("#4a7c2f"); + }); + + test("parses animated frames in fps order", () => { + const parsed = parseTexture(VALID_ANIMATED); + expect(parsed.kind).toBe("animated"); + if (parsed.kind !== "animated") return; + expect(parsed.fps).toBe(4); + expect(parsed.frames).toHaveLength(2); + expect(parsed.width).toBe(2); + expect(parsed.height).toBe(2); + }); + + test("rejects a ragged grid", () => { + const source = ` +palette + . #000000 + g #4a7c2f +grid + .g. + gg +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects a glyph missing from the palette", () => { + const source = ` +palette + . #000000 +grid + .x. +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects an animation frame with mismatched dimensions", () => { + const source = ` +palette + . #000000 + g #4a7c2f +frames fps=2 + --- 0 --- + .g + g. + --- 1 --- + .g. + g.. +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects out-of-order frame markers", () => { + const source = ` +palette + . #000000 +frames fps=2 + --- 0 --- + . + --- 2 --- + . +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects fps=0", () => { + const source = ` +palette + . #000000 +frames fps=0 + --- 0 --- + . +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects a missing grid/frames section", () => { + const source = ` +palette + . #000000 +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects a palette glyph longer than one character", () => { + const source = ` +palette + gg #000000 +grid + gg +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); + + test("rejects a malformed color", () => { + const source = ` +palette + . red +grid + . +`; + expect(() => parseTexture(source)).toThrow(TextureFormatError); + }); +}); + +describe("shipped texture assets", () => { + test("every file under assets/textures/ parses", async () => { + const entries = await readdir(TEXTURES_DIR); + const textureFiles = entries.filter((name) => name.endsWith(".txt")); + expect(textureFiles.length).toBeGreaterThan(0); + for (const name of textureFiles) { + const source = await readFile(join(TEXTURES_DIR, name), "utf8"); + expect(() => parseTexture(source), name).not.toThrow(); + } + }); +}); diff --git a/web/src/textures.ts b/web/src/textures.ts new file mode 100644 index 0000000..d16dce5 --- /dev/null +++ b/web/src/textures.ts @@ -0,0 +1,213 @@ +/** + * Parser for the text texture format (ADR 0009, `assets/textures/FORMAT.md`). + * + * This is the one place in the project allowed to read that format — keeping + * a second reader anywhere else would let the two drift, the same failure + * mode rule 4 forbids for domain rules, applied here to a rendering asset + * format instead of a simulation one. + */ + +import { Texture } from "pixi.js"; + +export type Palette = Map; + +export type ParsedTexture = + | { + kind: "static"; + palette: Palette; + width: number; + height: number; + grid: string[]; + } + | { + kind: "animated"; + palette: Palette; + width: number; + height: number; + fps: number; + frames: string[][]; + }; + +export class TextureFormatError extends Error {} + +function fail(message: string): never { + throw new TextureFormatError(message); +} + +const COLOR_RE = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; +const FRAMES_HEADER_RE = /^frames\s+fps=(\d+)$/; +const FRAME_MARKER_RE = /^---\s+(\d+)\s+---$/; + +/** + * Parses one texture file's contents. Throws `TextureFormatError` on any + * malformed input — a texture an agent got wrong should fail loudly at parse + * time, not render as a wrong-looking sprite. + */ +export function parseTexture(source: string): ParsedTexture { + const lines = source + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0 && !line.startsWith("#")); + + if (lines[0] !== "palette") { + fail( + `expected "palette" as the first section, got ${JSON.stringify(lines[0] ?? "")}`, + ); + } + + const palette: Palette = new Map(); + let i = 1; + while ( + i < lines.length && + lines[i] !== "grid" && + !lines[i].startsWith("frames") + ) { + const line = lines[i]; + const spaceAt = line.indexOf(" "); + if (spaceAt < 0) fail(`malformed palette entry: ${JSON.stringify(line)}`); + const glyph = line.slice(0, spaceAt); + const color = line.slice(spaceAt + 1).trim(); + if (glyph.length !== 1) { + fail( + `palette glyph must be exactly one character: ${JSON.stringify(glyph)}`, + ); + } + if (!COLOR_RE.test(color)) { + fail( + `palette color must be #rrggbb or #rrggbbaa, got ${JSON.stringify(color)}`, + ); + } + palette.set(glyph, color); + i++; + } + if (palette.size === 0) fail("palette section is empty"); + if (i >= lines.length) fail('missing "grid" or "frames" section'); + + const checkGlyphs = (row: string) => { + for (const ch of row) { + if (!palette.has(ch)) + fail(`glyph ${JSON.stringify(ch)} is not in the palette`); + } + }; + + if (lines[i] === "grid") { + const grid = lines.slice(i + 1); + if (grid.length === 0) fail("grid section is empty"); + const width = grid[0].length; + for (const row of grid) { + if (row.length !== width) { + fail( + `grid rows must all have the same width (expected ${width}, got ${row.length}: ${JSON.stringify(row)})`, + ); + } + checkGlyphs(row); + } + return { kind: "static", palette, width, height: grid.length, grid }; + } + + const framesHeader = FRAMES_HEADER_RE.exec(lines[i]); + if (!framesHeader) + fail(`malformed section header: ${JSON.stringify(lines[i])}`); + const fps = Number(framesHeader[1]); + if (!(fps > 0)) fail(`fps must be greater than 0, got ${fps}`); + + const frames: string[][] = []; + let j = i + 1; + let expectedIndex = 0; + while (j < lines.length) { + const marker = FRAME_MARKER_RE.exec(lines[j]); + if (!marker) { + fail( + `expected frame marker "--- ${expectedIndex} ---", got ${JSON.stringify(lines[j])}`, + ); + } + const idx = Number(marker[1]); + if (idx !== expectedIndex) { + fail( + `frame markers must be sequential from 0, expected ${expectedIndex}, got ${idx}`, + ); + } + j++; + const rows: string[] = []; + while (j < lines.length && !FRAME_MARKER_RE.test(lines[j])) { + rows.push(lines[j]); + j++; + } + if (rows.length === 0) fail(`frame ${idx} has no rows`); + frames.push(rows); + expectedIndex++; + } + if (frames.length === 0) fail("frames section has no frames"); + + const width = frames[0][0].length; + const height = frames[0].length; + for (const [idx, frame] of frames.entries()) { + if (frame.length !== height) { + fail( + `frame ${idx} has ${frame.length} rows, expected ${height} (frame 0's height)`, + ); + } + for (const row of frame) { + if (row.length !== width) { + fail( + `frame ${idx} row width ${row.length} does not match frame 0's width ${width}`, + ); + } + checkGlyphs(row); + } + } + + return { kind: "animated", palette, width, height, fps, frames }; +} + +/** One frame's rows, rasterized to a canvas — one filled rect per cell. */ +export function frameToCanvas( + frame: string[], + palette: Palette, + cellPx: number, +): HTMLCanvasElement { + const height = frame.length; + const width = frame[0]?.length ?? 0; + const canvas = document.createElement("canvas"); + canvas.width = width * cellPx; + canvas.height = height * cellPx; + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("2d canvas context unavailable"); + ctx.imageSmoothingEnabled = false; + for (let y = 0; y < height; y++) { + const row = frame[y]; + for (let x = 0; x < width; x++) { + // parseTexture already rejects any glyph missing from the palette, so + // this lookup cannot miss for a texture that made it through parsing. + ctx.fillStyle = palette.get(row[x]) as string; + ctx.fillRect(x * cellPx, y * cellPx, cellPx, cellPx); + } + } + return canvas; +} + +/** + * Every frame of a parsed texture, rasterized to a pixi `Texture` at the + * given cell size. One frame for a static texture, `fps`-ordered frames for + * an animation — the cell size is a render-time choice, not part of the file + * (decision §4), so it is a parameter here rather than baked into `parsed`. + */ +export function texturesFromParsed( + parsed: ParsedTexture, + cellPx: number, +): Texture[] { + const frames = parsed.kind === "static" ? [parsed.grid] : parsed.frames; + return frames.map((frame) => + Texture.from(frameToCanvas(frame, parsed.palette, cellPx)), + ); +} + +/** Fetches and parses a texture file from `web/assets/textures/`. */ +export async function loadTextureFile(path: string): Promise { + const res = await fetch(path); + if (!res.ok) + throw new Error( + `failed to load texture ${path}: ${res.status} ${res.statusText}`, + ); + return parseTexture(await res.text()); +} diff --git a/web/tsconfig.json b/web/tsconfig.json index 69c1e92..cd9a1f2 100644 --- a/web/tsconfig.json +++ b/web/tsconfig.json @@ -4,7 +4,7 @@ "module": "ESNext", "moduleResolution": "bundler", "lib": ["ES2022", "DOM", "DOM.Iterable"], - "types": ["vite/client"], + "types": ["vite/client", "bun"], "strict": true, "noEmit": true, "skipLibCheck": true,