A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D
Complete town models and animate house surface effects
SandroMaglionee7625fc286e4
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.mdindex 5a1d606..dd91dc1 100644--- a/DEVELOPMENT.md+++ b/DEVELOPMENT.md@@ -66,27 +66,31 @@ compares the complete world catalogue with the actual drawings fromand elevation controls also work with a keyboard. The original view uses a30-degree orthographic camera with the game's 64×32 projection.-| Collection | Models | Coverage |+| Collection | Entries | Coverage || --- | ---: | --- |-| Buildings | 28 | Every building kind, with its roof, topper and yard (the twelve added with the neighbourhood are placeholders, see below) |-| Homes | 9 | Settlers' and citizens' homes in all four roof palettes, and the placeholder townhouse |-| Land | 19 | Three tree shapes at three growth stages, stone and ore in both resource states, four crop stages, roads and water |-| People | 27 | Carriers, settlers, citizens, market and chapel walkers, all six hats and the sixteen reference-gallery residents |+| Buildings | 42 | Every building kind, plus winter and worn material presets of the seven town services and stores |+| Homes | 21 | Four settler and citizen roof palettes, townhouse, and fine/poor/worn/winter material presets of every tier |+| Land | 20 | Trees, rocks, crops, roads, water and raised stone paving |+| People | 32 | Carriers, residents, market and chapel walkers, and five equipped service workers || Cargo and vehicles | 75 | Twelve distinct goods and labelled crates; empty handcart/barrow and small/full loads of each good; the approved mixed goods plate |-| Construction and effects | 20 | Empty/supplied sites, frame/walls, problem sign, smoke, four placement/reach outlines, and the placeholder ruins, warning signs, and flames |+| Construction and effects | 14 | Sites, frame/walls, problem sign, smoke, placement outlines and three kinds of ruin |-The 178 entries cover object families and representative seeded variants.+The 204 entries cover object families and representative seeded variants.Continuous growth, construction progress, walk poses and colours can begenerated; this is not a list of every possible random seed. Page iconsremain the game's original 2D UI art.-`pnpm assets:build` exports 178 GLBs and editable geometry descriptions,-a manifest, and two standalone viewers to `output/inkline-3d/`:-`inkline-3d-study.html` and `inkline-3d-map.html`. It reimports every GLB and+`pnpm assets:build` exports 204 GLBs and editable geometry descriptions,+a manifest, and four standalone viewers to `output/inkline-3d/`:+`inkline-3d-study.html`, `inkline-3d-map.html`, and+`inkline-town-model-review.html`, and `inkline-house-effects.html`. It reimports every GLB andchecks geometry and unlit materials. The viewers work without a dev server;their optional web fonts use the network. The game build remains separate.+Material effects render in the viewers and live game. Ordinary GLB viewers+show the underlying mesh; effect parameters are preserved as GLB extras and+in the editable geometry descriptions, rather than baked into duplicate meshes.- `src/asset-lab/primitives.ts`: renderer-independent polygon/stroke schemaand reusable modelling operations in the game's cell units and pixel heights.@@ -113,7 +117,7 @@ Double-click the ground to focus the camera there.District shortcuts focus the town, workshops, homes, people, cargo yard or-forest. Inspect selects any of the 178 models and links to its original+forest. Inspect selects any of the 204 entries and links to its originaldrawing comparison. Eight additional people walk along the street using twoprocedural poses; pause them for review. Smoke and the problem sign facethe camera so they stay readable when the map turns.@@ -151,22 +155,39 @@ That is how the README's screenshots of grown towns were made.(seasons and the almanac, the crown, approval, the end of the term, history).- `src/present.ts`: per-frame interaction, panel, and view sync.- `src/art.ts`: all drawing: buildings and their yards, homes, the land, roads, carts, and figures.-- `src/render3d/`: live world renderer, model instances, camera and map input, the map views' overlay,- warning signs, flames, ruins, and winter frost.-- `src/asset-lab/placeholders.ts`: stand-in models for ornaments, ruins, warning signs, and flames.--**Placeholders.** The neighbourhood brought kinds with no approved model yet.-They are drawn so the game is playable, and are meant to be replaced:-the granary, smokehouse, fire watch, healer, hospital, watch house, and-builder's yard use the generic building in their colour; the garden, park,-fountain, statue, and plaza are simple shapes (`placeholders.ts`, and-`drawDecor` in `art.ts` for the menu pictures); the townhouse is the-citizens' home raised a storey; ruins, the warning signs over homes,-and flames are simple stand-ins; a paved street is the road with setts-drawn on it; a home's neighbourhood (fine or poor) and a run-down building-are shown only as a tint, not as fences, gardens, or a patched roof; and-winter frosts the land and tints what stands, rather than putting snow on-roofs.+- `src/render3d/`: live world renderer, model instances, camera and map input,+ overlays, ruins, surface shaders and roof particle emitters.+- `src/asset-lab/town-props.ts`: gardens, furniture, stone paving and ruins.+- `src/asset-lab/services.ts`: grain hoist, fish racks, watch tower, herbs,+ medical signs, street noticeboard and builder's equipment.+- `src/asset-lab/appearance.ts`: material state metadata for catalogue presets.+ Wear, neighbourhood, hazards and winter are per-instance attributes in the+ live renderer. A state change does not change the geometry cache key.++### Reviewing the new town models++Open [`/model-review.html`](http://localhost:5232/model-review.html) for+the models added for PR #3. Collections cover buildings, gardens and squares,+home tiers and neighbourhoods, winter, hazards, people/cargo and building+condition. Drag any model or use the rotation slider to turn the collection.+**Inspect** opens the full asset viewer. **Download GLB** exports one model;+**Save model sheet** captures a labelled sheet of the selected collection.+`pnpm check:models` checks every collection, camera controls, sheet exports+and phone layout, and saves PNGs to `output/inkline-3d/town-review/`.++Open [`/effects-lab.html`](http://localhost:5232/effects-lab.html) to inspect+eight conditions on the same house geometry. Select any home tier, rotate,+adjust effect strength or pause animation. Dirt, masonry, cracks, snow,+glazing damage and fire light come from `surface-shader.ts`. `structure-effects.ts`+samples the roof triangles for animated fire, smoke and ember emitters.+`pnpm check:effects` captures all tiers, verifies that animation changes the+rendered pixels, checks phone layout and exports a five-second MP4 to+`output/inkline-3d/house-effects/`. The runtime and this preview share the+same instanced renderer and effect code.++The original 2D menu drawings remain in `art.ts` for comparison. The live+3D town uses the new geometry, including equipped service workers and cured+fish cargo. The game has no audio, so winter music is outside this model work.- `src/townsfolk.ts`: residents out walking, for looking at only: not simulated, not saved.- `src/icons.ts`: the page's line-drawn icons.- `src/gallery.ts`: the dev-only art gallery (see above).@@ -272,3 +293,8 @@ pnpm --dir deploy exec alchemy destroy --stage preview --profile adminThe second command removes the preview. Each stage has its own Worker;previews stay on their `workers.dev` URL and never claim the custom domain.++The production build includes the game and all review pages. On any deployed+stage, use `/asset-lab.html` for the complete catalogue, `/model-review.html`+for the PR #3 collections, `/effects-lab.html` for animated house states, and+`/map-lab.html` to inspect all models together in a town.diff --git a/effects-lab.html b/effects-lab.htmlnew file mode 100644index 0000000..7a9074e--- /dev/null+++ b/effects-lab.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/favicon.svg"><title>Inkline Town · Effects on the house</title></head><body><main id="effects-lab"></main><script type="module" src="/src/effects-lab/main.ts"></script></body></html>diff --git a/model-review.html b/model-review.htmlnew file mode 100644index 0000000..90dd2a5--- /dev/null+++ b/model-review.html@@ -0,0 +1,2 @@+<!doctype html>+<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="/favicon.svg" type="image/svg+xml"><title>Inkline Town · Town model review</title></head><body><main id="review"></main><script type="module" src="/src/model-review/main.ts"></script></body></html>diff --git a/package.json b/package.jsonindex 052dbbf..1a7a4df 100644--- a/package.json+++ b/package.json@@ -11,6 +11,8 @@"balance": "node scripts/balance.ts","check": "node scripts/check.ts","check:browser": "node scripts/check-browser.ts",+ "check:models": "node scripts/check-town-models.ts",+ "check:effects": "node scripts/check-house-effects.ts","test": "node --test \"test/*.test.ts\"","release": "pnpm --dir deploy release"},diff --git a/scripts/check-house-effects.ts b/scripts/check-house-effects.tsnew file mode 100644index 0000000..7937e8a--- /dev/null+++ b/scripts/check-house-effects.ts@@ -0,0 +1,50 @@+import assert from "node:assert/strict"+import { existsSync } from "node:fs"+import { mkdir,writeFile } from "node:fs/promises"+import { execFileSync } from "node:child_process"+import { chromium } from "playwright"+declare global { interface Window { effectsLab:{capture:(t:number,focus?:boolean)=>string;pause:()=>void;stats:()=>{tier:number;yaw:number;time:number;frame:number;templates:number;activeTemplates:number;models:number}} } }+const executablePath=process.env.BROWSER_EXECUTABLE_PATH??["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)+const browser=await chromium.launch({headless:true,...(executablePath?{executablePath}:{})}),page=await browser.newPage({viewport:{width:1440,height:1100},deviceScaleFactor:2}),errors:string[]=[],output="output/inkline-3d/house-effects"+page.on("pageerror",e=>errors.push(e.message));page.on("console",m=>{if(m.type()==="error")errors.push(m.text())})+await mkdir(`${output}/frames`,{recursive:true})+await mkdir(`${output}/fire-frames`,{recursive:true})+try{+ await page.goto(`${process.env.GAME_BASE_URL??"http://127.0.0.1:5232"}/effects-lab.html`)+ await page.waitForFunction(()=>window.effectsLab?.stats().frame>2)+ await page.evaluate(()=>window.effectsLab.pause())+ for(const tier of [1,2,3]){+ await page.getByLabel("House tier").selectOption(String(tier))+ const data=await page.evaluate(()=>window.effectsLab.capture(2.0))+ await writeFile(`${output}/tier-${tier}.png`,Buffer.from(data.split(",")[1]!,"base64"))+ }+ await page.getByLabel("House tier").selectOption("2")+ const stats=await page.evaluate(()=>window.effectsLab.stats())+ assert.equal(stats.models,8); assert.ok(stats.templates<=3)+ assert.equal(stats.activeTemplates,1)+ assert.equal(await page.locator("canvas.rendering").evaluate(c=>c.getBoundingClientRect().width),1440,"Canvas CSS size must not grow with device pixel ratio")+ const original=await page.evaluate(()=>window.effectsLab.capture(2))+ await page.getByLabel("Effect strength").fill("0")+ const clean=await page.evaluate(()=>window.effectsLab.capture(2));assert.notEqual(clean,original)+ await page.getByLabel("Effect strength").fill("100")+ const t0=await page.evaluate(()=>window.effectsLab.capture(0)),t1=await page.evaluate(()=>window.effectsLab.capture(1))+ assert.notEqual(t0,t1,"Animation must change the actual rendered pixels")+ await page.getByRole("button",{name:"See the back",exact:true}).click()+ const back=await page.evaluate(()=>window.effectsLab.capture(2));await writeFile(`${output}/rear.png`,Buffer.from(back.split(",")[1]!,"base64"))+ await page.getByRole("button",{name:"See the back",exact:true}).click()+ for(let i=0;i<150;i++){+ const data=await page.evaluate(t=>window.effectsLab.capture(t),i/30)+ await writeFile(`${output}/frames/${String(i).padStart(4,"0")}.png`,Buffer.from(data.split(",")[1]!,"base64"))+ const fire=await page.evaluate(t=>window.effectsLab.capture(t,true),i/30)+ await writeFile(`${output}/fire-frames/${String(i).padStart(4,"0")}.png`,Buffer.from(fire.split(",")[1]!,"base64"))+ if(i===60)await writeFile(`${output}/fire-close-up.png`,Buffer.from(fire.split(",")[1]!,"base64"))+ }+ execFileSync("ffmpeg",["-y","-loglevel","error","-framerate","30","-i",`${output}/frames/%04d.png`,"-c:v","libx264","-crf","19","-pix_fmt","yuv420p","-movflags","+faststart",`${output}/house-effects.mp4`])+ execFileSync("ffmpeg",["-y","-loglevel","error","-framerate","30","-i",`${output}/fire-frames/%04d.png`,"-c:v","libx264","-crf","19","-pix_fmt","yuv420p","-movflags","+faststart",`${output}/fire-close-up.mp4`])+ await page.evaluate(()=>scrollTo(0,250));await page.screenshot({path:`${output}/preview.png`})+ await page.setViewportSize({width:390,height:844})+ assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth))+ await page.screenshot({path:`${output}/phone.png`})+ assert.deepEqual(errors,[])+ console.log(JSON.stringify({models:stats.models,templates:stats.templates,tiers:[1,2,3],animationFrames:150,video:`${output}/house-effects.mp4`,browserErrors:errors}))+}finally{await browser.close()}diff --git a/scripts/check-town-models.ts b/scripts/check-town-models.tsnew file mode 100644index 0000000..f85205c--- /dev/null+++ b/scripts/check-town-models.ts@@ -0,0 +1,60 @@+/** Review gallery and portable export checks, using the same isolated browser+ * workflow as check-browser.ts. The dev server must already be running. */+import assert from "node:assert/strict"+import { existsSync } from "node:fs"+import { mkdir, writeFile } from "node:fs/promises"+import { chromium } from "playwright"++const executablePath = process.env.BROWSER_EXECUTABLE_PATH ?? ["/Applications/Brave Browser.app/Contents/MacOS/Brave Browser", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"].find(existsSync)+const browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })+const page = await browser.newPage({ viewport: { width: 1440, height: 1100 }, deviceScaleFactor: 1 })+const errors: string[] = []+page.on("pageerror", e => errors.push(e.message))+page.on("console", e => { if (e.type() === "error") errors.push(e.text()) })+page.on("response", r => { if (r.status() >= 400) errors.push(`${r.status()} ${r.url()}`) })+const output = "output/inkline-3d/town-review"+await mkdir(output, { recursive: true })+const groups = ["Buildings", "Gardens & squares", "Homes & neighbourhoods", "Winter", "Ruins", "People & cargo", "Building condition"]+const captureSheet = async () => {+ const previous = await page.locator("#sheet-link").getAttribute("href")+ await page.getByRole("button", { name: "Save model sheet", exact: true }).click()+ await page.waitForFunction(previous => {+ const link = document.querySelector<HTMLAnchorElement>("#sheet-link")!+ return !link.hidden && link.getAttribute("href") !== previous+ }, previous)+ return page.evaluate(async () => {+ const blob = await fetch(document.querySelector<HTMLAnchorElement>("#sheet-link")!.href).then(r => r.blob())+ return new Promise<string>(resolve => {+ const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.readAsDataURL(blob)+ })+ })+}+try {+ await page.goto(`${process.env.GAME_BASE_URL ?? "http://127.0.0.1:5232"}/model-review.html`)+ await page.locator(".model-view").first().waitFor()+ for (const group of groups) {+ await page.getByRole("button", { name: group, exact: true }).click()+ const collection = new URL(page.url()).searchParams.get("collection")!+ const image = await captureSheet()+ assert.ok(image?.startsWith("data:image/png;base64,"))+ await writeFile(`${output}/${collection}.png`, Buffer.from(image.split(",")[1]!, "base64"))+ await page.evaluate(() => scrollTo(0, 350))+ await page.screenshot({ path: `${output}/${collection}-page.png` })+ await page.getByRole("button", { name: "See the back", exact: true }).click()+ assert.equal(await page.locator("output").textContent(), "180°")+ await page.getByRole("button", { name: "Reset view", exact: true }).click()+ await page.getByLabel("View elevation").selectOption("50")+ const rear = await captureSheet()+ assert.ok(rear && rear !== image, `${group}: the exported view must respond to the camera`)+ await page.getByRole("button", { name: "Reset view", exact: true }).click()+ console.log(`ok ${collection}: ${await page.locator(".model-view").count()} models, rotation, elevation, PNG export`)+ }+ await page.setViewportSize({ width: 390, height: 844 })+ await page.getByRole("button", { name: "Gardens & squares", exact: true }).click()+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "Phone preview must fit the viewport")+ await page.screenshot({ path: `${output}/phone.png` })+ assert.deepEqual(errors, [])+ console.log("ok phone layout; no browser errors")+} finally {+ await browser.close()+}diff --git a/scripts/ink-assets.ts b/scripts/ink-assets.tsindex 94b89f2..fed8254 100644--- a/scripts/ink-assets.ts+++ b/scripts/ink-assets.ts@@ -29,6 +29,7 @@ for (const asset of inkAssets) {await writeFile(path.join(output, "models", `${asset.id}.glb`), new Uint8Array(glb))await writeFile(path.join(output, "models", `${asset.id}.json`), JSON.stringify(asset, null, 2))const imported = await loader.parseAsync(glb, "")+ if(asset.effects&&!imported.scene.getObjectByName(asset.id)?.userData.inklineSurfaceEffects)throw new Error(`${asset.id}: surface state metadata lost on export`)let meshes = 0,vertices = 0imported.scene.traverse((object) => {@@ -50,6 +51,7 @@ for (const asset of inkAssets) {id: asset.id,title: asset.title,category: asset.category,+ effects: asset.effects,glb: `models/${asset.id}.glb`,geometry: `models/${asset.id}.json`,bytes: glb.byteLength,@@ -62,7 +64,9 @@ for (const asset of inkAssets) {await writeFile(path.join(output, "manifest.json"), JSON.stringify({ models: manifest.length, assets: manifest }, null, 2))for (const [input, directory, filename] of [["asset-lab.html", "viewer", "inkline-3d-study.html"],- ["map-lab.html", "map-viewer", "inkline-3d-map.html"]+ ["map-lab.html", "map-viewer", "inkline-3d-map.html"],+ ["model-review.html", "town-viewer", "inkline-town-model-review.html"],+ ["effects-lab.html", "effects-viewer", "inkline-house-effects.html"]]) {await build({configFile: false,diff --git a/src/art.ts b/src/art.tsindex 6c9d942..3b497e4 100644--- a/src/art.ts+++ b/src/art.ts@@ -20,6 +20,7 @@* - a crate is 6 units wide, a carried one 4.*/import { Container, Graphics } from "pixi.js"+import type { SurfaceState } from "./render3d/surface-state.ts"import { goods, GROWN, home, kinds, ROCK_AMOUNT, type GoodId, type Kind, type KindId, type Tier } from "./content.ts"import { cellOf, DIRS, key } from "./grid.ts"@@ -847,6 +848,7 @@ export const drawSite = (g: Graphics, half: number, share: number) => {/** What a building view shows each frame. */export interface BuildingLook {+ readonly effects?: Partial<SurfaceState>/** A sign over it, and whether it is on fire. */readonly alert?: Alert | nullreadonly burning?: boolean@@ -1031,6 +1033,7 @@ export const drawHouse = (g: Graphics, tier: Tier, build: number, doors: Doors,/** What a home view shows each frame. */export interface HouseLook {+ readonly effects?: Partial<SurfaceState>readonly tier: Tierreadonly build: numberreadonly doors: Doors@@ -1427,6 +1430,7 @@ export interface PersonDress {/** What a figure has with it. */export type Load =| { readonly kind: "none" }+ | { readonly kind: "service"; readonly role: "watchman" | "firefighter" | "physician" | "constable" | "builder" }/** A carrier's cart: `good` on it, `count` of it (none on the way back). */| { readonly kind: "cart"; readonly good: GoodId; readonly count: number }/** A market walker's basket of provisions. */diff --git a/src/asset-lab/appearance.ts b/src/asset-lab/appearance.tsnew file mode 100644index 0000000..1c01cd6--- /dev/null+++ b/src/asset-lab/appearance.ts@@ -0,0 +1,7 @@+import { type InkAsset } from "./primitives.ts"+import { surfaceState } from "../render3d/surface-state.ts"+export interface Appearance { worn?: boolean; band?: "poor" | "plain" | "fine"; winter?: boolean }+/** State is material data. The original mesh and its ink stay identical. */+export function withAppearance(asset: InkAsset, a: number, H: number, look: Appearance = {}, _home = false): InkAsset {+ return { ...asset, effects: { half: a, height: H, state: surfaceState({wear:look.worn?0.9:look.band==="poor"?0.55:0,care:look.band==="fine"?1:0,snow:look.winter?1:0}) } }+}diff --git a/src/asset-lab/assets.ts b/src/asset-lab/assets.tsindex 0bd84d1..76714dd 100644--- a/src/asset-lab/assets.ts+++ b/src/asset-lab/assets.ts@@ -1,13 +1,16 @@/** Portable polygon-and-stroke assets. Floor coordinates remain in cells;* heights remain in the original drawing's pixels. No renderer types here. */-import { kindIds, goodIds } from "../content.ts"+import { kindIds, goodIds, kinds, home } from "../content.ts"+import { withAppearance } from "./appearance.ts"+import { groundAsset } from "../render3d/models.ts"+import { key } from "../grid.ts"import { makeBuilding } from "./buildings.ts"import { house } from "./homes.ts"import { U } from "../iso.ts"import { makeTree, makeRock, makeField, makeRoadPatch, makeWater } from "./land.ts"import { personCatalogue, makeCarrier, makeGoods, makeCrate } from "./people.ts"import { makeSite, makeConstruction, makeMarker, makeSmoke, makePlot } from "./construction.ts"-import { makeFlames, makeRuin, makeWarning } from "./placeholders.ts"+import { makeRuin } from "./town-props.ts"import { Drawing, mix, pale, square, sides, palette, type InkAsset, type Vertex } from "./primitives.ts"export * from "./primitives.ts"@@ -116,6 +119,19 @@ for (const tier of [1, 2] as const)additional.push(asset)}additional.push(house(3))+for (const tier of [1, 2, 3] as const) for (const appearance of ["fine", "poor", "worn", "winter"] as const) {+ const base = house(tier), a = (home.half + (tier >= 2 ? 1 : 0)) * U+ const model = withAppearance(base, a, home.tiers[tier].height, { band: appearance === "fine" || appearance === "poor" ? appearance : "plain", worn: appearance === "worn", winter: appearance === "winter" }, true)+ model.id = `${base.id}-${appearance}`; model.title = `${base.title} · ${appearance}`; model.appearance = appearance+ model.note = appearance === "winter" ? "Snow settles on roof surfaces through the material shader." : appearance === "fine" ? "Fresh plaster and warm windows on the same house mesh." : "Dirt, exposed brick, cracks and roof moss through the material shader."+ additional.push(model)+}+for (const id of ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] as const) for (const appearance of ["winter", "worn"] as const) {+ const kind = kinds[id], base = makeBuilding(id)+ const model = withAppearance(base, kind.half * U, kind.roof === "gable" ? 20 : kind.stories * 32, { winter: appearance === "winter", worn: appearance === "worn" })+ model.id = `${id}-${appearance}`; model.title = `${kind.title} · ${appearance}`; model.appearance = appearance+ additional.push(model)+}for (const type of ["fir", "broadleaf", "poplar"] as const)for (const grown of [0.3, 0.6, 1]) {if (type === "fir" && grown === 1) continue@@ -124,6 +140,14 @@ for (const type of ["fir", "broadleaf", "poplar"] as const)for (const ore of [false, true]) for (const full of [false, true]) additional.push(makeRock(ore, full))for (const stage of [0, 1, 2, 3] as const) additional.push(makeField(stage))additional.push(makeRoadPatch(), makeWater(), ...personCatalogue())+{+ const cells = new Set([key(8, 8), key(7, 8), key(9, 8), key(8, 7), key(8, 9)])+ const asset = groundAsset(cells, new Set(), false, cells)+ const shift = ([u, v, z]: Vertex): Vertex => [u - 8.5, v - 8.5, z]+ asset.faces.forEach(f => { f.points = f.points.map(shift) }); asset.strokes.forEach(s => { s.points = s.points.map(shift) })+ asset.id = "paved-street"; asset.title = "Paved street"; asset.note = "Raised stone setts with staggered joints and joined edges."; asset.category = "land"; asset.reference = { type: "roads" }; asset.footprint = 3+ additional.push(asset)+}for (const barrow of [false, true]) {additional.push(makeCarrier(null, barrow))for (const good of goodIds) for (const count of [1, 4]) additional.push(makeCarrier(good, barrow, count))@@ -138,8 +162,6 @@ additional.push(makeSmoke(),...(["burnt", "collapsed", "derelict"] as const).map((cause) => makeRuin(1, cause)),makeRuin(2, "burnt"),- ...(["fire", "health", "order", "sick", "worn"] as const).map((kind) => makeWarning(kind)),- makeFlames(0),...["hover", "picked", "blocked", "reach"].map((look) => makePlot(look as "hover" | "picked" | "blocked" | "reach")))export const inkAssets: ReadonlyArray<InkAsset> = [...approvedAssets, ...additional]diff --git a/src/asset-lab/buildings.ts b/src/asset-lab/buildings.tsindex 1d6128f..b7e6416 100644--- a/src/asset-lab/buildings.ts+++ b/src/asset-lab/buildings.ts@@ -1,7 +1,8 @@import { kinds, type KindId } from "../content.ts"import { U } from "../iso.ts"import { Drawing, palette, pale, square, sides, type Vertex, type Side } from "./primitives.ts"-import { makeDecor } from "./placeholders.ts"+import { makeDecor } from "./town-props.ts"+import { finishTownBuilding, townBuildingNotes } from "./services.ts"const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }> = {townhall: { accent: 0x8a58a8, glass: 0xf3dca6 },@@ -20,7 +21,7 @@ const dresses: Record<KindId, { accent: number; roof?: number; glass?: number }>weaver: { accent: 0x8a58a8 },market: { accent: 0x3d6db5 },chapel: { accent: 0x3d6db5, glass: 0xc9d6ee },- // New kinds: the plain building in their colour, a placeholder until each has a model of its own.+ // Town services and stores share the palette; services.ts adds their fittings.granary: { accent: 0xd6ae2e },smokehouse: { accent: 0x9a5b3a, roof: 0x9a5b3a },firewatch: { accent: 0xc4523f, roof: 0xc4523f },@@ -54,13 +55,13 @@ export function makeBuilding(id: KindId, options: BuildingOptions = {}) {const d = new Drawing(id,kind.title,- id === "mill"+ townBuildingNotes[id] ?? (id === "mill"? "The lattice sails sit on a real upright plane. Flour sacks remain softly rounded.": id === "market"? "Striped canopy, coloured goods crates and roof flag, all built as geometry.": id === "townhall"? "Two storeys, clock faces, violet trim, three skylights and a red flag. Original dimensions throughout."- : "Original footprint, palette and yard details, with complete walls and roof geometry."+ : "Original footprint, palette and yard details, with complete walls and roof geometry."))d.asset.category = "buildings"d.asset.reference = { type: "building", kind: id }@@ -202,7 +203,7 @@ function finishBuilding(d: Drawing, id: KindId, a: number, p: number, H: number,if (kind.topper === "chimney" && fit > 0) {d.box(u, v, 2 * U, 2 * U, H, 24 * fit)d.face(square(u, v, 1.5 * U, H + 24 * fit + 0.035), 0x8b938c, 0)- } else if (kind.topper === "cupola" && fit > 0) {+ } else if (kind.topper === "cupola" && id !== "hospital" && fit > 0) {const half = 3 * U,top = H + 10 * fit,base = square(u, v, half, top)@@ -247,6 +248,7 @@ function finishBuilding(d: Drawing, id: KindId, a: number, p: number, H: number,for (let i = 0; i < 4; i++) d.face([base[i]!, base[(i + 1) % 4]!, [x, y, z + rise]], pale(color, i >= 2 ? 0.7 : 0.52))}if (fit <= 0.75) return+ finishTownBuilding(d, id, a, p, H)switch (id) {case "warehouse":d.crate(c, c - 1.5 * U, 0, 0x2f8c87, 1.6 * U, 6)diff --git a/src/asset-lab/homes.ts b/src/asset-lab/homes.tsindex b6219ed..18a4b8e 100644--- a/src/asset-lab/homes.ts+++ b/src/asset-lab/homes.ts@@ -14,7 +14,7 @@ export function house(id,tier === 1 ? "Settler cottage" : tier === 2 ? "Citizen home" : "Townhouse",tier === 3- ? "Placeholder townhouse: the citizens' home raised a storey, until it has a model of its own."+ ? "A burgher's townhouse with stone quoins, a cornice, iron balconies, a fanlight and a stepped entrance.": "Original roof palette, footprint, chimney, windows and awnings. Rear walls completed for rotation.")const variant = homeVariant(variantN)@@ -45,5 +45,25 @@ export function house(variant.roof.shade,fit > 0.8 && (variant.chimney || tier >= 2))+ if (tier === 3 && fit > 0.75) {+ for (const side of sides) {+ const p = (s: number, z: number, out = 0.02) => d.wall(side, a, s, z, out)+ for (const x of [-a + U, a - U]) for (let z = 1; z < H; z += 4)+ d.face([p(x - 0.6 * U, z), p(x + 0.6 * U, z), p(x + 0.6 * U, z + 2), p(x - 0.6 * U, z + 2)], 0xe7e3d4, 0.75, 0xa7b1a1)+ d.line([p(-a - U, H - 1), p(a + U, H - 1)], 2, 0xb8c4af)+ for (const along of [-3 * U, 3 * U]) {+ d.line([p(along - 1.5 * U, 17, 0.055), p(along + 1.5 * U, 17, 0.055)], 1)+ for (const dx of [-1.5, 0, 1.5]) d.line([p(along + dx * U, 14, 0.055), p(along + dx * U, 17, 0.055)], 0.75)+ }+ if (options.doors ? options.doors[side] : side === "right") {+ d.face([p(-2 * U, 10), p(2 * U, 10), p(U, 13), p(-U, 13)], 0xe2ebde, 1)+ const [u, v] = p(0, 0, 0.035)+ for (let i = 0; i < 3; i++) {+ const h = 0.04 + i * 0.035+ d.box(u, v, side === "left" || side === "backLeft" ? 2.5 * U : h, side === "right" || side === "backRight" ? 2.5 * U : h, 0, 1.5 - i * 0.4, 0xe5e6dd, 0xd3d9cc, 0xc3ccbd, 0.75)+ }+ }+ }+ }return d.asset}diff --git a/src/asset-lab/main.ts b/src/asset-lab/main.tsindex d7f920f..64c6c00 100644--- a/src/asset-lab/main.ts+++ b/src/asset-lab/main.ts@@ -26,7 +26,7 @@ import "./style.css"const root = document.querySelector<HTMLDivElement>("#lab")!root.innerHTML = `- <header><a href="/">Inkline Town</a><span>COMPLETE ASSET STUDY</span></header>+ <header><a href="/model-review.html">Model review ↗</a><span>COMPLETE ASSET CATALOGUE</span><a href="/effects-lab.html">Animated house effects ↗</a></header><div class="intro"><div><h1>The same ink.<br>A different angle.</h1><p>Original game drawings and complete 3D assets, side by side.</p></div><span class="tag">Procedural · Orthographic · Rotatable</span></div><div class="filters"><label>Collection <select id="category"></select></label><label>Find <input id="search" type="search" placeholder="Name or material"></label><a href="/map-lab.html">See everything on the map ↗</a></div><nav class="assets" aria-label="Choose an asset"></nav><section class="comparison" aria-label="Compare the original drawing with the 3D model">@@ -35,7 +35,7 @@ root.innerHTML = `</section><section class="controls" aria-label="Camera controls"><button id="reset">Match original view</button><label>Rotation <input id="rotation" type="range" min="-180" max="180" value="0" step="1"><output id="rotation-value">0°</output></label><label>Elevation <input id="elevation" type="range" min="10" max="65" value="30" step="1"><output id="elevation-value">30°</output></label><button id="rear">See the back</button></section><section class="caption"><div><h2 id="asset-title"></h2><p id="asset-note"></p></div><div class="downloads"><button id="download-glb">Download GLB</button><button id="download-source">Download geometry</button><button id="download-png">Save comparison</button></div></section>- <footer><span>Same palette, dimensions and two ink weights. New faces complete the volume.</span><span>Three.js prototype · PixiJS 3D integration pending</span></footer>+ <footer><span>Same palette, dimensions and two ink weights. New faces complete the volume.</span><span>These models are used in the live 3D game.</span></footer>`const viewer = document.querySelector<HTMLDivElement>("#viewer")!const reference = document.querySelector<HTMLCanvasElement>("#reference")!diff --git a/src/asset-lab/people.ts b/src/asset-lab/people.tsindex 27ed42b..db6d9bf 100644--- a/src/asset-lab/people.ts+++ b/src/asset-lab/people.ts@@ -4,6 +4,11 @@ import { Drawing, palette, type Vertex } from "./primitives.ts"import { U } from "../iso.ts"const R = 45.2548+export type ServiceRole = "watchman" | "firefighter" | "physician" | "constable" | "builder"+export function serviceCostume(dress: PersonDress, role: ServiceRole): PersonDress {+ const coats = { watchman: 0xb56e58, firefighter: 0xb96750, physician: 0xdce7d4, constable: 0x6e88a2, builder: 0xb69b72 }+ return { ...dress, coat: coats[role], trim: role === "firefighter" ? 0xc3aa72 : role === "physician" ? 0xeef2e4 : coats[role], hat: role === "physician" ? "bonnet" : role === "firefighter" ? "brim" : "cap", long: role === "physician" }+}export function drawPerson(d: Drawing, dress: PersonDress, load: Load, cart: CartLook | null, phase = 0) {const swing = phase === 0 ? 1 : -1// Complete rounded volumes preserve the simple original silhouette.@@ -127,6 +132,32 @@ export function drawPerson(d: Drawing, dress: PersonDress, load: Load, cart: Car0x8a6a45)}+ if (load.kind === "service") {+ const u = 0.08, v = -0.05+ if (load.role === "physician") {+ d.box(u, v, 1.3 * U, U, 4, 3.5, 0xa9bfad, 0xc9dac7, 0x92ad98, 0.75)+ d.line([[u - U, v, 8], [u - U, v, 9], [u + U, v, 9], [u + U, v, 8]], 0.75)+ d.line([[u, v + 1.01 * U, 4.8], [u, v + 1.01 * U, 6.8]], 1, 0xf4f5eb)+ d.line([[u - 0.6 * U, v + 1.01 * U, 5.8], [u + 0.6 * U, v + 1.01 * U, 5.8]], 1, 0xf4f5eb)+ } else if (load.role === "firefighter") {+ d.cylinder(u, v, 1.5 * U, 2, 4, 0xb8a27d, 0xb4cfdb, 0.75, 12)+ d.line([[u - U, v, 6], [u, v, 9], [u + U, v, 6]], 0.75)+ d.line([[-0.08, 0.02, 5], [-0.08, 0.02, 13]], 1.5, 0x8a6a45)+ d.box(-0.08, 0.02, 1.3 * U, 0.6 * U, 12, 2, 0xbfc7bd, 0xd7dfd1, 0x9da89c, 0.75)+ } else if (load.role === "watchman") {+ d.line([[u, v, 6], [u, v, 18]], 1, 0x8a6a45)+ d.box(u, v, U, U, 8, 3, 0xe5d6a5, 0xf3e6bd, 0xd6c48d, 0.75)+ d.cylinder(u, v, 1.4 * U, 11, 0.5, palette.ink, palette.ink, 0.75, 12)+ } else if (load.role === "constable") {+ d.line([[u, v, 4], [u, v, 11]], 1.5, 0x8a6a45)+ d.face([[-0.05, 0.058, 8], [-0.01, 0.058, 8], [-0.01, 0.058, 6], [-0.03, 0.058, 5], [-0.05, 0.058, 6]], 0xd5c697, 0.75)+ } else {+ d.box(u, v, 1.7 * U, U, 3, 3, 0xd5b28a, 0xe9d2a8, 0xbda07a, 0.75)+ d.line([[u - U, v, 6], [u - U, v, 8], [u + U, v, 8], [u + U, v, 6]], 0.75)+ d.line([[-0.07, 0, 6], [-0.07, 0, 12]], 1.5, 0x8a6a45)+ d.box(-0.07, 0, U, 0.7 * U, 11, 2, 0xb8bfae, 0xd5dbc9, 0x9ea993, 0.75)+ }+ }}export function drawCargo(d: Drawing, good: GoodId, count: number, u: number, v: number, z: number) {@@ -162,11 +193,9 @@ export function drawCargo(d: Drawing, good: GoodId, count: number, u: number, v:break}case "fish":- case "smoked":case "bread": {- // Smoked fish is fish in the smokehouse's brown.const fishy = good !== "bread",- tint = good === "fish" ? 0x2f8c87 : good === "smoked" ? 0x9a5b3a : 0xd98a6a+ tint = good === "fish" ? 0x2f8c87 : 0xd98a6ad.box(u, v, 1.6 * U, 1.1 * U, z, 3, 0xc9a46a, 0xe3c592, 0xd2b07a, 1)for (let i = 0; i < n + 1; i++) {const x = u + (i - n / 2) * 0.9 * U,@@ -185,6 +214,17 @@ export function drawCargo(d: Drawing, good: GoodId, count: number, u: number, v:}break}+ case "smoked": {+ d.box(u, v, 2.2 * U, 1.3 * U, z, 2, 0xd5b28a, 0xe9d2a8, 0xbda07a, 1)+ for (let i = 0; i < n + 1; i++) {+ const y = v + (i - n / 2) * 0.8 * U+ // Split cured fillets, tied in pairs: flatter and longer than fresh fish.+ d.ellipsoid(u, y, z + 2.8, 2 * U, 0.4 * U, 0.6, 0xb98a61, 0.75, 0xd9b589, 12)+ for (const x of [-1, 0, 1]) d.line([[u + x * U, y - 0.3 * U, z + 3.2], [u + (x + 0.3) * U, y + 0.3 * U, z + 3.2]], 0.5, 0x8a6a45)+ }+ for (const x of [-0.8, 0.8]) d.line([[u + x * U, v - U, z + 3.6], [u + x * U, v + U, z + 3.6]], 0.75, 0xe6d4b2)+ break+ }case "flour":;[-1, 1, 0].slice(0, n).forEach((a, i) => d.sack(u + a * U, v, z + (i === 2 ? 4 : 0)))break@@ -287,6 +327,8 @@ export function personCatalogue() {makePerson("market-walker", "Market walker", serviceDress(0x3d6db5, 0.3, false), { kind: "basket", goods: ["fish", "bread", "cloth"] }))items.push(makePerson("chapel-walker", "Chapel walker", serviceDress(0x3d6db5, 0.6, true), { kind: "bell" }))+ for (const role of ["watchman", "firefighter", "physician", "constable", "builder"] as const)+ items.push(makePerson(`service-${role}`, role[0]!.toUpperCase() + role.slice(1), serviceCostume(serviceDress(0x3d6db5, 0.3, false), role), { kind: "service", role }))for (let i = 0; i < 16; i++) {const tier = i < 8 ? 1 : 2,n = (i * 0.37) % 1,diff --git a/src/asset-lab/placeholders.ts b/src/asset-lab/placeholders.tsdeleted file mode 100644index a9248de..0000000--- a/src/asset-lab/placeholders.ts+++ /dev/null@@ -1,132 +0,0 @@-/**- * Placeholder models for what the town gained with desirability, services,- * and decay: ornaments (garden, park, fountain, statue, plaza), ruins, the- * signs that go up over a home at risk, and flames. They are built from the- * same primitives as everything else so they sit in the drawing, but they- * are simple stand-ins until each gets a proper model.- */-import { kinds, type KindId } from "../content.ts"-import { U } from "../iso.ts"-import { Drawing, palette, square, type Vertex } from "./primitives.ts"--const green = 0xd8e6c9-const leaves = 0xa9c79a-const stone = 0xe4e6e0-const water = 0xc9dde6--const tree = (d: Drawing, u: number, v: number, size = 1) => {- d.line([[u, v, 0], [u, v, 5 * size]], 1.5, 0x6b5a45)- d.ellipsoid(u, v, 5 * size + 6 * size, (5 * size) / 64, (5 * size) / 64, 6 * size, leaves, 1)-}--const figure = (d: Drawing, u: number, v: number, z: number) => {- d.box(u, v, 2.5 * U, 2.5 * U, z - 6, 6, stone, 0xdcded7, 0xc9ccc4)- d.cylinder(u, v, 0.9 * U, z, 11, 0xb9beb5, 0xc9ccc4, 1, 10)- d.ellipsoid(u, v, z + 13, 0.9 * U, 0.9 * U, 2.2, 0xc9ccc4, 1, undefined, 10)-}--/** An ornament of `id`, `size` cells a side, on its plate. */-export function makeDecor(id: KindId) {- const kind = kinds[id],- p = (kind.size * 8 - 1) * U- const d = new Drawing(id, kind.title, "Placeholder ornament: simple shapes standing in until it has a model of its own.")- d.asset.category = "buildings"- d.asset.reference = { type: "building", kind: id }- d.asset.footprint = kind.size- d.face(square(0, 0, p, -0.15), id === "plaza" || id === "statue" || id === "fountain" ? stone : green)- if (id === "garden") {- tree(d, -p / 2, -p / 2, 0.7)- tree(d, p / 2, p / 2, 0.8)- for (const [u, v, c] of [[p / 2, -p / 2, 0xe89a7c], [-p / 2, p / 2, 0xe3c25a], [0, 0, 0xc9a0d6]] as const) d.box(u, v, 1.5 * U, 1.5 * U, 0, 2, c, c, c, 1)- } else if (id === "park") {- tree(d, -p / 2, -p / 2, 1.1)- tree(d, p / 2, -p / 3, 0.9)- tree(d, -p / 3, p / 2, 1)- d.line([[-p, p / 6, 0.02], [p, -p / 6, 0.02]], 3, 0xe6e8e2)- d.box(p / 2, p / 2, 3 * U, U, 0, 3, 0xd5a86c, 0xc79a5b, 0xb08a5a, 1)- } else if (id === "fountain") {- d.cylinder(0, 0, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)- d.cylinder(0, 0, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)- d.cylinder(0, 0, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)- } else if (id === "statue") {- figure(d, 0, 0, 6)- } else if (id === "plaza") {- for (let i = -2; i <= 2; i++) {- d.line([[-p, (i * p) / 3, 0.02], [p, (i * p) / 3, 0.02]], 1, 0xc9ccc4)- d.line([[(i * p) / 3, -p, 0.02], [(i * p) / 3, p, 0.02]], 1, 0xc9ccc4)- }- figure(d, 0, 0, 6)- tree(d, -p * 0.75, -p * 0.75, 0.7)- tree(d, p * 0.75, p * 0.75, 0.7)- }- return d.asset-}--/** What is left of a home or building: charred, tumbled down, or boarded up. */-export function makeRuin(size: number, cause: "burnt" | "collapsed" | "derelict") {- const d = new Drawing(`ruin-${cause}-${size}`, `Ruin · ${cause}`, "Placeholder ruin: broken walls on a cleared plate, until it has a model of its own.")- d.asset.category = "construction"- d.asset.reference = { type: "none" }- d.asset.footprint = size- const p = (size * 8 - 1) * U,- a = p - 2 * U- const wall = cause === "burnt" ? 0x77736b : cause === "collapsed" ? 0xe2ddd0 : 0xd9d4c7- d.face(square(0, 0, p, -0.15), cause === "burnt" ? 0xb9b5ab : 0xe9e6dd)- if (cause === "derelict") {- d.box(0, 0, a, a, 0, 9, 0xcfcabd, wall, 0xc4bfb2)- for (const s of [-1, 1]) d.line([[a + 0.004, s * a * 0.4, 2], [a + 0.004, -s * a * 0.4, 7]], 1.5, 0x8a6a45)- return d.asset- }- const pieces: ReadonlyArray<readonly [number, number, number]> = [[-a, -a, 7], [a * 0.3, -a, 4], [-a, a * 0.2, 5], [a * 0.6, a * 0.6, 3]]- for (const [u, v, h] of pieces) d.box(u + U, v + U, 1.2 * U * size, 1.2 * U * size, 0, h, wall, wall, 0xc4bfb2, 1)- if (cause === "burnt") for (let i = 0; i < 3; i++) d.line([[-a + i * a * 0.6, -a * 0.5, 0.5], [-a + i * a * 0.7 + a * 0.4, a * 0.4, 3]], 2, 0x3d4943)- else for (let i = 0; i < 4; i++) d.box(-a * 0.2 + i * U * 2, a * 0.1, U, U, 0, 1.5, wall, wall, wall, 1)- return d.asset-}--export type WarningKind = "fire" | "health" | "order" | "sick" | "worn"--/** A sign over a home at risk, facing the camera: a smoke wisp, a pale face, a broken window, a sick face, a cracked wall. */-export function makeWarning(kind: WarningKind) {- const d = new Drawing(`warning-${kind}`, `Warning · ${kind}`, "Placeholder sign over a home or building at risk.")- d.asset.category = "construction"- d.asset.reference = { type: "none" }- d.asset.footprint = 1- const at = (x: number, z: number): Vertex => [x / 64, -x / 64, z]- const edge = kind === "fire" ? 0xc4523f : kind === "health" || kind === "sick" ? 0x4f9a6a : kind === "order" ? 0x3d4f6e : 0x8a6a45- d.face([at(-7, 0), at(7, 0), at(7, 14), at(-7, 14)], 0xf6f7f3, 1, edge)- if (kind === "fire") {- d.line([at(-1, 2), at(-3, 5), at(0, 8), at(-2, 11), at(1, 13)], 1.5, 0x77817a)- d.line([at(3, 3), at(2, 6), at(4, 9)], 1, 0x9aa29b)- } else if (kind === "health" || kind === "sick") {- const ring = Array.from({ length: 16 }, (_, i): Vertex => at(Math.cos((i / 16) * Math.PI * 2) * 4.5, 7 + Math.sin((i / 16) * Math.PI * 2) * 4.5))- d.face(ring, kind === "sick" ? 0xc9dfb4 : 0xf1f0e6, 1)- d.face([at(-2.2, 8), at(-1.2, 8), at(-1.2, 9), at(-2.2, 9)], palette.ink, 0)- d.face([at(1.2, 8), at(2.2, 8), at(2.2, 9), at(1.2, 9)], palette.ink, 0)- d.line([at(-2, 4.5), at(0, 5.5), at(2, 4.5)], 1)- } else if (kind === "order") {- d.face([at(-4, 3), at(4, 3), at(4, 11), at(-4, 11)], 0xdbe6ea, 1)- d.line([at(0, 3), at(0, 11)], 1)- d.line([at(-4, 7), at(4, 7)], 1)- d.line([at(-3, 10), at(1, 6), at(-1, 5), at(3, 3.5)], 1.5, 0xc4523f)- } else {- d.line([at(-4, 12), at(-1, 8), at(-3, 6), at(1, 2)], 1.5, 0x8a6a45)- d.line([at(2, 12), at(4, 9)], 1, 0x8a6a45)- }- return d.asset-}--/** Flames over a burning home or building, facing the camera; `phase` 0 or 1 flickers them. */-export function makeFlames(phase: number) {- const d = new Drawing(`flames-${phase}`, "Flames", "Placeholder flames over a burning home or building.")- d.asset.category = "construction"- d.asset.reference = { type: "none" }- d.asset.footprint = 1- const at = (x: number, z: number): Vertex => [x / 64, -x / 64, z]- const tongue = (x: number, w: number, h: number, color: number) =>- d.face([at(x - w, 0), at(x - w * 0.4, h * 0.55), at(x + (phase ? w * 0.3 : -w * 0.3), h), at(x + w * 0.5, h * 0.5), at(x + w, 0)], color, 1, 0xc4523f)- tongue(-5, 4, phase ? 14 : 12, 0xf0a868)- tongue(4, 4, phase ? 11 : 15, 0xf0a868)- tongue(0, 5, phase ? 20 : 18, 0xf3c76b)- return d.asset-}diff --git a/src/asset-lab/primitives.ts b/src/asset-lab/primitives.tsindex f1a0964..6d62a6f 100644--- a/src/asset-lab/primitives.ts+++ b/src/asset-lab/primitives.ts@@ -2,6 +2,7 @@import { U } from "../iso.ts"import type { GoodId, KindId, Tier } from "../content.ts"import type { CartLook, Load, PersonDress } from "../art.ts"+import type { SurfaceState } from "../render3d/surface-state.ts"export type Vertex = readonly [u: number, v: number, height: number]export interface Face {@@ -32,6 +33,8 @@ export type AssetReference =| { type: "roads" | "water" }| { type: "none" }export interface InkAsset {+ effects?: { half: number; height: number; state: SurfaceState }+ appearance?: "fine" | "poor" | "worn" | "winter"category?: AssetCategoryreference?: AssetReferencefootprint?: numberdiff --git a/src/asset-lab/renderer.ts b/src/asset-lab/renderer.tsindex beb01d6..6d2136d 100644--- a/src/asset-lab/renderer.ts+++ b/src/asset-lab/renderer.ts@@ -6,6 +6,7 @@ import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js"import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"import { mergeGeometries, mergeVertices } from "three/addons/utils/BufferGeometryUtils.js"import { palette, type Face, type InkAsset, type Vertex } from "./primitives.ts"+import { installSurfaceShader } from "../render3d/surface-shader.ts"/** A 30° elevation and 45° heading reproduce the game's 64×32 projection.* The vertical conversion preserves pixel-authored building heights exactly. */@@ -100,16 +101,19 @@ function faceMesh(points: ReadonlyArray<Vertex>, color: number, opacity = 1) {const geometry = new THREE.BufferGeometry()geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3))geometry.computeVertexNormals()- return new THREE.Mesh(geometry, fillMaterial(color, opacity))+ const mesh = new THREE.Mesh(geometry, fillMaterial(color, opacity))+ mesh.userData.structureSurface = true+ return mesh}export interface BuiltAsset {group: THREE.GrouplineMaterials: Array<{ material: LineMaterial; width: number }>updateContours: (camera: THREE.Camera) => void+ updateEffects: (time: number) => voiddispose: () => void}-export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; meshInk?: boolean; hullContours?: boolean; meshContours?:boolean } = {}): BuiltAsset {+export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; meshInk?: boolean; hullContours?: boolean; meshContours?:boolean; surfaceEffects?: boolean } = {}): BuiltAsset {const group = new THREE.Group()group.name = asset.idif (options.batchFaces) {@@ -124,12 +128,23 @@ export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; mesconst geometry = mergeGeometries(geometries)if (!geometry) throw new Error("Could not batch map faces")geometries.forEach((g) => g.dispose())- group.add(new THREE.Mesh(geometry, fillMaterial(color, opacity)))+ const mesh = new THREE.Mesh(geometry, fillMaterial(color, opacity))+ mesh.userData.structureSurface = true+ group.add(mesh)}} else {for (const face of asset.faces) group.add(faceMesh(face.points, face.color, face.opacity ?? 1))}const lineMaterials: Array<{ material: LineMaterial; width: number }> = []+ const effectTime = { value: 0 }, effectMaterials: THREE.MeshBasicMaterial[] = []+ if (asset.effects && options.surfaceEffects !== false) {+ const e = asset.effects+ for (const child of group.children) if (child instanceof THREE.Mesh && child.userData.structureSurface) {+ const source = child.material as THREE.MeshBasicMaterial, material = source.clone()+ installSurfaceShader(material, source.color.getHex(THREE.SRGBColorSpace), effectTime, e.state, new THREE.Vector4(e.half * floorScale, e.height / Math.cos(Math.PI / 6), 0.31, 1))+ child.material = material; effectMaterials.push(material)+ }+ }const curveMaterials: Array<THREE.MeshBasicMaterial> = []const curves = new Map<string, { geometries: Array<THREE.BufferGeometry>; color: number; opacity: number }>()const batches = new Map<string, { positions: Array<number>; width: number; color: number; opacity: number }>()@@ -290,10 +305,11 @@ export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; mes})for (const { material } of lineMaterials) material.dispose()curveMaterials.forEach((material) => material.dispose())+ effectMaterials.forEach(m => m.dispose())if (hull) (hull.material as THREE.Material).dispose()for (const object of group.children) if (object instanceof LineSegments2) object.geometry.dispose()}- return { group, lineMaterials, updateContours, dispose }+ return { group, lineMaterials, updateContours, updateEffects: time => { effectTime.value = time }, dispose }}/** GLB uses ordinary meshes for ink strokes so the outlines survive import.@@ -301,6 +317,7 @@ export function buildAsset(asset: InkAsset, options: { batchFaces?: boolean; mesexport async function exportAsset(asset: InkAsset) {const group = new THREE.Group()group.name = asset.id+ if(asset.effects)group.userData.inklineSurfaceEffects=asset.effectsfor (const face of asset.faces) group.add(faceMesh(face.points, face.color, face.opacity ?? 1))const contourFaces = asset.faces.filter((face) => face.contour)const hull = contourFaces.length ? silhouetteMesh(asset, contourFaces) : null@@ -328,6 +345,7 @@ export async function exportAsset(asset: InkAsset) {// Batch like materials before export rather than shipping hundreds of nodes.const merged = new THREE.Group()merged.name = group.name+ merged.userData = { ...group.userData }group.updateMatrixWorld(true)const batches = new Map<THREE.MeshBasicMaterial, Array<THREE.BufferGeometry>>()group.traverse((object) => {diff --git a/src/asset-lab/services.ts b/src/asset-lab/services.tsnew file mode 100644index 0000000..08c6042--- /dev/null+++ b/src/asset-lab/services.ts@@ -0,0 +1,108 @@+import { type KindId } from "../content.ts"+import { U } from "../iso.ts"+import { Drawing, palette, pale, sides, square, type Vertex } from "./primitives.ts"+import { bench, flowerBed } from "./town-props.ts"++export const townBuildingNotes: Partial<Record<KindId, string>> = {+ granary: "Raised grain store with timber braces, a sack hoist, ventilation shutters and grain bins.",+ smokehouse: "Soot-stained flue, drying fish rack, split firewood and a curing barrel.",+ firewatch: "A timber lookout and alarm bell above the red roof; ladder, buckets and a water butt below.",+ healer: "An apothecary with a mortar sign, herb beds, medicine jars and a waiting bench.",+ hospital: "Pale green ward windows, a roof lantern, medical emblems and a waiting bench.",+ watchhouse: "Blue shield, barred windows, a lantern and a street noticeboard.",+ builder: "Open timber racks, trestle workbench, mallet, ladder and dressed stone."+}++export function finishTownBuilding(d: Drawing, id: KindId, a: number, p: number, H: number) {+ const c = (a + p) / 2+ const post = (u: number, v: number, height: number, z = 0) => d.box(u, v, 0.35 * U, 0.35 * U, z, height, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 0.75)+ const ladder = (u: number, v: number, height: number) => {+ for (const x of [-1.2, 1.2]) d.line([[u + x * U, v, 0], [u + x * U, v - 1.5 * U, height]], 1, 0x8a6a45)+ for (let z = 3; z < height; z += 3) d.line([[u - 1.2 * U, v - (z / height) * 1.5 * U, z], [u + 1.2 * U, v - (z / height) * 1.5 * U, z]], 1, 0x8a6a45)+ }+ if (id === "granary") {+ for (const side of sides) {+ const at = (s: number, z: number) => d.wall(side, a, s, z, 0.015)+ for (const x of [-a + U, a - U]) d.line([at(x, 0), at(x, H)], 1.5, 0x9f8b69)+ d.line([at(-a + U, 28), at(0, 40), at(a - U, 28)], 1, 0x9f8b69)+ for (const z of [47, 50, 53]) d.line([at(-2 * U, z), at(2 * U, z)], 1, 0xa99575)+ }+ post(c, -a * 0.4, 43)+ d.line([[c, -a * 0.4, 43], [c, a * 0.5, 43], [c, a * 0.5, 33]], 1.5, 0x8a6a45)+ d.sack(c, a * 0.5, 27)+ for (const y of [-a + U, -a + 4 * U, a - U]) d.sack(c, y)+ d.cylinder(-a - 2 * U, c, 1.5 * U, 0, 7, 0xc4b08b, 0xe9cf7c, 1, 12)+ } else if (id === "smokehouse") {+ d.box(-a / 2, -a / 2, 2.1 * U, 2.1 * U, H + 20, 4, 0x8f988b, 0xb2b9a9, 0x9ea792, 1)+ const y0 = -a - 2.5 * U, y1 = -a + 5 * U+ post(c, y0, 14); post(c, y1, 14)+ d.line([[c, y0, 14], [c, y1, 14]], 1.5, 0x8a6a45)+ for (let i = 1; i <= 3; i++) {+ const y = y0 + (y1 - y0) * i / 4+ d.line([[c, y, 14], [c, y, 11]], 0.75)+ d.ellipsoid(c, y, 8, 0.027, 0.04, 3, 0xb58b64, 1, 0xd5b48c, 12)+ d.face([[c, y - U, 5], [c, y + U, 5], [c, y, 3]], 0xb58b64, 0.75)+ for (const z of [7, 9]) d.line([[c + 0.03, y - 0.02, z], [c + 0.03, y + 0.02, z - 0.5]], 0.5, 0x8a6a45)+ }+ d.cylinder(-a - 2 * U, c, 1.5 * U, 0, 7, 0xbda07a, 0xdbc3a0, 1)+ for (let i = 0; i < 3; i++) d.log("u", c + i * U, -a - U, -a + 3 * U, 0, 1.3, 0xb08a5e, 0xe9d2a8)+ } else if (id === "firewatch") {+ const half = 3 * U, z = H + 13+ for (const [u, v] of square(0, 0, half)) post(u, v, 15, z)+ d.box(0, 0, half + U, half + U, z, 1.5, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 1)+ d.pyramid(half + U, z + 15, 7, pale(0xc4523f, 0.7), pale(0xc4523f, 0.52))+ d.cylinder(0, 0, 1.5 * U, z + 5, 1, 0xc2ac70, 0xe4d29a, 1, 12)+ d.ellipsoid(0, 0, z + 7, U, U, 2, 0xd3bd84, 1, undefined, 12)+ d.line([[0, 0, z + 9], [0, 0, z + 14]], 1)+ ladder(c, -a / 2, 31)+ d.cylinder(c, c, 2 * U, 0, 9, 0xc79a5b, 0xc9dde6, 1)+ for (const y of [-2, 1]) d.cylinder(-a - 2 * U, c + y * U, U, 0, 4, 0xbda07a, 0xa9c5d0, 1, 12)+ } else if (id === "healer" || id === "hospital") {+ for (const side of sides) {+ const at = (s: number, z: number): Vertex => d.wall(side, a, s, z, 0.02), z = id === "hospital" ? 49 : 22+ d.face([at(-2 * U, z), at(2 * U, z), at(2 * U, z + 7), at(-2 * U, z + 7)], 0xeef3e6, 1, 0x809b87)+ d.line([at(0, z + 1.5), at(0, z + 5.5)], 2, 0x719383)+ d.line([at(-U, z + 3.5), at(U, z + 3.5)], 2, 0x719383)+ }+ flowerBed(d, c, -a / 2, 2.5, 0xb29ac2)+ flowerBed(d, -a / 2, c, 2.5, 0xe1cb85)+ bench(d, c, c)+ if (id === "healer") {+ d.box(-a - 2 * U, c, 1.5 * U, 2.5 * U, 0, 6, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 1)+ for (const y of [-1, 1]) {+ d.cylinder(-a - 2 * U, c + y * U, 0.6 * U, 6, 2.5, 0xa8c4b8, 0xd8e8d9, 0.75, 10)+ d.cylinder(-a - 2 * U, c + y * U, 0.3 * U, 8.5, 1, 0xbda07a, 0xbda07a, 0.5, 10)+ }+ d.cylinder(0, 0, 3 * U, H, 4, 0xc1cabb, 0xe9eee3, 1, 16)+ d.line([[0, 0, H + 3], [2 * U, 0, H + 9]], 2, 0x8a6a45)+ } else {+ d.box(0, 0, 4 * U, 4 * U, H, 8, 0xe9eee3, 0xdbe6d8, 0xc9d8cd, 1)+ d.pyramid(4.5 * U, H + 8, 5, 0xe9eee3, 0xc9d8cd)+ for (const side of sides) d.window(side, 4 * U, 0, H + 2, 4, 0xdbe9e7)+ }+ } else if (id === "watchhouse") {+ for (const side of sides) {+ const at = (s: number, z: number) => d.wall(side, a, s, z, 0.02)+ d.face([at(-2 * U, 28), at(2 * U, 28), at(2 * U, 23), at(0, 20), at(-2 * U, 23)], 0xa8bdd1, 1)+ d.line([at(0, 22), at(0, 27)], 1, 0x3d6db5)+ for (const x of [-a / 2, a / 2]) for (const dx of [-0.5, 0.5]) d.line([at(x + dx * U, 12), at(x + dx * U, 20)], 0.75)+ }+ post(c, -a / 2, 20)+ d.box(c, -a / 2, U, U, 15, 4, 0xe5d6a5, 0xf3e6bd, 0xd6c48d, 1)+ for (const x of [-1.5, 1.5]) post(-a / 2 + x * U, c, 15)+ d.box(-a / 2, c, 2 * U, 0.4 * U, 6, 8, 0xd5b994, 0xe9d2a8, 0xbda07a, 1)+ for (const x of [-1, 1]) d.box(-a / 2 + x * U, c + 0.5 * U, 0.6 * U, 0.05 * U, 8, 4, 0xf5f2e6, 0xf5f2e6, 0xe8e4d5, 0.5)+ } else if (id === "builder") {+ for (const y of [-a + U, -a + 5 * U]) post(c, y, 14)+ for (const z of [3, 8, 13]) {+ d.line([[c - U, -a + U, z], [c + U, -a + U, z]], 1, 0x8a6a45)+ d.box(c, -a + 3 * U, U, 3 * U, z, 1, 0xe9c6a0, 0xd8af80, 0xc69867, 0.75)+ }+ for (const y of [-1.5, 1.5]) post(-a / 2, c + y * U, 6)+ d.box(-a / 2, c, 3 * U, 2 * U, 6, 1, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 1)+ d.line([[-a / 2, c, 7], [-a / 2 + U, c, 11]], 1.5, 0x8a6a45)+ d.box(-a / 2 + U, c, U, 0.7 * U, 10, 2, 0x9ca79a, 0xbfc8ba, 0x8f9a8c, 0.75)+ ladder(c, c, 18)+ for (const x of [-1, 1]) d.box(c + x * U, c - 2 * U, U, U, 0, 3, 0xe4e6df, 0xd6d9cf, 0xc2c9bd, 1)+ }+}diff --git a/src/asset-lab/town-props.ts b/src/asset-lab/town-props.tsnew file mode 100644index 0000000..7aeb81d--- /dev/null+++ b/src/asset-lab/town-props.ts@@ -0,0 +1,151 @@+/**+ * Town models for what the town gained with desirability, services,+ * and decay: ornaments (garden, park, fountain, statue, plaza) and ruins.+ * They are built from the same primitives as everything else so they+ * have complete rotatable geometry in the same pale ink palette.+ */+import { kinds, type KindId } from "../content.ts"+import { U } from "../iso.ts"+import { Drawing, palette, square, type Vertex } from "./primitives.ts"++const green = 0xd8e6c9+const leaves = 0xa9c79a+const stone = 0xe4e6e0+const water = 0xc9dde6++const tree = (d: Drawing, u: number, v: number, size = 1) => {+ d.cylinder(u, v, 0.5 * U * size, 0, 8 * size, 0xb08a5e, 0xb08a5e, 1, 8)+ for (const [x, y, z, r] of [[-2, 0, 11, 4], [2, 1, 13, 4.5], [0, -2, 16, 3.5]] as const)+ d.ellipsoid(u + x * U * size, v + y * U * size, z * size, r * U * size, r * U * size, r * size, 0xb7cbaa, 1, 0xe2ead4, 12)+}++export function flowerBed(d: Drawing, u: number, v: number, width = 3, color = 0xc78374) {+ d.box(u, v, width * U, 1.2 * U, 0, 2, 0xbac9a4, 0xe4d7bd, 0xd0c2a8, 1)+ for (let i = -1; i <= 1; i++) {+ const x = u + i * width * U * 0.65+ d.ellipsoid(x, v, 3, U, U, 1.2, leaves, 0, undefined, 8)+ d.ellipsoid(x, v, 4.2, 0.6 * U, 0.6 * U, 0.7, color, 0.5, undefined, 8)+ }+}+export function bench(d: Drawing, u: number, v: number) {+ for (const x of [-2.5, 2.5]) d.box(u + x * U, v, 0.4 * U, 1.2 * U, 0, 4, palette.ink, palette.ink, palette.ink, 0.75)+ for (const y of [-0.7, 0.7]) d.box(u, v + y * U, 3.5 * U, 0.55 * U, 4, 1, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 0.75)+ for (const z of [6, 8]) d.box(u, v - 1.3 * U, 3.5 * U, 0.35 * U, z, 1, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 0.75)+}+/** Raised staggered setts share a pitch across neighbouring road cells. */+export function setts(d: Drawing, x: number, y: number, half: number, z: number) {+ const pitch = 0.125+ for (let row = Math.floor((y - half) / pitch); row < Math.ceil((y + half) / pitch); row++) {+ const shift = Math.abs(row % 2) * pitch / 2+ for (let col = Math.floor((x - half - shift) / pitch); col < Math.ceil((x + half - shift) / pitch); col++) {+ const l = Math.max(x - half, col * pitch + shift), r = Math.min(x + half, (col + 1) * pitch + shift),+ b = Math.max(y - half, row * pitch), t = Math.min(y + half, (row + 1) * pitch)+ if (r - l < 0.02 || t - b < 0.02) continue+ const shade = (row * 7 + col * 3) % 4 === 0 ? 0xdce0d8 : 0xe7e9e2+ d.box((l + r) / 2, (b + t) / 2, (r - l) / 2 - 0.005, (t - b) / 2 - 0.005, z, 0.22, shade, 0xc6ccc3, 0xbfc6bc, 0.5, 0xa0aaa0)+ }+ }+}++const figure = (d: Drawing, u: number, v: number, z: number) => {+ d.box(u, v, 3.3 * U, 3.3 * U, z - 6, 2)+ d.box(u, v, 2.5 * U, 2.5 * U, z - 4, 7, stone, 0xd5d9d0, 0xbec5bb)+ d.face([[u + 2.51 * U, v - U, z - 2], [u + 2.51 * U, v + U, z - 2], [u + 2.51 * U, v + U, z + 1], [u + 2.51 * U, v - U, z + 1]], 0xc1af81, 0.75)+ for (const x of [-0.7, 0.7]) d.cylinder(u + x * U, v, 0.55 * U, z + 3, 5, 0xaebbb0, 0xc9d2c7, 0.75, 8)+ d.ellipsoid(u, v, z + 11, 1.7 * U, 1.3 * U, 4, 0xaebbb0, 1, 0xc9d2c7, 12)+ d.ellipsoid(u, v, z + 16.3, 1.1 * U, 1.1 * U, 1.8, 0xc9d2c7, 1, undefined, 12)+ d.cylinder(u, v, 1.7 * U, z + 17.2, 0.5, 0xaebbb0, 0xc9d2c7, 0.75, 12)+ d.line([[u - 1.2 * U, v, z + 13], [u - 2.4 * U, v, z + 10], [u - 2.4 * U, v, z + 7]], 2, 0xaebbb0)+ d.box(u - 2.4 * U, v, U, 0.5 * U, z + 6, 3, 0xc9d2c7, 0xaebbb0, 0x9daa9f, 1)+ d.line([[u + 1.2 * U, v, z + 13], [u + 2.8 * U, v, z + 14], [u + 2.8 * U, v, z + 20]], 2, 0xaebbb0)+ d.face([[u + 2.8 * U, v, z + 19], [u + 5 * U, v, z + 17], [u + 2.8 * U, v, z + 16]], 0xc9d2c7, 1)+}++/** An ornament of `id`, `size` cells a side, on its plate. */+export function makeDecor(id: KindId) {+ const kind = kinds[id],+ p = (kind.size * 8 - 1) * U+ const d = new Drawing(id, kind.title, "Planting beds, carved stone and timber furniture in the town's pale ink palette.")+ d.asset.category = "buildings"+ d.asset.reference = { type: "building", kind: id }+ d.asset.footprint = kind.size+ d.face(square(0, 0, p, -0.15), id === "plaza" || id === "statue" || id === "fountain" ? stone : green)+ if (id === "garden") {+ d.box(0, 0, p, U, 0, 0.3, 0xeee9de, 0xe3ddcf, 0xd5d0c4, 0.75)+ tree(d, -p / 2, -p / 2, 0.7)+ tree(d, p / 2, p / 2, 0.8)+ flowerBed(d, p / 2, -p / 2, 2, 0xc78374)+ flowerBed(d, -p / 2, p / 2, 2, 0xd6ba69)+ } else if (id === "park") {+ tree(d, -p / 2, -p / 2, 1.1)+ tree(d, p / 2, -p / 3, 0.9)+ tree(d, -p / 3, p / 2, 1)+ d.box(0, 0, p, U, 0, 0.3, 0xeee9de, 0xe3ddcf, 0xd5d0c4, 0.75)+ bench(d, p / 2, p / 2)+ flowerBed(d, p / 2, p * 0.8, 3, 0xb29ac2)+ } else if (id === "fountain") {+ d.cylinder(0, 0, 5.5 * U, 0, 4, 0xdfe3dc, water, 1, 16)+ d.cylinder(0, 0, 1.2 * U, 4, 7, 0xdfe3dc, stone, 1, 10)+ d.cylinder(0, 0, 2.5 * U, 11, 2, 0xdfe3dc, water, 1, 12)+ d.cylinder(0, 0, 4.6 * U, 4.03, 0.2, water, 0xd8e8ee, 0.75, 24)+ d.ellipsoid(0, 0, 15, U, U, 1.8, stone, 1, undefined, 12)+ for (let i = 0; i < 4; i++) {+ const a = i * Math.PI / 2+ d.line(Array.from({ length: 9 }, (_, j): Vertex => { const t = j / 8; return [Math.cos(a) * (1 + 3 * t) * U, Math.sin(a) * (1 + 3 * t) * U, 13 + 2 * Math.sin(t * Math.PI) - 8 * t] }), 1, 0x8faebd)+ }+ for (const r of [2.5, 3.5]) d.line(Array.from({ length: 25 }, (_, i): Vertex => [Math.cos(i * Math.PI / 12) * r * U, Math.sin(i * Math.PI / 12) * r * U, 4.3]), 0.75, 0xa9c5d0)+ } else if (id === "statue") {+ setts(d, 0, 0, p - 0.02, 0)+ figure(d, 0, 0, 6)+ } else if (id === "plaza") {+ setts(d, 0, 0, p - 0.02, 0)+ figure(d, 0, 0, 6)+ tree(d, -p * 0.75, -p * 0.75, 0.7)+ tree(d, p * 0.75, p * 0.75, 0.7)+ bench(d, p * 0.6, -p * 0.7)+ bench(d, -p * 0.6, p * 0.7)+ }+ if (id === "garden" || id === "park") for (const y of [-p + U, p - U]) {+ for (let x = -p + U; x <= p - U; x += 2 * U) d.box(x, y, 0.25 * U, 0.25 * U, 0, 5, 0xe9d2a8, 0xd0b58c, 0xb08a5e, 0.75)+ d.line([[-p + U, y, 3], [p - U, y, 3]], 1, 0xb08a5e)+ }+ return d.asset+}++/** What is left of a home or building: charred, tumbled down, or boarded up. */+export function makeRuin(size: number, cause: "burnt" | "collapsed" | "derelict") {+ const d = new Drawing(`ruin-${cause}-${size}`, `Ruin · ${cause}`, "Exposed masonry, fallen rafters, roof tiles and weeds; each cause leaves a different silhouette.")+ d.asset.category = "construction"+ d.asset.reference = { type: "none" }+ d.asset.footprint = size+ const p = (size * 8 - 1) * U,+ a = p - 2 * U+ const wall = cause === "burnt" ? 0x9c9b90 : cause === "collapsed" ? 0xe2ddd0 : 0xd9d4c7+ d.face(square(0, 0, p, -0.15), cause === "burnt" ? 0xb9b5ab : 0xe9e6dd)+ if (cause === "derelict") {+ d.box(0, 0, a, a, 0, 16, 0xe3ddcf, wall, 0xc4c8bb)+ d.gable(a, 16, 5, "x", 0xd5cbb3, 0xb9b09a, false)+ for (const side of ["right", "left", "backRight", "backLeft"] as const) {+ d.window(side, a, 0, 5, 6, 0x7f8982)+ for (const z of [5, 8]) d.line([d.wall(side, a, -2 * U, z, 0.02), d.wall(side, a, 2 * U, z + 1, 0.02)], 2, 0xb08a5e)+ d.line([d.wall(side, a, -a / 2, 14, 0.02), d.wall(side, a, -a / 3, 10, 0.02), d.wall(side, a, -a / 2, 7, 0.02)], 1, 0x8d9589)+ }+ for (const x of [-a, a]) for (const j of [-1, 0, 1]) d.line([[x, a / 2, 0], [x + j * U, a / 2, 3 + Math.abs(j)]], 0.75, 0x95ab81)+ return d.asset+ }+ const pieces: ReadonlyArray<readonly [number, number, number]> = [[-a, -a, 7], [a * 0.3, -a, 4], [-a, a * 0.2, 5], [a * 0.6, a * 0.6, 3]]+ for (const [u, v, h] of pieces) d.box(u + U, v + U, 1.2 * U * size, 1.2 * U * size, 0, h, wall, wall, 0xc4bfb2, 1)+ for (const side of [-1, 1]) {+ d.face([[-a, side * a, 0], [a, side * a, 0], [a, side * a, 4], [a * 0.4, side * a, 4], [a * 0.4, side * a, 9], [0, side * a, 7], [-a / 3, side * a, 13], [-a, side * a, 10]], wall, 1.5)+ for (const z of [3, 6]) d.line([[-a, side * (a + 0.005), z], [0, side * (a + 0.005), z]], 0.75, 0xa6ad9f)+ }+ d.box(-a * 0.65, -a * 0.5, U, U, 0, cause === "burnt" ? 20 : 11, 0xdbd6c8, wall, 0xa6aa9c, 1)+ for (let i = 0; i < 6; i++) {+ const x = -a * 0.7 + (i % 3) * a * 0.65, y = -a * 0.2 + Math.floor(i / 3) * a * 0.7+ d.face([[x, y, 3], [x + 2 * U, y, 2], [x + 2 * U, y + U, 1], [x, y + U, 2]], cause === "burnt" ? 0x818577 : 0xc3a18f, 0.75)+ }+ if (cause === "burnt") for (let i = 0; i < 3; i++) d.line([[-a + i * a * 0.6, -a * 0.5, 0.5], [-a + i * a * 0.7 + a * 0.4, a * 0.4, 3]], 2, 0x3d4943)+ else for (let i = 0; i < 4; i++) d.box(-a * 0.2 + i * U * 2, a * 0.1, U, U, 0, 1.5, wall, wall, wall, 1)+ return d.asset+}+diff --git a/src/effects-lab/main.ts b/src/effects-lab/main.tsnew file mode 100644index 0000000..7046d54--- /dev/null+++ b/src/effects-lab/main.ts@@ -0,0 +1,93 @@+import * as THREE from "three"+import { house } from "../asset-lab/homes.ts"+import { home, type Tier } from "../content.ts"+import { U } from "../iso.ts"+import { ModelHandle,ModelPool } from "../render3d/pool.ts"+import { surfaceState,type SurfaceState } from "../render3d/surface-state.ts"+import { StructureEffects } from "../render3d/structure-effects.ts"+import "./style.css"++const cases: Array<{title:string;note:string;state:Partial<SurfaceState>}>=[+ {title:"Sound house",note:"The original house, without an effect.",state:{}},+ {title:"Cared for",note:"Fresh plaster and warm window light.",state:{care:1}},+ {title:"Neglected",note:"Stained plaster, exposed brick, cracks and roof moss.",state:{wear:0.95}},+ {title:"Fire warning",note:"Smoke escapes from the roof; heat colours the eaves.",state:{fireRisk:1,wear:0.2}},+ {title:"Sickness",note:"Damp green stains and unhealthy window light.",state:{health:1,sick:1,wear:0.3}},+ {title:"Unrest",note:"Fractures in the actual glazing; darkened windows.",state:{order:1,wear:0.3}},+ {title:"Winter",note:"Snow covers the existing roof surfaces.",state:{snow:1}},+ {title:"Burning",note:"Roof fire, rising smoke, embers, soot and flickering windows.",state:{burning:1,wear:0.4}}+]+const root=document.querySelector<HTMLElement>("#effects-lab")!+root.innerHTML=`<header><a href="/model-review.html">Inkline Town</a><span>LIVE MATERIAL & PARTICLE STUDY</span><a href="/">Play the town ↗</a></header><section class="intro"><h1>One house.<br>Eight conditions.</h1><p>These are actual renders of the shared game mesh. Surface shaders change its condition; particles emit from its roof. Drag to turn the view.</p></section><section class="controls"><label>House <select aria-label="House tier"><option value="1">Settler cottage</option><option value="2" selected>Citizen home</option><option value="3">Townhouse</option></select></label><label>Rotation <input aria-label="Rotation" id="rotation" type="range" min="-180" max="180" value="0"><output id="angle">0°</output></label><label>Effect strength <input aria-label="Effect strength" id="strength" type="range" min="0" max="100" value="100"><output id="amount">100%</output></label><button id="pause">Pause animation</button><button id="rear">See the back</button></section><section class="grid" aria-label="House effects"></section><footer><span id="stats"></span><span>Same mesh · Surface shaders · Roof particles · Drag to rotate</span></footer>`+const grid=root.querySelector<HTMLElement>(".grid")!, renderer=new THREE.WebGLRenderer({alpha:true,antialias:true,preserveDrawingBuffer:true}),scene=new THREE.Scene(),pool=new ModelPool(),camera=new THREE.OrthographicCamera(-100,100,100,-100,0.1,4000)+renderer.setPixelRatio(Math.min(devicePixelRatio,2));renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.setClearColor(0xf0f2ec,0)+renderer.domElement.className="rendering";document.body.append(renderer.domElement);scene.add(pool.root)+const views=cases.map((c,i)=>{+ const card=document.createElement("article")+ card.innerHTML=`<div class="render-view" role="img" aria-label="${c.title}"></div><div class="caption"><h2>${c.title}</h2><p>${c.note}</p></div>`;grid.append(card)+ if(i===7){const b=document.createElement("button");b.textContent="Fire close-up";card.querySelector(".caption")!.append(b);b.onclick=()=>{card.classList.toggle("close-up");b.textContent=card.classList.contains("close-up")?"Back to overview":"Fire close-up";card.scrollIntoView({block:"start"})}}+ const handle=new ModelHandle(pool),anchor=new THREE.Group();anchor.position.x=i*200;anchor.add(handle.root);scene.add(anchor)+ return{card,handle,anchor,effects:null as StructureEffects|null,view:card.querySelector<HTMLElement>(".render-view")!}+})+let tier:Tier=2,yaw=0,strength=1,time=0,paused=false,last=0,frame=0+function build(){+ const asset=house(tier,0.28,"preview",{doors:{right:true,left:false}}),H=home.tiers[tier].height,half=(home.half+(tier>=2?1:0))*U*32*Math.SQRT2+ views.forEach(v=>{+ v.handle.use(`house/${tier}`,()=>asset);v.handle.effectBounds.set(half,H/Math.cos(Math.PI/6),0.31,1)+ v.effects?.dispose();v.effects=new StructureEffects(asset,H);v.anchor.add(v.effects.group)+ })+}+function stateAt(i:number){return surfaceState(Object.fromEntries(Object.entries(cases[i]!.state).map(([k,v])=>[k,v*strength])))}+function update(t:number){+ time=t;pool.time.value=t+ views.forEach((v,i)=>{const s=stateAt(i);v.handle.effects=s;v.effects!.set(s);v.effects!.update(t)})+ scene.updateMatrixWorld(true);pool.flush()+}+function aim(i:number,width:number,height:number){+ const H=home.tiers[tier].height,vertical=(H+28)/Math.cos(Math.PI/6)*1.35,heading=(45+yaw)*Math.PI/180,+ target=new THREE.Vector3(i*200,(H+8)/Math.cos(Math.PI/6)/2,0)+ camera.top=vertical/2;camera.bottom=-camera.top;camera.left=-vertical*width/height/2;camera.right=-camera.left+ camera.position.copy(target).add(new THREE.Vector3(Math.sin(heading)*866,500,Math.cos(heading)*866));camera.lookAt(target);camera.updateProjectionMatrix();camera.updateMatrixWorld()+ camera.getWorldDirection(pool.viewDirection).negate()+}+function render(){+ renderer.setSize(innerWidth,innerHeight,false);renderer.setScissorTest(false);renderer.clear();renderer.setScissorTest(true)+ views.forEach((v,i)=>{+ const r=v.view.getBoundingClientRect();if(r.bottom<=0||r.top>=innerHeight)return+ aim(i,r.width,r.height)+ renderer.setViewport(r.left,innerHeight-r.bottom,r.width,r.height)+ renderer.setScissor(Math.max(0,r.left),Math.max(0,innerHeight-r.bottom),Math.min(innerWidth,r.right)-Math.max(0,r.left),Math.min(innerHeight,r.bottom)-Math.max(0,r.top))+ renderer.render(scene,camera)+ })+ root.querySelector("#stats")!.textContent=`1 active house mesh · ${views.length} instances · ${time.toFixed(1)} s`+ frame+++}+/** Captures the same GPU scene at a reproducible animation time. */+function capture(t=time,focus=false){+ update(t)+ const canvas=document.createElement("canvas"),ctx=canvas.getContext("2d")!,width=focus?960:320,height=focus?600:300,viewHeight=focus?520:230+ canvas.width=960;canvas.height=focus?680:1000;ctx.fillStyle="#f0f2ec";ctx.fillRect(0,0,canvas.width,canvas.height)+ ctx.fillStyle="#3d4943";ctx.font="30px Georgia";ctx.fillText("Inkline Town / effects on one house",24,40)+ ctx.font="12px monospace";ctx.fillText(`${home.tiers[tier].title} · shared mesh · ${t.toFixed(2)} s`,24,65)+ renderer.setPixelRatio(1);renderer.setSize(width,viewHeight,false);renderer.setScissorTest(false)+ const indices=focus?[7]:views.map((_,i)=>i)+ indices.forEach((i,index)=>{+ aim(i,width,viewHeight);renderer.setViewport(0,0,width,viewHeight);renderer.render(scene,camera)+ const x=index%3*width,y=85+Math.floor(index/3)*height+ ctx.drawImage(renderer.domElement,x,y,width,viewHeight);ctx.fillStyle="#3d4943";ctx.font="19px Georgia";ctx.fillText(cases[i]!.title,x+20,y+viewHeight+30)+ })+ renderer.setPixelRatio(Math.min(devicePixelRatio,2));render();return canvas.toDataURL()+}+root.querySelector<HTMLSelectElement>("select")!.onchange=e=>{tier=Number((e.target as HTMLSelectElement).value) as Tier;build();update(time);render()}+root.querySelector<HTMLInputElement>("#rotation")!.oninput=e=>{yaw=Number((e.target as HTMLInputElement).value);root.querySelector("#angle")!.textContent=`${yaw}°`;render()}+root.querySelector<HTMLInputElement>("#strength")!.oninput=e=>{strength=Number((e.target as HTMLInputElement).value)/100;root.querySelector("#amount")!.textContent=`${Math.round(strength*100)}%`;update(time);render()}+root.querySelector<HTMLButtonElement>("#pause")!.onclick=e=>{paused=!paused;(e.target as HTMLButtonElement).textContent=paused?"Resume animation":"Pause animation"}+root.querySelector<HTMLButtonElement>("#rear")!.onclick=()=>{yaw=yaw===180?0:180;root.querySelector<HTMLInputElement>("#rotation")!.value=String(yaw);root.querySelector("#angle")!.textContent=`${yaw}°`;render()}+let drag:{x:number;yaw:number}|null=null+grid.onpointerdown=e=>{if(!(e.target as HTMLElement).classList.contains("render-view"))return;drag={x:e.clientX,yaw};grid.setPointerCapture(e.pointerId)}+grid.onpointermove=e=>{if(drag){yaw=((drag.yaw+(e.clientX-drag.x)*0.5+540)%360)-180;render()}}+grid.onpointerup=grid.onpointercancel=()=>{drag=null}+build();update(0)+renderer.setAnimationLoop(now=>{const dt=last?Math.min((now-last)/1000,0.1):0;last=now;if(!paused)update(time+dt);render()})+Object.assign(window,{effectsLab:{capture,pause:()=>{paused=true},stats:()=>({tier,yaw,time,frame,templates:pool.stats().templates,activeTemplates:new Set(views.map(v=>v.handle.template)).size,models:pool.stats().models})}})+if(import.meta.hot)import.meta.hot.dispose(()=>{renderer.setAnimationLoop(null);views.forEach(v=>v.effects?.dispose());pool.dispose();renderer.dispose();renderer.domElement.remove()})diff --git a/src/effects-lab/style.css b/src/effects-lab/style.cssnew file mode 100644index 0000000..34c8da8--- /dev/null+++ b/src/effects-lab/style.css@@ -0,0 +1,3 @@+*{box-sizing:border-box}body{margin:0;background:#f0f2ec;color:#3d4943;font-family:Georgia,serif}#effects-lab{max-width:1400px;margin:auto;padding:24px 40px}a{color:inherit;text-underline-offset:4px}header{display:flex;justify-content:space-between;border-bottom:1px solid #c9d1c1;padding:0 0 18px;font:12px monospace}header a:first-child{font:bold 18px Georgia}.intro{display:flex;align-items:center;justify-content:space-between;gap:40px;padding:24px 0}h1{font-size:46px;line-height:1.04;font-weight:normal;margin:0}.intro p{max-width:500px;font:14px/1.7 system-ui;color:#717d68}.controls{display:flex;gap:20px;align-items:center;flex-wrap:wrap;border-block:1px solid #c9d1c1;padding:16px 0;margin-bottom:22px;font:12px system-ui}label{display:flex;gap:8px;align-items:center}input{width:125px;accent-color:#728460}select,button{font:12px system-ui;color:inherit;background:transparent;border:1px solid #bcc7b4;padding:9px;border-radius:4px;cursor:pointer}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px}article{border:1px solid #c9d1c1;border-radius:4px;background:#f7f8f3;overflow:hidden}.render-view{height:280px;cursor:grab;touch-action:pan-y}.caption{border-top:1px solid #dce2d4;padding:16px;position:relative;z-index:2}h2{font-size:21px;font-weight:normal;margin:0 0 8px}.caption p{font:12px/1.6 system-ui;color:#717d68;margin:0;min-height:38px}.rendering{position:fixed;inset:0;pointer-events:none;z-index:1}header,.intro,.controls,footer{position:relative;z-index:2}footer{display:flex;justify-content:space-between;gap:20px;padding:24px 0;font:11px/1.6 monospace;color:#717d68}@media(max-width:900px){#effects-lab{padding:20px}.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.intro{display:block}.intro p{max-width:none}}@media(max-width:540px){.grid{grid-template-columns:1fr}header span{display:none}.controls{gap:12px}.render-view{height:290px}h1{font-size:38px}footer{display:block}}+article.close-up{grid-column:1/-1}article.close-up .render-view{height:500px}.caption button{margin-top:10px}+canvas.rendering{width:100%;height:100%}diff --git a/src/map-lab/map.ts b/src/map-lab/map.tsindex 0f86d0c..5341dde 100644--- a/src/map-lab/map.ts+++ b/src/map-lab/map.ts@@ -121,7 +121,7 @@ const layout: Array<[string, number, number]> = [["fishery", 13, 1]]for (const [id, x, y] of layout) place(id, x, y)-// The newer quarter: services, food stores, and ornaments (placeholder models), along the south-west street.+// Services, food stores and ornaments along the south-west street.const quarter: Array<[string, number, number]> = [["firewatch", -17, -2],["healer", -17, 1],@@ -137,6 +137,10 @@ const quarter: Array<[string, number, number]> = [["plaza", 9, -8]]for (const [id, x, y] of quarter) place(id, x, y)+// The review annex gives seasonal/condition variants their own ground,+// keeping them apart from the functioning town streets.+face([[-20, 17, -0.5], [18, 17, -0.5], [18, 29, -0.5], [-20, 29, -0.5]], 0xf0f2ec, true)+inkAssets.filter(a => a.category === "buildings" && a.appearance).forEach((a, i) => place(a.id, -17 + (i % 7) * 5, 18 + Math.floor(i / 7) * 5))const homes = inkAssets.filter((a) => a.category === "homes")homes.forEach((a, i) => place(a.id, -7 + (i % 4) * 1.8, 6 + Math.floor(i / 4) * 2))const trees = inkAssets.filter((a) => a.reference?.type === "tree")@@ -145,6 +149,7 @@ for (let i = 0; i < 18; i++) place(trees[i % trees.length]!.id, -8 + (i % 9) * 2inkAssets.filter((a) => a.reference?.type === "rock").forEach((a, i) => place(a.id, -16 + (i % 2) * 1.5, 4 + Math.floor(i / 2) * 1.5))inkAssets.filter((a) => a.reference?.type === "field").forEach((a, i) => place(a.id, -8 + (i % 2) * 1.2, -10 + Math.floor(i / 2) * 1.2))place("roads", 15, 8)+place("paved-street", 15, 12)place("water", 7, 14)// A cargo yard at the quay. Every product has a handcart and a barrow,@@ -219,6 +224,7 @@ export const districts = {homes: { title: "Homes", x: -4, y: 7, zoom: 5 },people: { title: "People", x: 0, y: -2, zoom: 7 },cargo: { title: "Cargo yard", x: 7, y: 7, zoom: 4 },- forest: { title: "Forest & farms", x: -10, y: -11, zoom: 3.2 }+ forest: { title: "Forest & farms", x: -10, y: -11, zoom: 3.2 },+ variants: { title: "Winter & wear", x: -2, y: 21, zoom: 2.3 }} as constexport const testMap = { asset: town, buildings, effects, trees: trees.length + 18, roads: roads.size, coverage: represented.size }diff --git a/src/model-review/main.ts b/src/model-review/main.tsnew file mode 100644index 0000000..14807f9--- /dev/null+++ b/src/model-review/main.ts@@ -0,0 +1,115 @@+import * as THREE from "three"+import { assetById } from "../asset-lab/assets.ts"+import { buildAsset, exportAsset } from "../asset-lab/renderer.ts"+import "./style.css"++const families = {+ buildings: { title: "Buildings", ids: ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] },+ ornaments: { title: "Gardens & squares", ids: ["garden", "park", "fountain", "statue", "plaza", "paved-street"] },+ homes: { title: "Homes & neighbourhoods", ids: ["cottage", "citizen", "townhouse", "cottage-fine", "citizen-fine", "townhouse-fine", "cottage-poor", "citizen-worn", "townhouse-worn"] },+ winter: { title: "Winter", ids: ["cottage-winter", "citizen-winter", "townhouse-winter", "granary-winter", "smokehouse-winter", "firewatch-winter", "healer-winter", "hospital-winter", "watchhouse-winter", "builder-winter"] },+ hazards: { title: "Ruins", ids: ["ruin-burnt-1", "ruin-collapsed-1", "ruin-derelict-1"] },+ people: { title: "People & cargo", ids: ["service-watchman", "service-firefighter", "service-physician", "service-constable", "service-builder", "goods-smoked", "cart-smoked-4", "barrow-smoked-4"] },+ wear: { title: "Building condition", ids: ["granary-worn", "smokehouse-worn", "firewatch-worn", "healer-worn", "hospital-worn", "watchhouse-worn", "builder-worn"] }+} as const+type Family = keyof typeof families+const root = document.querySelector<HTMLElement>("#review")!+root.innerHTML = `<header><a href="/">Inkline Town</a><span>PR 03 / MODEL REVIEW</span><a href="/map-lab.html">Town map ↗</a></header>+ <section class="intro"><div><p class="eyebrow">A town with a little more life</p><h1>New places.<br>The same ink.</h1><p>Inspect the models together, turn them around, then open any one for a closer look.</p></div><aside>7 buildings<br>5 ornaments<br>3 home tiers<br><span>Plus people, hazards, paving,<br>snow and signs of wear.</span></aside></section>+ <nav aria-label="Model collections"></nav><section class="camera"><label>Turn the models <input aria-label="Model rotation" type="range" min="-180" max="180" value="0"><output>0°</output></label><button id="rear">See the back</button><button id="reset">Reset view</button><button id="sheet">Save model sheet</button><a id="sheet-link" hidden download>Download sheet ↗</a><label>View <select aria-label="View elevation"><option value="30">Street angle</option><option value="50">From above</option><option value="15">Near the ground</option></select></label></section>+ <section class="grid" aria-label="3D models"></section><footer><a href="/effects-lab.html">Animated house effects ↗</a> · Drag a model to turn the collection · <a href="/asset-lab.html">Full asset catalogue ↗</a> · <a href="/">Play this town ↗</a></footer>`+const nav = root.querySelector("nav")!, grid = root.querySelector<HTMLElement>(".grid")!, rotation = root.querySelector<HTMLInputElement>("input")!, elevation = root.querySelector<HTMLSelectElement>("select")!+const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true, preserveDrawingBuffer: true })+renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); renderer.outputColorSpace = THREE.SRGBColorSpace+renderer.setClearColor(0xf0f2ec, 0); renderer.setScissorTest(true)+renderer.domElement.className = "models"; document.body.append(renderer.domElement)+let family: Family = "buildings", yaw = 0, pitch = 30, renders = 0+let sheetUrl = ""+let models: Array<{ scene: THREE.Scene; camera: THREE.OrthographicCamera; built: ReturnType<typeof buildAsset>; view: HTMLElement; center: THREE.Vector3; size: THREE.Vector3 }> = []+function render() {+ renderer.setSize(innerWidth, innerHeight, false)+ renderer.setScissorTest(false); renderer.clear(); renderer.setScissorTest(true)+ for (const model of models) {+ const r = model.view.getBoundingClientRect()+ if (r.bottom <= 0 || r.top >= innerHeight) continue+ const heading = (45 + yaw) * Math.PI / 180, angle = pitch * Math.PI / 180,+ extent = Math.max(model.size.y, Math.hypot(model.size.x, model.size.z) * 0.75, 18) * 1.3,+ vertical = Math.max(extent, Math.hypot(model.size.x, model.size.z) * r.height / r.width * 1.4), camera = model.camera+ camera.top = vertical / 2; camera.bottom = -camera.top; camera.left = -vertical * r.width / r.height / 2; camera.right = -camera.left+ camera.position.copy(model.center).add(new THREE.Vector3(Math.sin(heading) * Math.cos(angle), Math.sin(angle), Math.cos(heading) * Math.cos(angle)).multiplyScalar(1000))+ camera.lookAt(model.center); camera.updateProjectionMatrix(); camera.updateMatrixWorld()+ model.built.updateContours(camera)+ renderer.setViewport(r.left, innerHeight - r.bottom, r.width, r.height)+ renderer.setScissor(Math.max(0, r.left), Math.max(0, innerHeight - r.bottom), Math.min(innerWidth, r.right) - Math.max(0, r.left), Math.min(innerHeight, r.bottom) - Math.max(0, r.top))+ renderer.render(model.scene, camera)+ }+ root.querySelector("output")!.textContent = `${Math.round(yaw)}°`; rotation.value = String(yaw); renders+++}+function select(next: Family) {+ if (sheetUrl) URL.revokeObjectURL(sheetUrl)+ sheetUrl = ""; root.querySelector<HTMLAnchorElement>("#sheet-link")!.hidden = true+ family = next; models.forEach(m => m.built.dispose()); models = []; grid.replaceChildren()+ for (const [i, id] of families[family].ids.entries()) {+ const asset = assetById.get(id)!+ if (!asset) throw new Error(`Missing review model: ${id}`)+ const card = document.createElement("article")+ card.innerHTML = `<div class="card-top"><span>${String(i + 1).padStart(2, "0")}</span><a href="/asset-lab.html?asset=${id}">Inspect ↗</a></div><div class="model-view" role="img" aria-label="${asset.title} 3D model"></div><div class="caption"><h2>${asset.title}</h2><p>${asset.note}</p><button class="export">Download GLB</button></div>`+ grid.append(card)+ const built = buildAsset(asset, {batchFaces: true}), scene = new THREE.Scene(), camera = new THREE.OrthographicCamera(-100, 100, 100, -100, 0.1, 4000)+ scene.add(built.group); scene.updateMatrixWorld(true)+ const bounds = new THREE.Box3().setFromObject(built.group)+ models.push({built, scene, camera, view: card.querySelector<HTMLElement>(".model-view")!, center: bounds.getCenter(new THREE.Vector3()), size: bounds.getSize(new THREE.Vector3())})+ card.querySelector<HTMLButtonElement>(".export")!.onclick = async () => {+ const url = URL.createObjectURL(new Blob([await exportAsset(asset)], {type: "model/gltf-binary"})), a = document.createElement("a")+ a.href = url; a.download = `inkline-${id}.glb`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000)+ }+ }+ nav.querySelectorAll("button").forEach(b => { b.setAttribute("aria-pressed", String(b.dataset.family === next)) })+ history.replaceState(null, "", `?collection=${next}`); render()+}+for (const [id, group] of Object.entries(families)) {+ const b = document.createElement("button"); b.textContent = group.title; b.dataset.family = id; b.onclick = () => select(id as Family); nav.append(b)+}+rotation.oninput = () => { yaw = Number(rotation.value); render() }+elevation.onchange = () => { pitch = Number(elevation.value); render() }+root.querySelector<HTMLButtonElement>("#rear")!.onclick = () => { yaw = yaw === 180 ? 0 : 180; render() }+root.querySelector<HTMLButtonElement>("#reset")!.onclick = () => { yaw = 0; pitch = 30; elevation.value = "30"; render() }+root.querySelector<HTMLButtonElement>("#sheet")!.onclick = () => {+ const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d")!, columns = 3, width = 400, height = 350+ canvas.width = columns * width; canvas.height = 100 + Math.ceil(models.length / columns) * height+ ctx.fillStyle = "#f0f2ec"; ctx.fillRect(0, 0, canvas.width, canvas.height)+ ctx.fillStyle = "#3d4943"; ctx.font = "30px Georgia"; ctx.fillText(`Inkline Town / ${families[family].title}`, 30, 48)+ ctx.font = "13px monospace"; ctx.fillText(`PR 03 · ${Math.round(yaw)}° rotation · ${pitch}° elevation`, 30, 76)+ renderer.setSize(width, 270, false); renderer.setScissorTest(false)+ models.forEach((model, i) => {+ const camera = model.camera, heading = (45 + yaw) * Math.PI / 180, angle = pitch * Math.PI / 180,+ vertical = Math.max(model.size.y, Math.hypot(model.size.x, model.size.z) * 0.75, 18) * 1.3+ camera.top = vertical / 2; camera.bottom = -camera.top; camera.left = -vertical * width / 270 / 2; camera.right = -camera.left+ camera.position.copy(model.center).add(new THREE.Vector3(Math.sin(heading) * Math.cos(angle), Math.sin(angle), Math.cos(heading) * Math.cos(angle)).multiplyScalar(1000))+ camera.lookAt(model.center); camera.updateProjectionMatrix(); camera.updateMatrixWorld(); model.built.updateContours(camera)+ renderer.setViewport(0, 0, width, 270); renderer.render(model.scene, camera)+ const x = (i % columns) * width, y = 100 + Math.floor(i / columns) * height+ ctx.drawImage(renderer.domElement, x, y, width, 270)+ ctx.fillStyle = "#3d4943"; ctx.font = "21px Georgia"; ctx.fillText(assetById.get(families[family].ids[i]!)!.title, x + 24, y + 305)+ ctx.strokeStyle = "#cbd1c5"; ctx.strokeRect(x + 12, y + 8, width - 24, height - 20)+ })+ render()+ canvas.toBlob(blob => {+ if (!blob) return+ if (sheetUrl) URL.revokeObjectURL(sheetUrl)+ sheetUrl = URL.createObjectURL(blob)+ const link = root.querySelector<HTMLAnchorElement>("#sheet-link")!+ link.href = sheetUrl; link.download = `inkline-${family}-review.png`; link.hidden = false+ })+}+let drag: { x: number; yaw: number } | null = null+grid.onpointerdown = e => { if (!(e.target as HTMLElement).classList.contains("model-view")) return; drag = {x: e.clientX, yaw}; grid.setPointerCapture(e.pointerId) }+grid.onpointermove = e => { if (drag) { yaw = ((drag.yaw + (e.clientX - drag.x) * 0.5 + 540) % 360) - 180; render() } }+grid.onpointerup = grid.onpointercancel = () => { drag = null }+let frame = 0+const schedule = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(render) }+addEventListener("scroll", schedule, {passive: true}); addEventListener("resize", schedule)+const query = new URLSearchParams(location.search).get("collection")+select(query && query in families ? query as Family : "buildings")+Object.assign(window, { townModelReview: { stats: () => ({ family, models: models.length, renders, yaw, pitch }) } })+if (import.meta.hot) import.meta.hot.dispose(() => { models.forEach(m => m.built.dispose()); renderer.dispose(); renderer.domElement.remove(); removeEventListener("scroll", schedule); removeEventListener("resize", schedule) })diff --git a/src/model-review/style.css b/src/model-review/style.cssnew file mode 100644index 0000000..115a8ba--- /dev/null+++ b/src/model-review/style.css@@ -0,0 +1 @@+*{box-sizing:border-box}body{margin:0;background:#f0f2ec;color:#3d4943;font-family:Georgia,serif}a{color:inherit;text-underline-offset:4px}#review{max-width:1400px;margin:auto;padding:28px 44px}header{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #cbd1c5;padding-bottom:18px;font:12px ui-monospace,monospace;letter-spacing:.08em}header>a:first-child{font:bold 18px Georgia,serif;text-decoration:none}.intro{display:flex;justify-content:space-between;align-items:center;padding:42px 0 30px}.eyebrow{text-transform:uppercase;font:11px ui-monospace,monospace;letter-spacing:.14em;color:#78846f}h1{font-size:56px;line-height:1.02;font-weight:normal;margin:12px 0 20px}.intro p:last-child{max-width:530px;font:15px/1.65 system-ui,sans-serif;color:#687262}.intro aside{border-left:1px solid #cbd1c5;padding-left:25px;font:14px/1.9 ui-monospace,monospace;min-width:240px}.intro aside span{display:block;margin-top:12px;font:13px/1.6 system-ui,sans-serif;color:#78846f}nav{display:flex;gap:6px;flex-wrap:wrap;padding:14px 0;border-block:1px solid #cbd1c5}button,select{font:12px system-ui,sans-serif;color:inherit;border:1px solid #c5cdc0;background:transparent;border-radius:4px;padding:9px 12px;cursor:pointer}nav button[aria-pressed=true]{background:#3d4943;border-color:#3d4943;color:#f0f2ec}.camera{display:flex;align-items:center;flex-wrap:wrap;gap:12px;padding:18px 0 24px;font:12px system-ui,sans-serif}.camera label{display:flex;gap:12px;align-items:center}.camera label:last-child{margin-left:auto}input{accent-color:#748667;width:180px}output{width:35px;font:12px ui-monospace,monospace}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:20px}article{border:1px solid #cbd1c5;border-radius:4px;overflow:hidden;background:#f6f7f2}.card-top{display:flex;justify-content:space-between;padding:16px 18px;font:11px ui-monospace,monospace;color:#7f8c76}.model-view{height:265px;touch-action:pan-y;cursor:grab}.caption{padding:18px;border-top:1px solid #dce1d5}h2{font-size:22px;font-weight:normal;margin:0 0 8px}.caption p{font:12px/1.65 system-ui,sans-serif;color:#74806d;min-height:40px;margin:0 0 12px}.caption button{padding:6px 9px;font-size:11px}.models{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:1}header,nav,.camera,.card-top,.caption,footer{position:relative;z-index:2}footer{font:11px/1.8 ui-monospace,monospace;color:#74806d;padding:30px 0 10px}@media(min-width:1500px){.grid{grid-template-columns:repeat(4,minmax(0,1fr))}}@media(max-width:850px){#review{padding:22px}.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.intro aside{display:none}h1{font-size:46px}.model-view{height:220px}}@media(max-width:520px){#review{padding:18px}.intro{padding:24px 0 18px}h1{font-size:42px}header span{display:none}.grid{grid-template-columns:1fr}.camera label:last-child{margin-left:0}.model-view{height:260px}input{width:130px}}diff --git a/src/present.ts b/src/present.tsindex 3afdd14..d4cd351 100644--- a/src/present.ts+++ b/src/present.ts@@ -5,6 +5,7 @@* and the views follow the world.*/import { RenderSync } from "@typeonce/bevy-ts-render"+import { hazardStrength } from "./render3d/surface-state.ts"import { appealAt, appealParts, buildingSource, landSource, type AppealSource } from "./appeal.ts"import { homeHeight, topOf, type Alert, type Load, type Emphasis } from "./art.ts"@@ -964,6 +965,10 @@ export const Animate = Game.System(alert: alertOf(r ? { fire: r.fire, health: 0, order: 0 } : undefined, false, worn),burning: data.burning.present,worn,+ effects: {+ wear: 1-(maybe(data.condition)?.value??CONDITION_MAX)/CONDITION_MAX,+ fireRisk: hazardStrength(r?.fire??0,risk.warn,RISK_MAX)+ },working: status === "working",problem: problemOf(kind, status) !== null,build: buildOf(maybe(data.site), maybe(data.rising)),@@ -990,6 +995,13 @@ export const Animate = Game.System(alert: data.site.present ? null : alertOf(maybe(data.risk), data.sick.present, worn),burning: data.burning.present,worn,+ effects: {+ wear: Math.max(desirability<0?0.55:0,1-(maybe(data.condition)?.value??CONDITION_MAX)/CONDITION_MAX),+ fireRisk: hazardStrength(maybe(data.risk)?.fire??0,risk.warn,RISK_MAX),+ health: hazardStrength(maybe(data.risk)?.health??0,risk.warn,RISK_MAX),+ order: hazardStrength(maybe(data.risk)?.order??0,risk.warn,RISK_MAX),+ sick: Number(data.sick.present)+ },band: desirability < 0 ? "poor" : desirability >= home.tiers[2].appeal ? "fine" : "plain"},emphasis(entity.id)@@ -1002,7 +1014,17 @@ export const Animate = Game.System(const roam = maybe(data.roam)const load: Load = errand? { kind: "cart", good: errand.good, count: !errand.back || errand.count > 0 ? errand.count : 0 }- : roam?.service === "faith" || roam?.service === "health"+ : maybe(data.rescue)+ ? { kind: "service", role: "firefighter" }+ : roam?.service === "fire"+ ? { kind: "service", role: "watchman" }+ : roam?.service === "health"+ ? { kind: "service", role: "physician" }+ : roam?.service === "order"+ ? { kind: "service", role: "constable" }+ : roam?.service === "repair"+ ? { kind: "service", role: "builder" }+ : roam?.service === "faith"? { kind: "bell" }: roam && total(roam.basket) > 0? { kind: "basket", goods: goodIds.filter((g) => roam.basket[g] > 0) }diff --git a/src/render3d/models.ts b/src/render3d/models.tsindex 0af997f..92e5a44 100644--- a/src/render3d/models.ts+++ b/src/render3d/models.ts@@ -7,6 +7,8 @@ import { kinds, home, type KindId, type Tier } from "../content.ts"import { GRID, U, type Point } from "../iso.ts"import { key, cellOf, DIRS } from "../grid.ts"import type { Preview } from "../ui.ts"+import { withAppearance, type Appearance } from "../asset-lab/appearance.ts"+import { setts } from "../asset-lab/town-props.ts"export type DoorSet = Record<Side, boolean>export const noDoors: DoorSet = { right: false, left: false, backRight: false, backLeft: false }@@ -60,17 +62,19 @@ export function constructionAsset(size: number, half: number, height: number, buif (stage.walls > 0) d.box(0, 0, a, a, 0, Math.max(2, Math.round(height * stage.walls)))return d.asset}-export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number) {+export function buildingAsset(id: KindId, build: number, share: number | null, doors: DoorSet, open: number, appearance: Appearance = {}) {const kind = kinds[id],stage = buildStages(build)// An ornament is laid out at once.if (kind.decor) return makeBuilding(id)if (build < 0.78) return constructionAsset(kind.size, kind.half, kind.roof === "gable" ? 20 : kind.stories * 32, build, share)- return makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)+ const asset = makeBuilding(id, { doors, open, fit: stage.fit, plate: false, motion: false } satisfies BuildingOptions)+ return build >= 1 ? withAppearance(asset, kind.half * U, kind.roof === "gable" ? 20 : kind.stories * 32, appearance) : asset}-export function homeAsset(tier: Tier, n: number, build: number, share: number | null, doors: DoorSet) {+export function homeAsset(tier: Tier, n: number, build: number, share: number | null, doors: DoorSet, appearance: Appearance = {}) {if (build < 0.78) return constructionAsset(1, home.half + (tier >= 2 ? 1 : 0), home.tiers[tier].height, build, share)- return house(tier, n, "home", { doors, fit: buildStages(build).fit, plate: false })+ const asset = house(tier, n, "home", { doors, fit: buildStages(build).fit, plate: false })+ return build >= 1 ? withAppearance(asset, (home.half + (tier >= 2 ? 1 : 0)) * U, home.tiers[tier].height, appearance, true) : asset}export function homeKey(n: number) {return JSON.stringify(homeVariant(n))@@ -132,7 +136,7 @@ export function landAsset(mask: string, frost = false) {frost ? 0xf7f9fb : 0xf0f2ec,0)- // Frost: a few pale flecks of snow (a placeholder for a proper winter look).+ // Windblown flecks complement the material snow on roofs.if (frost && hash(x * 7 + 3, y * 5 + 1) < 0.18) {const u = x + 0.2 + hash(x, y * 3) * 0.6,v = y + 0.2 + hash(y, x * 3) * 0.6@@ -198,12 +202,7 @@ export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<numbehalf = 0.375,stone = paved.has(k),color = stone ? (hash(cell.x, cell.y) < 0.25 ? 0xd3d6cf : 0xd8dbd4) : hash(cell.x, cell.y) < 0.25 ? 0xe2e4dd : 0xe6e8e2- // Paved: setts in rows across the street (a placeholder for a proper paved road).- if (stone)- for (const t of [-0.22, 0, 0.22]) {- d.line([[x - 0.3, y + t, z + 0.015], [x + 0.3, y + t, z + 0.015]], 1, 0xb4b9b1, 0.8)- d.line([[x + t, y - 0.3, z + 0.015], [x + t, y + 0.3, z + 0.015]], 1, 0xb4b9b1, 0.5)- }+ if (stone) setts(d, x, y, half, z + 0.015)d.face(square(x, y, half, z), color, 0)for (const { x: dx, y: dy } of DIRS) {const q = (along: number, across: number, height = z + 0.02): Vertex => [@@ -213,6 +212,11 @@ export function groundAsset(roads: ReadonlySet<number>, water: ReadonlySet<numbe]if (roads.has(key(cell.x + dx, cell.y + dy))) {d.face([q(half, -half, z), q(0.5, -half, z), q(0.5, half, z), q(half, half, z)], color, 0)+ if (stone) {+ // Complete the short joining strip as a pair of stone kerbs.+ const center = q((half + 0.5) / 2, 0, z + 0.015)+ d.box(center[0], center[1], dx ? 0.0575 : half - 0.005, dy ? 0.0575 : half - 0.005, center[2], 0.22, 0xe0e4dc, 0xc6ccc3, 0xbfc6bc, 0.5, 0xa0aaa0)+ }d.line([q(half, -half), q(0.5, -half)], 1.5)d.line([q(half, half), q(0.5, half)], 1.5)d.line([q(0.0625, 0), q(0.1875, 0)], 1, 0xb4b9b1)diff --git a/src/render3d/pool.ts b/src/render3d/pool.tsindex 48c8cd2..3aaa50b 100644--- a/src/render3d/pool.ts+++ b/src/render3d/pool.ts@@ -1,6 +1,8 @@import * as THREE from "three"import { buildAsset, type BuiltAsset } from "../asset-lab/renderer.ts"import type { InkAsset } from "../asset-lab/primitives.ts"+import { surfaceState, type SurfaceState } from "./surface-state.ts"+import { installSurfaceShader } from "./surface-shader.ts"interface Part {source: THREE.Mesh<THREE.BufferGeometry, THREE.MeshBasicMaterial>@@ -16,6 +18,9 @@ interface Template {handles: Set<ModelHandle>capacity: numberalpha: Float32Array+ effects: Float32Array+ hazards: Float32Array+ bounds: Float32Arrayused: number}@@ -25,6 +30,8 @@ export class ModelHandle {readonly tint = new THREE.Color(0xffffff)alpha = 1colors: ReadonlyMap<number, number> | null = null+ effects: SurfaceState = surfaceState()+ effectBounds = new THREE.Vector4()template: Template | null = nullreadonly pool: ModelPoolreadonly entity: number | null@@ -56,10 +63,11 @@ export class ModelPool {private matrix = new THREE.Matrix4()private color = new THREE.Color()readonly viewDirection = new THREE.Vector3(1, 1, 1).normalize()+ readonly time = { value: 0 }acquire(key: string, create: () => InkAsset): Template {let entry = this.templates.get(key)if (!entry) {- const model = buildAsset(create(), { batchFaces: true, meshInk: true, meshContours: true })+ const model = buildAsset(create(), { batchFaces: true, meshInk: true, meshContours: true, surfaceEffects: false })const parts: Array<Part> = []model.group.updateMatrixWorld(true)for (const child of model.group.children) {@@ -88,6 +96,7 @@ export class ModelPool {}material.customProgramCacheKey = () =>source.geometry.hasAttribute("inkNormalA") ? "ink-instance-silhouette-v1" : "ink-instance-opacity-v1"+ if (source.userData.structureSurface) installSurfaceShader(material,color,this.time,surfaceState(),new THREE.Vector4(),true)parts.push({ source, material, mesh: null, color })}entry = {@@ -98,6 +107,7 @@ export class ModelPool {handles: new Set(),capacity: 0,alpha: new Float32Array(),+ effects: new Float32Array(), hazards: new Float32Array(), bounds: new Float32Array(),used: ++this.stamp}this.templates.set(key, entry)@@ -127,6 +137,9 @@ export class ModelPool {if (entry.capacity < handles.length) {entry.capacity = 2 ** Math.ceil(Math.log2(Math.max(4, handles.length)))entry.alpha = new Float32Array(entry.capacity)+ entry.effects = new Float32Array(entry.capacity * 4)+ entry.hazards = new Float32Array(entry.capacity * 4)+ entry.bounds = new Float32Array(entry.capacity * 4)for (const part of entry.parts) {if (part.mesh) {part.mesh.removeFromParent()@@ -137,6 +150,9 @@ export class ModelPool {geometry.setIndex(part.source.geometry.index)for (const [key, attribute] of Object.entries(part.source.geometry.attributes)) geometry.setAttribute(key, attribute)geometry.setAttribute("inkOpacity", new THREE.InstancedBufferAttribute(entry.alpha, 1))+ geometry.setAttribute("structureState",new THREE.InstancedBufferAttribute(entry.effects,4))+ geometry.setAttribute("structureHazards",new THREE.InstancedBufferAttribute(entry.hazards,4))+ geometry.setAttribute("structureBounds",new THREE.InstancedBufferAttribute(entry.bounds,4))geometry.boundingBox = part.source.geometry.boundingBox?.clone() ?? nullgeometry.boundingSphere = part.source.geometry.boundingSphere?.clone() ?? nullpart.mesh = new THREE.InstancedMesh(geometry, part.material, entry.capacity)@@ -149,6 +165,10 @@ export class ModelPool {handles.forEach((handle, i) => {handle.root.updateWorldMatrix(true, false)entry.alpha[i] = Math.min(1, Math.max(0, handle.alpha))+ const e=handle.effects+ entry.effects.set([e.wear,e.care,e.snow,e.burning],i*4)+ entry.hazards.set([e.fireRisk,e.health,e.order,e.sick],i*4)+ handle.effectBounds.toArray(entry.bounds,i*4)for (const part of entry.parts) {this.matrix.multiplyMatrices(handle.root.matrixWorld, part.source.matrixWorld)part.mesh!.setMatrixAt(i, this.matrix)@@ -163,6 +183,7 @@ export class ModelPool {mesh.instanceMatrix.needsUpdate = trueif (mesh.instanceColor) mesh.instanceColor.needsUpdate = truemesh.geometry.getAttribute("inkOpacity").needsUpdate = true+ for(const key of ["structureState","structureHazards","structureBounds"])mesh.geometry.getAttribute(key).needsUpdate=truemesh.computeBoundingSphere()}}diff --git a/src/render3d/scene.ts b/src/render3d/scene.tsindex 4b879aa..0cf1d98 100644--- a/src/render3d/scene.ts+++ b/src/render3d/scene.ts@@ -259,6 +259,7 @@ export class GameScene {onTick({ deltaMS: delta })for (const node of this.nodes) node.orient()this.camera.getWorldDirection(this.pool.viewDirection).negate()+ this.pool.time.value = now / 1000this.pool.flush()this.renderer.render(this.scene, this.camera)this.frames++diff --git a/src/render3d/structure-effects.ts b/src/render3d/structure-effects.tsnew file mode 100644index 0000000..4bc9015--- /dev/null+++ b/src/render3d/structure-effects.ts@@ -0,0 +1,103 @@+import * as THREE from "three"+import { type InkAsset } from "../asset-lab/primitives.ts"+import { surfaceState, type SurfaceState } from "./surface-state.ts"++const vertex = `+attribute float particleSeed;+uniform float time;+uniform float power;+uniform float mode;+varying vec2 tex;+varying float age;+varying float seed;+void main(){+ tex=uv; seed=particleSeed;+ float life=mode<0.5?1.8:mode<1.5?4.2:2.8;+ age=fract(time/life+seed);+ vec4 center=modelViewMatrix*instanceMatrix*vec4(0,0,0,1);+ float rise=mode<0.5?0.0:mode<1.5?age*32.0:age*35.0;+ center.y+=rise;+ center.x+=sin(seed*43.0+age*4.0)*(mode<0.5?0.7:3.0)*age;+ float size=mode<0.5?(0.8+0.2*sin(time*8.0+seed*31.0))*power:mode<1.5?(0.55+age*1.15):1.0;+ vec2 scale=vec2(length(instanceMatrix[0].xyz),length(instanceMatrix[1].xyz));+ if(mode<0.5)center.y+=scale.y*size*0.5;+ center.xy+=(position.xy*scale)*size;+ gl_Position=projectionMatrix*center;+}+`+const fragment = `+uniform float time; uniform float power; uniform float mode;+varying vec2 tex; varying float age; varying float seed;+float hash(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}+float noise(vec2 p){vec2 i=floor(p),f=fract(p);f=f*f*(3.0-2.0*f);return mix(mix(hash(i),hash(i+vec2(1,0)),f.x),mix(hash(i+vec2(0,1)),hash(i+vec2(1,1)),f.x),f.y);}+void main(){+ vec2 p=tex; float alpha; vec3 color;+ if(mode<0.5){+ float y=p.y; float curl=sin(y*8.0-time*4.5+seed*39.0)*0.11*y;+ float body=abs(p.x-0.5-curl)/(0.46*(1.0-y*0.86));+ float edge=1.0-smoothstep(0.45,1.0,body+noise(vec2(p.x*6.0,y*5.0-time*3.5)+seed*10.0)*0.27);+ alpha=edge*smoothstep(0.0,0.10,y)*(1.0-smoothstep(0.82,1.0,y))*0.82;+ float core=(1.0-body)*pow(1.0-y,0.7);+ color=mix(vec3(0.87,0.33,0.12),vec3(1.0,0.83,0.38),smoothstep(0.0,0.8,core));+ }else if(mode<1.5){+ float d=length((p-0.5)*2.0); float cloud=noise(p*5.0+vec2(seed*9.0,time*0.12));+ alpha=(1.0-smoothstep(0.3,1.0,d+cloud*0.2))*sin(age*3.14159)*0.20*power;+ color=mix(vec3(0.35,0.39,0.33),vec3(0.64,0.66,0.58),age);+ }else{+ alpha=(1.0-smoothstep(0.05,0.5,length(p-0.5)))*sin(age*3.14159)*power;+ color=vec3(1.0,0.67,0.24);+ }+ if(alpha<0.015)discard;+ gl_FragColor=vec4(pow(color,vec3(2.2)),alpha);+ #include <colorspace_fragment>+}+`++/** Particle emitters sampled from the actual roof triangles, never a hovering+ * sign or replacement mesh. Billboards face the camera inside the shader. */+export class StructureEffects {+ readonly group = new THREE.Group()+ private state = surfaceState()+ private layers: Array<THREE.InstancedMesh<THREE.PlaneGeometry,THREE.ShaderMaterial>> = []+ private asset: InkAsset+ private H: number+ constructor(asset: InkAsset, height: number) { this.asset=asset; this.H=height; this.group.visible=false }+ set(next: SurfaceState) { this.state=next; this.group.visible=next.burning>0||next.fireRisk>0 }+ private build() {+ const scale=32*Math.SQRT2, convert=(p: readonly number[])=>new THREE.Vector3(p[0]!*scale,p[2]!/Math.cos(Math.PI/6),p[1]!*scale)+ const roofs=this.asset.faces.filter(f=>f.points.every(p=>p[2]>=this.H-0.01)&&f.points.length>=3).flatMap(f=> {+ const a=convert(f.points[0]!), triangles: Array<THREE.Triangle>=[]+ for(let i=1;i<f.points.length-1;i++){+ const t=new THREE.Triangle(a,convert(f.points[i]!),convert(f.points[i+1]!)), n=t.getNormal(new THREE.Vector3())+ if(Math.abs(n.y)>0.15&&t.getArea()>2)triangles.push(t)+ }+ return triangles+ })+ for(const [mode,count] of [[0,16],[1,18],[2,14]] as const){+ const geometry=new THREE.PlaneGeometry(1,1), seeds=Float32Array.from({length:count},(_,i)=>(i*0.6180339)%1)+ geometry.setAttribute("particleSeed",new THREE.InstancedBufferAttribute(seeds,1))+ const material=new THREE.ShaderMaterial({vertexShader:vertex,fragmentShader:fragment,uniforms:{time:{value:0},power:{value:0},mode:{value:mode}},transparent:true,depthWrite:false,depthTest:true,side:THREE.DoubleSide})+ const mesh=new THREE.InstancedMesh(geometry,material,count)+ const dummy=new THREE.Object3D()+ for(let i=0;i<count;i++){+ const t=roofs[i%roofs.length], u=0.15+((i*0.37)%0.65),v=0.12+((i*0.23)%0.6), sum=u+v,+ a=u/Math.max(1,sum),b=v/Math.max(1,sum)+ const at=t?t.a.clone().multiplyScalar(1-a-b).addScaledVector(t.b,a).addScaledVector(t.c,b):new THREE.Vector3(0,this.H/Math.cos(Math.PI/6),0)+ dummy.position.copy(at).add(new THREE.Vector3(0,mode===0?0:mode===1?3:0.5,0))+ const size=mode===0?[5+i%3,13+i%4*2.5]:mode===1?[8+i%4,8+i%4]:[0.7,0.9]+ dummy.scale.set(size[0]!,size[1]!,1);dummy.updateMatrix();mesh.setMatrixAt(i,dummy.matrix)+ }+ mesh.frustumCulled=false;mesh.renderOrder=3+mode;this.layers.push(mesh);this.group.add(mesh)+ }+ }+ update(time: number) {+ if(!this.group.visible)return+ if(!this.layers.length)this.build()+ for(const [i,mesh]of this.layers.entries()){+ mesh.visible=i===1?true:this.state.burning>0+ mesh.material.uniforms.time!.value=time+ mesh.material.uniforms.power!.value=i===1?Math.max(this.state.burning,this.state.fireRisk*0.42):this.state.burning+ }+ }+ dispose(){this.layers.forEach(m=>{m.geometry.dispose();m.material.dispose();m.dispose()});this.layers=[];this.group.removeFromParent()}+}diff --git a/src/render3d/surface-shader.ts b/src/render3d/surface-shader.tsnew file mode 100644index 0000000..566503e--- /dev/null+++ b/src/render3d/surface-shader.ts@@ -0,0 +1,76 @@+import * as THREE from "three"+import { type SurfaceState } from "./surface-state.ts"++/** One shader for catalogue meshes and GPU instances in the live town. */+const declarations = `+varying vec3 vStructurePosition;+varying vec3 vStructureNormal;+varying vec4 vStructureState;+varying vec4 vStructureHazards;+varying vec4 vStructureBounds;+uniform float structureTime;+uniform float structureGlass;+float grainHash(vec2 p){ return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453); }+float grain(vec2 p){ vec2 i=floor(p),f=fract(p); f=f*f*(3.0-2.0*f); return mix(mix(grainHash(i),grainHash(i+vec2(1,0)),f.x),mix(grainHash(i+vec2(0,1)),grainHash(i+vec2(1,1)),f.x),f.y); }+vec3 inkRGB(vec3 c){ return pow(c,vec3(2.2)); }+`+const shade = `+if(vStructureBounds.w>0.5){+ vec3 p=vStructurePosition; vec3 n=normalize(vStructureNormal);+ float H=vStructureBounds.y, halfWidth=vStructureBounds.x;+ float wear=vStructureState.x,care=vStructureState.y,snow=vStructureState.z,burn=vStructureState.w;+ float fireRisk=vStructureHazards.x,health=vStructureHazards.y,order=vStructureHazards.z,sick=vStructureHazards.w;+ float roof=step(H-0.15,p.y)*smoothstep(0.12,0.45,abs(n.y));+ float wall=(1.0-roof)*step(0.1,p.y)*step(p.y,H+0.1)*(1.0-structureGlass);+ vec2 uv=abs(n.x)>abs(n.z)?p.zy:p.xy;+ float g=grain(uv*0.32+vStructureBounds.z);+ float lower=1.0-smoothstep(0.0,H*0.7,p.y);+ float dirt=wear*wall*(0.16+0.45*lower+0.20*g);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.60,0.62,0.52)),dirt);+ float plaster=wear*wall*smoothstep(0.58,0.76,g)*(0.4+0.6*lower);+ vec2 brick=vec2((uv.x+mod(floor(uv.y/1.8),2.0)*1.8)/3.6,uv.y/1.8);+ float mortar=max(1.0-smoothstep(0.025,0.08,fract(brick.y)),1.0-smoothstep(0.025,0.06,fract(brick.x)));+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(mix(vec3(0.68,0.53,0.40),vec3(0.84,0.79,0.68),mortar)),plaster*0.9);+ float crack=abs(uv.x-halfWidth*0.36-sin(uv.y*0.64)*0.48-sin(uv.y*1.5)*0.16);+ float crackMask=(1.0-smoothstep(0.045,0.10,crack))*smoothstep(H*0.25,H*0.4,p.y)*step(p.y,H*0.92);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.39,0.43,0.36)),crackMask*wear*wall*0.85);+ float moss=roof*wear*smoothstep(0.3,0.8,grain(p.xz*0.30))*0.45;+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.47,0.54,0.37)),moss);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.97,0.96,0.90)),care*wall*0.12);+ float damp=(health*0.45+sick*0.65)*wall*lower*smoothstep(0.35,0.75,g);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.48,0.59,0.43)),damp);+ if(structureGlass>0.5){+ float fissure=abs(fract((uv.x+uv.y*0.38+sin(uv.y*2.0)*0.18)/3.2)-0.5);+ float broken=(1.0-smoothstep(0.025,0.065,fissure))*order;+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.25,0.31,0.29)),broken*0.95);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.58,0.69,0.45)),sick*0.35);+ float warm=care*0.6+burn*(0.75+0.15*sin(structureTime*9.0+p.x*2.0));+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(1.0,0.76,0.36)),warm);+ }+ float soot=(roof+wall*0.5)*burn*(0.35+grain(p.xz*0.27)*0.50);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.28,0.31,0.27)),soot);+ float heat=roof*burn*pow(grain(p.xz*0.45+vec2(0.0,-structureTime*1.3)),5.0);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.99,0.49,0.19)),heat*0.75);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.80,0.63,0.43)),roof*fireRisk*0.15*(0.7+0.3*sin(structureTime*3.0)));+ float frost=roof*snow*smoothstep(-0.05,0.22,grain(p.xz*0.65)+smoothstep(H,H+2.0,p.y)*0.15);+ diffuseColor.rgb=mix(diffuseColor.rgb,inkRGB(vec3(0.97,0.98,0.96)),frost);+}+`+export function installSurfaceShader(material: THREE.MeshBasicMaterial, color: number, time: {value: number}, state: SurfaceState, bounds: THREE.Vector4, instanced = false) {+ const previous = material.onBeforeCompile.bind(material)+ const previousKey = material.customProgramCacheKey.bind(material)+ const s = new THREE.Vector4(state.wear,state.care,state.snow,state.burning), h = new THREE.Vector4(state.fireRisk,state.health,state.order,state.sick)+ material.onBeforeCompile = (shader, renderer) => {+ previous(shader,renderer)+ shader.uniforms.structureTime = time+ shader.uniforms.structureGlass = {value: [0xdbe6ea,0xf3dca6,0xc9d6ee,0xd5dae4,0xdbe9e7].includes(color)?1:0}+ shader.uniforms.structureState = {value:s}; shader.uniforms.structureHazards = {value:h}; shader.uniforms.structureBounds={value:bounds}+ const inputs = instanced ? "attribute vec4 structureState; attribute vec4 structureHazards; attribute vec4 structureBounds;" : "uniform vec4 structureState; uniform vec4 structureHazards; uniform vec4 structureBounds;"+ shader.vertexShader = `varying vec3 vStructurePosition; varying vec3 vStructureNormal; varying vec4 vStructureState; varying vec4 vStructureHazards; varying vec4 vStructureBounds; ${inputs}\n` + shader.vertexShader+ shader.vertexShader = shader.vertexShader.replace("#include <begin_vertex>","#include <begin_vertex>\nvStructurePosition=position; vStructureNormal=normal; vStructureState=structureState; vStructureHazards=structureHazards; vStructureBounds=structureBounds;")+ shader.fragmentShader=declarations+shader.fragmentShader+ shader.fragmentShader=shader.fragmentShader.replace("#include <color_fragment>","#include <color_fragment>\n"+shade)+ }+ material.customProgramCacheKey=()=>`${previousKey()}/structure-surface-v1/${Number(instanced)}`+ return { set(next: SurfaceState) { s.set(next.wear,next.care,next.snow,next.burning); h.set(next.fireRisk,next.health,next.order,next.sick) } }+}diff --git a/src/render3d/surface-state.ts b/src/render3d/surface-state.tsnew file mode 100644index 0000000..88b327a--- /dev/null+++ b/src/render3d/surface-state.ts@@ -0,0 +1,17 @@+export interface SurfaceState {+ wear: number+ care: number+ snow: number+ burning: number+ fireRisk: number+ health: number+ order: number+ sick: number+}+export const surfaceState = (state: Partial<SurfaceState> = {}): SurfaceState => {+ const bound = (n = 0) => Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0+ return { wear: bound(state.wear), care: bound(state.care), snow: bound(state.snow), burning: bound(state.burning), fireRisk: bound(state.fireRisk), health: bound(state.health), order: bound(state.order), sick: bound(state.sick) }+}+/** A warning is visible as soon as the simulation's warning threshold is met. */+export const hazardStrength = (value: number, threshold: number, maximum: number) =>+ value < threshold || maximum <= threshold ? 0 : Math.min(1,0.35+0.65*(value-threshold)/(maximum-threshold))diff --git a/src/render3d/views.ts b/src/render3d/views.tsindex 659a129..0a9d12a 100644--- a/src/render3d/views.ts+++ b/src/render3d/views.ts@@ -2,7 +2,6 @@ import * as THREE from "three"import {carrierDress,cartLook,- homeHeight,serviceDress,type Alert,type BuildingLook,@@ -12,54 +11,31 @@ import {type Load,type Emphasis} from "../art.ts"-import { kinds, GROWN, ROCK_AMOUNT, type KindId } from "../content.ts"+import { kinds, home, GROWN, ROCK_AMOUNT, type KindId } from "../content.ts"import { U, type Point } from "../iso.ts"import { vertex3 } from "../asset-lab/renderer.ts"import { Drawing, type Vertex } from "../asset-lab/primitives.ts"import { makeSails, makeFlag } from "../asset-lab/buildings.ts"import { makeMarker } from "../asset-lab/construction.ts"-import { makeFlames, makeRuin, makeWarning } from "../asset-lab/placeholders.ts"-import { makePerson } from "../asset-lab/people.ts"+import { makeRuin } from "../asset-lab/town-props.ts"+import { StructureEffects } from "./structure-effects.ts"+import { surfaceState, type SurfaceState } from "./surface-state.ts"+import { makePerson, serviceCostume, type ServiceRole } from "../asset-lab/people.ts"import { makeTree, makeRock, makeField, hash } from "../asset-lab/land.ts"import { ModelHandle } from "./pool.ts"import { buildingAsset, homeAsset, homeKey, doorKey, noDoors, quantizeBuild, plateAsset, treeVariant } from "./models.ts"import type { GameScene, SceneNode } from "./scene.ts"-/** Winter's cold tint over everything that stands (a placeholder for snowy roofs). */+/** Winter's cold light complements the roof snow shader. */const FROST = 0xe4ecf6-/** Run down, and a poor street: duller, browner. */-const WORN = 0xe2d9c8-const POOR = 0xeee8dcconst multiply = (a: number, b: number) => {const c = (shift: number) => Math.round((((a >> shift) & 0xff) * ((b >> shift) & 0xff)) / 255)return (c(16) << 16) | (c(8) << 8) | c(0)}-/** A sign over a home or building at risk, and flames when it burns: both face the camera. */-class Signs {- private readonly sign: ModelHandle- private readonly flames: ModelHandle- constructor(make: (pickable?: boolean) => ModelHandle) {- this.sign = make(false)- this.flames = make(false)- this.sign.root.visible = false- this.flames.root.visible = false- }- update(alert: Alert | null | undefined, burning: boolean, height: number) {- this.sign.root.visible = !burning && alert !== null && alert !== undefined- if (alert && !burning) this.sign.use("warning-" + alert, () => makeWarning(alert))- this.sign.root.position.set(0, (height + 10) / Math.cos(Math.PI / 6), 0)- this.flames.root.visible = burning- if (burning) {- const phase = Math.floor(performance.now() / 160) % 2- this.flames.use("flames-" + phase, () => makeFlames(phase))- this.flames.root.position.set(0, (height * 0.6) / Math.cos(Math.PI / 6), 0)- }- }- orient(heading: number) {- this.sign.root.rotation.y = heading - Math.PI / 4- this.flames.root.rotation.y = heading - Math.PI / 4- }+/** Surface parameters are independent of shared architectural geometry. */+export function structureState(look: {worn?: boolean; band?: "poor" | "plain" | "fine"; alert?: Alert | null; burning?: boolean; effects?: Partial<SurfaceState>}, winter: boolean) {+ return surfaceState({wear: look.worn?0.9:look.band==="poor"?0.55:0, care: look.band==="fine"?1:0, snow:Number(winter), burning:Number(!!look.burning), fireRisk:look.alert==="fire"?1:0, health:look.alert==="health"?1:0, order:look.alert==="order"?1:0,sick:look.alert==="sick"?1:0,...look.effects})}export class WorldView implements SceneNode {@@ -68,6 +44,7 @@ export class WorldView implements SceneNode {readonly stage: GameScenereadonly entity: numberprotected models: Array<ModelHandle> = []+ protected effects: StructureEffects | null = nullprivate disposed = falseprivate opacity = 1constructor(stage: GameScene, entity: number) {@@ -98,6 +75,7 @@ export class WorldView implements SceneNode {if (this.disposed) returnthis.disposed = truefor (const m of this.models) m.dispose()+ this.effects?.dispose()this.group.removeFromParent()this.stage.remove(this)}@@ -116,14 +94,12 @@ export class BuildingView extends WorldView {private opening = 0private beat = -1private pulse = 0- private signs: Signsconstructor(kindId: KindId, stage: GameScene, entity: number) {super(stage, entity)this.kindId = kindIdthis.body = this.model()this.plate = this.model()this.marker = this.model()- this.signs = new Signs((pickable) => this.model(pickable))this.motion = this.model()this.marker.use("problem-marker", makeMarker)this.marker.root.visible = false@@ -163,8 +139,15 @@ export class BuildingView extends WorldView {)const signed = !!look.burning || (look.alert !== null && look.alert !== undefined)this.marker.root.visible = look.problem && look.build >= 1 && !signed- this.signs.update(look.alert, !!look.burning, H + (kind.topper === "none" ? 0 : 16))- this.shade = look.worn ? WORN : 0xffffff+ const state = structureState(look,this.stage.frost)+ this.body.effects = build >= 1 ? state : surfaceState()+ this.body.effectBounds.set(kind.half * U * 32 * Math.SQRT2,H/Math.cos(Math.PI/6),this.entity%97/97,Number(!kind.decor))+ if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){+ this.effects = new StructureEffects(buildingAsset(this.kindId,1,null,noDoors,0),H)+ this.group.add(this.effects.group)+ }+ this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)+ this.shade = 0xffffffthis.motion.root.visible = look.build >= 1 && (kind.topper === "flag" || kind.topper === "sails")if (kind.topper === "flag") {this.wave += dt * (look.working ? 6 : 3)@@ -218,23 +201,17 @@ export class BuildingView extends WorldView {override orient() {this.marker.root.rotation.y = this.stage.heading - Math.PI / 4for (const smoke of this.smokes) smoke.root.rotation.y = this.stage.heading - Math.PI / 4- this.signs.orient(this.stage.heading)}}export class HouseView extends WorldView {private body: ModelHandleprivate plate: ModelHandle- private signs: Signsprivate n = 0.03constructor(stage: GameScene, entity: number) {super(stage, entity)this.body = this.model()this.plate = this.model()- this.signs = new Signs((pickable) => this.model(pickable))- }- override orient() {- this.signs.orient(this.stage.heading)}place(x: number, y: number) {this.n = hash(x, y)@@ -250,9 +227,17 @@ export class HouseView extends WorldView {homeAsset(look.tier, this.n, build, share, doors))this.plate.use(`plate/1/${build}`, () => plateAsset(1, build))- this.signs.update(look.alert, !!look.burning, homeHeight(look.tier))- // Placeholder for homes that look like their street: fences and gardens on a fine one, a patched roof on a poor one.- this.shade = look.worn ? WORN : look.band === "poor" ? POOR : 0xffffff+ const state=structureState(look,this.stage.frost), H=home.tiers[look.tier].height+ this.body.effects=build>=1?state:surfaceState()+ this.body.effectBounds.set((home.half+(look.tier>=2?1:0))*U*32*Math.SQRT2,H/Math.cos(Math.PI/6),this.n,1)+ // Recreate emitters only if an actual architectural upgrade changes the roof.+ if(this.effects&&this.effects.group.userData.tier!==look.tier){this.effects.dispose();this.effects=null}+ if(!this.effects&&build>=1&&(state.burning||state.fireRisk)){+ this.effects=new StructureEffects(homeAsset(look.tier,this.n,1,null,noDoors),H)+ this.effects.group.userData.tier=look.tier;this.group.add(this.effects.group)+ }+ this.effects?.set(build>=1?state:surfaceState());this.effects?.update(performance.now()/1000)+ this.shade=0xffffffthis.emphasis(emphasis)}}@@ -338,6 +323,7 @@ export class WalkerView extends WorldView {private cart: CartLook | nullprivate faithDress: PersonDress | null = nullprivate currentDress: PersonDress | null = null+ private serviceDresses = new Map<ServiceRole, PersonDress>()constructor(stage: GameScene, entity: number, dress: PersonDress, cart: CartLook | null) {super(stage, entity)this.dress = dress@@ -356,7 +342,8 @@ export class WalkerView extends WorldView {return view}update(x: number, y: number, dir: Point, phase: number, load: Load) {- const dress = load.kind === "bell" && this.faithDress ? this.faithDress : this.dress+ if (load.kind === "service" && !this.serviceDresses.has(load.role)) this.serviceDresses.set(load.role, serviceCostume(this.dress, load.role))+ const dress = load.kind === "service" ? this.serviceDresses.get(load.role)! : load.kind === "bell" && this.faithDress ? this.faithDress : this.dress// Costume colours vary per person without duplicating the same geometry.const canonicalDress = { ...dress, coat: 0xff0001, skin: 0xff0003, trim: dress.trim === 0xf7f8f4 ? dress.trim : 0xff0002 },canonicalCart = this.cart ? { ...this.cart, wood: { top: 0xff0004, left: 0xff0005, right: 0xff0006 } } : nulldiff --git a/test/ink-assets.test.ts b/test/ink-assets.test.tsindex e63e85c..4ea81c7 100644--- a/test/ink-assets.test.ts+++ b/test/ink-assets.test.ts@@ -18,7 +18,7 @@ test("the portable catalogue covers all world object families", () => {}const hats = new Set(inkAssets.flatMap((a) => (a.reference?.type === "walker" ? [a.reference.dress.hat] : [])))assert.deepEqual([...hats].sort(), ["bonnet", "brim", "cap", "hood", "none", "top"])- for (const tier of [1, 2]) assert.equal(inkAssets.filter((a) => a.reference?.type === "house" && a.reference.tier === tier).length, 4)+ for (const tier of [1, 2]) assert.equal(inkAssets.filter((a) => a.reference?.type === "house" && a.reference.tier === tier && !a.appearance).length, 4)assert.equal(inkAssets.filter((a) => a.reference?.type === "tree").length, 9)assert.equal(inkAssets.filter((a) => a.reference?.type === "rock").length, 4)assert.equal(inkAssets.filter((a) => a.reference?.type === "field").length, 4)diff --git a/test/render3d.test.ts b/test/render3d.test.tsindex 17661e2..a37f1a6 100644--- a/test/render3d.test.ts+++ b/test/render3d.test.ts@@ -5,6 +5,9 @@ import { kindIds } from "../src/content.ts"import { Drawing, type InkAsset } from "../src/asset-lab/primitives.ts"import { buildingAsset, homeAsset, noDoors, treeVariant } from "../src/render3d/models.ts"import { ModelHandle, ModelPool } from "../src/render3d/pool.ts"+import { assetById } from "../src/asset-lab/assets.ts"+import { surfaceState, hazardStrength } from "../src/render3d/surface-state.ts"+import { StructureEffects } from "../src/render3d/structure-effects.ts"function valid(asset: InkAsset) {for (const face of asset.faces) {@@ -82,3 +85,56 @@ test("a seeded forest uses a bounded set of variants and preserves cell offsets"}assert.ok(variants.size <= 34)})++test("surface states preserve the base geometry instead of making variant meshes", () => {+ for (const id of ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] as const) {+ const plain = buildingAsset(id, 1, null, noDoors, 0)+ for (const appearance of ["worn", "winter"] as const) {+ const model = buildingAsset(id, 1, null, noDoors, 0, { worn: appearance === "worn", winter: appearance === "winter" })+ valid(model)+ assert.ok(assetById.has(`${id}-${appearance}`))+ assert.deepEqual(model.faces,plain.faces)+ assert.deepEqual(model.strokes,plain.strokes)+ assert.ok(model.effects)+ }+ }+ for (const tier of [1, 2, 3] as const) {+ const plain = homeAsset(tier, 0.03, 1, null, noDoors)+ for (const look of [{ band: "fine" as const }, { band: "poor" as const }, { worn: true }, { winter: true }]) {+ const model = homeAsset(tier, 0.03, 1, null, noDoors, look)+ valid(model)+ assert.deepEqual(model.faces,plain.faces)+ assert.deepEqual(model.strokes,plain.strokes)+ assert.ok(model.effects)+ }+ }+})++test("different surface states share geometry and remain independent per instance", () => {+ const pool=new ModelPool(),a=new ModelHandle(pool),b=new ModelHandle(pool)+ let built=0+ const create=()=>{built++;return homeAsset(2,0.28,1,null,noDoors)}+ a.use("home",create);b.use("home",create)+ a.effectBounds.set(12,30,0.1,1);b.effectBounds.copy(a.effectBounds)+ a.effects=surfaceState({snow:1});b.effects=surfaceState({wear:0.9,burning:1})+ pool.flush()+ // Non-pickable effects use the same pool; inspect the render batch directly.+ const part=pool.root.children[0]!.children[0] as THREE.Mesh+ const state=part.geometry.getAttribute("structureState")+ assert.equal(state.getZ(0),1);assert.equal(state.getX(1),Math.fround(0.9));assert.equal(state.getW(1),1)+ for(let i=0;i<100;i++){a.effects=surfaceState({wear:i/100});pool.flush()}+ assert.equal(built,1);assert.equal(pool.stats().templates,1)+ const particles=new StructureEffects(create(),26)+ particles.set(surfaceState({burning:1}));particles.update(0)+ assert.equal(particles.group.children.length,3)+ particles.update(100);assert.equal(particles.group.children.length,3)+ particles.set(surfaceState());assert.equal(particles.group.visible,false)+ particles.dispose();pool.dispose()+})++test("hazard effects become visible at the warning threshold and remain bounded", () => {+ assert.equal(hazardStrength(6999,7000,10000),0)+ assert.equal(hazardStrength(7000,7000,10000),0.35)+ assert.equal(hazardStrength(10000,7000,10000),1)+ assert.equal(hazardStrength(12000,7000,10000),1)+})diff --git a/vite.config.ts b/vite.config.tsindex 15652d9..ca7ec93 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,3 +1,16 @@import { defineConfig } from "vite"-export default defineConfig({})+export default defineConfig({+ build: {+ rolldownOptions: {+ input: {+ game: "index.html",+ gallery: "gallery.html",+ assets: "asset-lab.html",+ map: "map-lab.html",+ models: "model-review.html",+ effects: "effects-lab.html"+ }+ }+ }+})