diff --git a/apps/web/e2e/units.e2e.mjs b/apps/web/e2e/units.e2e.mjs new file mode 100644 index 0000000..6f76915 --- /dev/null +++ b/apps/web/e2e/units.e2e.mjs @@ -0,0 +1,130 @@ +// End-to-end test of the sprite layers: zoomed out the map shows overlays only; zoomed in, resource +// objects, roads, a hall at each capital and the walking villagers are drawn, and the villagers move +// while time runs. Screenshots (E2E_SHOTS=) are for a human to look at. +// +// pnpm --filter @sovereign/web e2e:units +// +// It starts the Vite dev server itself and needs Chromium. The world is 2000 x 2000, so this takes a +// few minutes in software GL. +import { chromium } from 'playwright' +import { + SOFTWARE_GL, + centerOn, + firstNationPoint, + readCamera, + startDevServer, + withTimeout +} from './support.mjs' + +const PORT = 5198 +const SEED = 1337 +const viewport = { width: 1280, height: 800 } + +const stats = (page) => + page.$eval('canvas', (c) => ({ + sprites: c.dataset.sprites, + roads: Number(c.dataset.spriteRoads), + resources: Number(c.dataset.spriteResources), + halls: Number(c.dataset.spriteHalls), + units: Number(c.dataset.spriteUnits) + })) + +async function main() { + const problems = [] + const fail = (message) => problems.push(message) + const nation = firstNationPoint(SEED) + const { url, stop } = await startDevServer(PORT) + const browser = await chromium.launch({ args: SOFTWARE_GL }) + try { + const page = await browser.newPage({ viewport }) + page.on('pageerror', (error) => fail(`pageerror: ${error.message}`)) + page.on('console', (message) => { + if (message.type() === 'error') fail(`console.error: ${message.text()}`) + }) + await withTimeout(page.goto(url), 30_000, 'load the page') + await page.fill('#seed-input', String(SEED)) + await page.click('text=New World') + await withTimeout( + page.waitForFunction(() => document.querySelector('.time-controls') !== null, null, { + timeout: 240_000 + }), + 245_000, + 'the world and its time controls' + ) + await page.waitForTimeout(800) + + // far out: overlays only + let s = await stats(page) + if (s.sprites !== 'off') fail(`zoomed out, sprites should be off, got ${s.sprites}`) + if (s.units !== 0 || s.resources !== 0) fail('zoomed out, no sprites should be made') + + // centre the first nation, then zoom in with the + button + const drag = async (dx, dy) => { + const x = viewport.width / 2 + const y = viewport.height / 2 + await page.mouse.move(x, y) + await page.mouse.down() + await page.mouse.move(x + dx / 2, y + dy / 2, { steps: 4 }) + await page.mouse.move(x + dx, y + dy, { steps: 4 }) + await page.mouse.up() + await page.waitForTimeout(100) + } + if (!(await centerOn(page, nation, drag, viewport, 2))) + fail('could not centre the first nation') + for (let i = 0; i < 12 && (await readCamera(page)).zoom < 5; i += 1) { + await page.click('button[aria-label="Zoom in"]') + await page.waitForTimeout(150) + } + await centerOn(page, nation, drag, viewport, 2) + await page.waitForTimeout(600) + const zoom = (await readCamera(page)).zoom + if (zoom < 2.5) fail(`could not zoom in far enough (zoom ${zoom})`) + + s = await stats(page) + if (s.sprites !== 'on') fail(`zoomed in, sprites should be on, got ${s.sprites}`) + if (!(s.units > 0)) fail('zoomed in on a capital, there should be villagers') + if (!(s.halls >= 1)) fail('zoomed in on a capital, its hall should be drawn') + if (!(s.resources > 0)) fail('zoomed in on land, there should be resource objects') + if (process.env.E2E_SHOTS) + await page.screenshot({ path: `${process.env.E2E_SHOTS}/units-still.png` }) + + // time runs, and the villagers walk: the picture changes + const before = await page.screenshot({ clip: { x: 340, y: 150, width: 600, height: 500 } }) + await page.click('.time-controls__play') + await page.waitForTimeout(3000) + const after = await page.screenshot({ clip: { x: 340, y: 150, width: 600, height: 500 } }) + if (before.equals(after)) + fail('the picture did not change while time ran: villagers did not move') + if (process.env.E2E_SHOTS) + await page.screenshot({ path: `${process.env.E2E_SHOTS}/units-running.png` }) + + // zooming back out takes the sprites away + for (let i = 0; i < 14 && (await readCamera(page)).zoom > 1; i += 1) { + await page.click('button[aria-label="Zoom out"]') + await page.waitForTimeout(100) + } + s = await stats(page) + if (s.sprites !== 'off') fail('zoomed back out, sprites should be off again') + await withTimeout( + page.evaluate(() => document.title), + 5_000, + 'the page being alive' + ) + await page.close() + } finally { + await browser.close() + stop() + } + if (problems.length > 0) { + console.error(`FAIL\n${problems.map((p) => ` - ${p}`).join('\n')}`) + process.exit(1) + } + console.log( + 'PASS: sprites gate on zoom, draw resources, halls and villagers, and the villagers move' + ) +} + +main().catch((error) => { + console.error(error) + process.exit(1) +}) diff --git a/apps/web/package.json b/apps/web/package.json index 8525842..f962a7a 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -12,7 +12,8 @@ "test": "vitest run --passWithNoTests", "e2e": "node e2e/strict-mode.e2e.mjs", "e2e:mobile": "node e2e/mobile.e2e.mjs", - "e2e:time": "node e2e/time.e2e.mjs" + "e2e:time": "node e2e/time.e2e.mjs", + "e2e:units": "node e2e/units.e2e.mjs" }, "dependencies": { "@sovereign/config": "workspace:*", diff --git a/apps/web/src/MapView.tsx b/apps/web/src/MapView.tsx index c147398..db96eca 100644 --- a/apps/web/src/MapView.tsx +++ b/apps/web/src/MapView.tsx @@ -303,6 +303,16 @@ const MapView: React.FC = () => { for (const name of LAYER_NAMES) renderer.setLayer(name, ready.layers[name], width, height) + renderer.setNationColors(ready.snapshot.nations.map((n) => n.color)) + renderer.setSpriteWorld({ + width, + height, + resources: ready.fields.resources, + roads: ready.roads, + halls: ready.snapshot.nations.map((n) => ({ tile: n.capital, color: n.color })) + }) + renderer.setUnits(ready.units) + mapSizeRef.current = { width, height, tileSize } biomeIdsRef.current = ready.fields.biomeIds baseLayerRef.current = ready.layers.biome @@ -443,6 +453,7 @@ const MapView: React.FC = () => { timestep: store.timestep, saturated: ticked.saturated }) + rendererRef.current?.setUnits(ticked.units) if (ticked.claims > 0) { nationsRef.current = ticked.nations store.setNations(ticked.nations) diff --git a/apps/web/src/host/protocol.ts b/apps/web/src/host/protocol.ts index 38f2aae..a36711f 100644 --- a/apps/web/src/host/protocol.ts +++ b/apps/web/src/host/protocol.ts @@ -8,6 +8,7 @@ import type { NationSnapshot, ResourceSlots, StrategicPoint, + UnitSnapshot, WorldSnapshot } from '@sovereign/contracts' import type { LayerName } from '@sovereign/renderer' @@ -46,6 +47,10 @@ export interface WorldReady { /** Every overlay as RGBA pixels, `width * height * 4` bytes. */ layers: Record fields: WorldFields + /** One byte per tile for the road sprites: 0 for none, else `16 | sides` (see `roadMaskFromRoutes`). */ + roads: Uint8Array + /** Where every unit is. */ + units: UnitSnapshot } /** The world after some ticks. */ @@ -64,6 +69,8 @@ export interface WorldTicked { ownership?: Uint8Array /** The political overlay as RGBA pixels, when it was asked for and is out of date. */ political?: Uint8ClampedArray + /** Where every unit is now (sent every time: they walk). */ + units: UnitSnapshot } export type WorldResponse = diff --git a/apps/web/src/host/readyMessage.ts b/apps/web/src/host/readyMessage.ts index 761883d..f399baf 100644 --- a/apps/web/src/host/readyMessage.ts +++ b/apps/web/src/host/readyMessage.ts @@ -13,12 +13,13 @@ import { humidityRgba, politicalRgba, resourceRgba, + roadMaskFromRoutes, strategicRgba, temperatureRgba, type LayerName, type PoliticalStyle } from '@sovereign/renderer' -import type { ResourceSlot } from '@sovereign/contracts' +import type { ResourceSlot, UnitSnapshot } from '@sovereign/contracts' import type { World } from '@sovereign/simulation' import type { WorldFields, WorldReady } from './protocol' @@ -36,6 +37,11 @@ function slotArrays(slot: ResourceSlot): Uint8Array[] { return [slot.type, slot.richness, slot.stock] } +/** The buffers of a unit snapshot, for a transfer list. */ +export function unitBuffers(units: UnitSnapshot): ArrayBuffer[] { + return [units.id, units.kind, units.owner, units.x, units.y].map((a) => a.buffer as ArrayBuffer) +} + export function buildReady(world: World, style: PoliticalStyle): Built { const t = world.terrain const { width, height } = t @@ -72,20 +78,26 @@ export function buildReady(world: World, style: PoliticalStyle): Built { ownership: world.map.ownership.slice() } + const roads = roadMaskFromRoutes(t.routes, width, height) + const units = world.unitPositions() const { resources, ...flat } = fields const transfer = [ ...Object.values(layers), ...Object.values(flat), ...slotArrays(resources.surface), - ...slotArrays(resources.ground) + ...slotArrays(resources.ground), + roads ].map((array) => array.buffer as ArrayBuffer) + transfer.push(...unitBuffers(units)) return { message: { type: 'ready', snapshot: world.snapshot(), strategicPoints: t.strategicPoints.map((p) => ({ ...p })), layers, - fields + fields, + roads, + units }, transfer } diff --git a/apps/web/src/host/tickRunner.ts b/apps/web/src/host/tickRunner.ts index 311592b..a53483a 100644 --- a/apps/web/src/host/tickRunner.ts +++ b/apps/web/src/host/tickRunner.ts @@ -13,6 +13,7 @@ import { biomeRgba, politicalRgba, type PoliticalStyle } from '@sovereign/renderer' import type { World } from '@sovereign/simulation' import type { RunOptions, WorldTicked } from './protocol' +import { unitBuffers } from './readyMessage' export interface Ticked { message: WorldTicked @@ -62,9 +63,10 @@ export class TickRunner { time: world.clock.time, claims, saturated: world.saturated, - nations: world.snapshot().nations + nations: world.snapshot().nations, + units: world.unitPositions() } - const transfer: ArrayBuffer[] = [] + const transfer: ArrayBuffer[] = unitBuffers(message.units) const due = options.flush === true || world.saturated || this.now() - this.lastSent >= this.minOverlayMs diff --git a/apps/web/src/state/persistence.ts b/apps/web/src/state/persistence.ts index 6590696..35b5b54 100644 --- a/apps/web/src/state/persistence.ts +++ b/apps/web/src/state/persistence.ts @@ -16,7 +16,8 @@ const DB_NAME = 'sovereign' // 4: engine save format 3 (every tile has two resource slots with richness and stock); older records are dropped. // 5: engine save format 4 (a route network, and the profile of each nation's land); older records are dropped. // 6: engine save format 5 (nations own provinces, with expansion points); older records are dropped. -const DB_VERSION = 6 +// 7: engine save format 6 (the world has units: the entity store is saved); older records are dropped. +const DB_VERSION = 7 const STORE_NAME = 'saves' /* ------------------------------------------------------------------ */ diff --git a/apps/web/tests/readyMessage.test.ts b/apps/web/tests/readyMessage.test.ts index 8f5c406..5d398f7 100644 --- a/apps/web/tests/readyMessage.test.ts +++ b/apps/web/tests/readyMessage.test.ts @@ -6,11 +6,12 @@ import { humidityRgba, politicalRgba, resourceRgba, + roadMaskFromRoutes, strategicRgba, temperatureRgba } from '@sovereign/renderer' import { World } from '@sovereign/simulation' -import type { ResourceSlot } from '@sovereign/contracts' +import type { ResourceSlot, UnitSnapshot } from '@sovereign/contracts' import { buildReady } from '../src/host/readyMessage' import type { WorldFields } from '../src/host/protocol' @@ -46,6 +47,14 @@ function fieldArrays(fields: WorldFields): Array { ] } +const unitArrays = (u: UnitSnapshot): Array => [ + u.id, + u.kind, + u.owner, + u.x, + u.y +] + const make = (): World => World.create({ seed: 21, config: SMALL }) describe('buildReady', () => { @@ -134,10 +143,31 @@ describe('buildReady', () => { for (const array of fieldArrays(message.fields)) expect(own.has(array.buffer)).toBe(false) }) + it('carries the units as the world places them, in tiles', () => { + expect(message.units).toEqual(world.unitPositions()) + expect(message.units.count).toBeGreaterThan(0) + }) + + it('carries a road byte per tile, made from the routes', () => { + expect(message.roads).toEqual(roadMaskFromRoutes(world.terrain.routes, width, height)) + expect(message.roads.length).toBe(width * height) + expect(message.roads.some((v) => v !== 0)).toBe(true) + }) + + it("sends the units' own copies, never the engine's arrays", () => { + const again = world.unitPositions() + for (const key of ['id', 'kind', 'owner', 'x', 'y'] as const) { + expect(message.units[key].buffer).not.toBe(again[key].buffer) + } + }) + it('lists every buffer to transfer exactly once, and nothing else', () => { - const buffers = [...Object.values(message.layers), ...fieldArrays(message.fields)].map( - (a) => a.buffer - ) + const buffers = [ + ...Object.values(message.layers), + ...fieldArrays(message.fields), + message.roads, + ...unitArrays(message.units) + ].map((a) => a.buffer) expect(transfer.length).toBe(buffers.length) expect(new Set(transfer).size).toBe(transfer.length) for (const b of buffers) expect(transfer).toContain(b) diff --git a/apps/web/tests/simulationHost.test.ts b/apps/web/tests/simulationHost.test.ts index 4bd4ea7..a8b2a50 100644 --- a/apps/web/tests/simulationHost.test.ts +++ b/apps/web/tests/simulationHost.test.ts @@ -33,7 +33,16 @@ const TICKED: WorldTicked = { time: 10, claims: 2, saturated: false, - nations: [] + nations: [], + units: { + tick: 10, + count: 0, + id: new Uint32Array(0), + kind: new Uint8Array(0), + owner: new Uint8Array(0), + x: new Float32Array(0), + y: new Float32Array(0) + } } const setup = (): { host: SimulationHost; worker: FakeWorker } => { diff --git a/apps/web/tests/tickRunner.test.ts b/apps/web/tests/tickRunner.test.ts index 3f6361b..2b1b961 100644 --- a/apps/web/tests/tickRunner.test.ts +++ b/apps/web/tests/tickRunner.test.ts @@ -87,6 +87,28 @@ describe('TickRunner: running the world', () => { }) }) +describe('TickRunner: the units', () => { + it('says where every unit is after the run, in tiles', () => { + const { world, runner } = setup() + const { message } = runner.run(30) + expect(message.units).toEqual(world.unitPositions()) + expect(message.units.tick).toBe(30) + expect(message.units.count).toBeGreaterThan(0) + }) + + it('sends units every time, even when nothing else changed, and they have moved on', () => { + const { runner } = setup() + const first = runner.run(1).message.units + const last = runner.run(40).message.units + expect(last.tick).toBe(first.tick + 40) + let moved = 0 + for (let i = 0; i < first.count; i += 1) { + if (first.x[i] !== last.x[i] || first.y[i] !== last.y[i]) moved += 1 + } + expect(moved).toBeGreaterThan(0) + }) +}) + describe('TickRunner: ownership and the political overlay', () => { it('sends nothing about ownership when nothing was claimed', () => { const { runner } = setup() @@ -139,13 +161,18 @@ describe('TickRunner: ownership and the political overlay', () => { it('lists every buffer it sends for transfer', () => { const { runner } = setup() const { message, transfer } = runner.run(300, { political: true }) - const buffers = [message.ownership, message.political].map((a) => a?.buffer) + const u = message.units + const buffers = [u.id, u.kind, u.owner, u.x, u.y, message.ownership, message.political].map( + (a) => a?.buffer + ) expect(transfer).toEqual(buffers) }) - it('has nothing to transfer when nothing is sent', () => { + it('transfers only the units when nothing else is sent', () => { const { runner } = setup() - expect(runner.run(0).transfer).toEqual([]) + const { message, transfer } = runner.run(0) + const u = message.units + expect(transfer).toEqual([u.id, u.kind, u.owner, u.x, u.y].map((a) => a.buffer)) }) }) diff --git a/docs/decisions/0008-units-and-a-living-world.md b/docs/decisions/0008-units-and-a-living-world.md index 47cbd53..dac7769 100644 --- a/docs/decisions/0008-units-and-a-living-world.md +++ b/docs/decisions/0008-units-and-a-living-world.md @@ -49,6 +49,13 @@ ADR 0007 made the world tick, but nations grow by an abstract points-and-claims So nodes as entities is confirmed and the tile-data fallback in the plan is not needed. +## What M1 built (and what it did not) + +- `EntityStore` (struct-of-arrays, lowest-free-id allocation, saved and hashed), `Pathfinder` and `RouteCache` over the 4-tile cost grid (step cost is the mean of two cells so a route and its reverse cost the same), counter-based randomness for unit behaviour (a pure hash of seed, unit, tick and purpose, so nothing about it is saved), and a timer-wheel `WanderSystem` whose wheel is derived from the rows' `wake` ticks. Hash schema 5, save format 6, web database version 7. +- A unit arriving in a cell stands on that cell's **anchor tile** (the land tile nearest its middle): the middle of a coastal cell can be sea. +- Drawing: `SpriteLayers` (pooled sprites for the visible tiles only, from one procedural atlas), unit positions sent with every run and glided on the main thread by `UnitInterpolator`, a road byte per tile from the route network, a hall at each capital. Sprites replace nothing: they show when a tile is 10 screen pixels wide and the overlays stay underneath. +- **Not done, on purpose:** resource nodes are still the tile slot arrays (the nodes-as-rows migration is M2, when gathering needs it); there are no gatherers, stockpiles, houses or roads that emerge from walking; the starting halls stand on the capitals the old system picked. + ## Alternatives considered - **Keep expansion as a system and add units on top as decoration.** Rejected: the owner asked for the behaviour, not the picture; a settler who walks but whose claim is bought by points is a lie. diff --git a/docs/development.md b/docs/development.md index 62660a5..e5e2eb6 100644 --- a/docs/development.md +++ b/docs/development.md @@ -38,6 +38,7 @@ Installing downloads the Electron binary. To skip it when you only work on the e | `pnpm --filter @sovereign/web e2e` | the browser end-to-end test on the desktop: the StrictMode double mount, then the mouse (hover, wheel, drag, click a nation); needs Chromium (`pnpm --filter @sovereign/web exec playwright install chromium`) | | `pnpm --filter @sovereign/web e2e:mobile` | the same on a phone, in Chromium's touch emulation at 390 x 844 and 844 x 390: the layout fits, one finger pans, two fingers pinch, a tap opens a nation's panel and fills the tile inspector. Set `E2E_SHOTS=` to save screenshots. Real iOS and Android devices are not covered | | `pnpm --filter @sovereign/web e2e:time` | time: on the desktop, play, pause, the speeds and the keys (Space, + and -), a nation growing in its panel until the borders settle; on a phone (portrait and landscape), the transport bar fits, its buttons are big enough to tap and it does not cover the HUD, the toolbar or the legend. A few minutes in software GL (a 2000 x 2000 world, then a run to settlement) | +| `pnpm --filter @sovereign/web e2e:units` | the sprite layers: zoomed out there are no sprites, zoomed in on a capital there are resource objects, roads, a hall and villagers, the villagers move while time runs, and zooming out removes them again. A few minutes in software GL (a 2000 x 2000 world). Set `E2E_SHOTS=` to save screenshots | | `pnpm probe` | the probes in `tests/probe/`. Alone it times world generation, hash, save and load. `pnpm probe -- tests/probe/biome-coverage.probe.ts` generates 10 full-size worlds and reports each biome's share of land, the ocean amounts, elevation percentiles, river and resource coverage, strategic point counts and whether all 26 biomes appear | | `pnpm probe -- tests/probe/resource-quality.probe.ts` | generates 10 full-size worlds and reports every resource's share of land, its clustering (patches or speckle), how many landmasses lack it, and its geology (height, ridge, basin, river and coast, top biomes) | | `pnpm probe -- tests/probe/units.probe.ts` | what a simulated unit costs: a gatherer loop for 2,000, 10,000 and 30,000 units over the real cost grid, with every walker stepped each tick, with units that sleep until they arrive, and with routes shared between units | diff --git a/docs/roadmap.md b/docs/roadmap.md index 63684f9..d9f6cf6 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -23,7 +23,7 @@ The land is cut into about 2,100 provinces by travel cost, so borders are pulled ## In progress: a world that lives (units) -The abstract expansion of phase 3 is being replaced by **units**: villagers and settlers who walk, gather, carry, build and spread, with resource nodes as entities and territory from buildings, drawn as zoom-gated pixel sprites ([decision 0008](decisions/0008-units-and-a-living-world.md)). Stages: M1 entities and a world you can see, M2 the gather loop, M3 settle and build, M4 live (hunger, births, hunting), M5 spread (new villages, nations, secession, colonisation), M6 crowds and god powers. M0, the probes that fixed the budget (about 10,000 simulated units, shared routes, event-driven), is done. +The abstract expansion of phase 3 is being replaced by **units**: villagers and settlers who walk, gather, carry, build and spread, with resource nodes as entities and territory from buildings, drawn as zoom-gated pixel sprites ([decision 0008](decisions/0008-units-and-a-living-world.md)). Stages: M1 entities and a world you can see, M2 the gather loop, M3 settle and build, M4 live (hunger, births, hunting), M5 spread (new villages, nations, secession, colonisation), M6 crowds and god powers. M0, the probes that fixed the budget (about 10,000 simulated units, shared routes, event-driven), is done. **M1 is done**: an `EntityStore` of rows, A* over the cost grid with shared routes, a timer-wheel `WanderSystem` (villagers walk between places near their home; hash 5, save 6), and zoom-gated sprites (resources, roads from the route network, a hall at each capital, tinted walking villagers) from a procedural pixel-art atlas. Villagers only wander so far: they do not gather, build or settle yet (that is M2 onward). ## Phases diff --git a/docs/simulation/determinism.md b/docs/simulation/determinism.md index 3b34680..6e823b8 100644 --- a/docs/simulation/determinism.md +++ b/docs/simulation/determinism.md @@ -162,7 +162,7 @@ output: hex(h1) hex(h2) hex(h3) hex(h4), each as 8 lowercase hex digits (uint32) A state hash begins with the four ASCII bytes `SOVH`, then `writeUint32(HASH_SCHEMA_VERSION)`. Any change to the field list, order or encoding of what is hashed requires bumping `HASH_SCHEMA_VERSION` and regenerating the golden hashes with a rationale in the PR. Old versions stay documented here rather than being edited in place, so a reader can tell what an older golden entry actually hashed. -#### Version 4 (current) +#### Version 5 (current) The canonical layout of a world, written in this order (`World.stateHash()`), after the `SOVH` header and version: @@ -171,6 +171,19 @@ The canonical layout of a world, written in this order (`World.stateHash()`), af Then the province cut, which is derived from the terrain but fingerprinted so that an engine that cuts it differently is caught: `writeUint32(province count)`, then for each province `area` (uint32) and `seed` (uint32, the tile it was seeded from). 3. Strategic points: `writeUint32(count)`, then for each `x` (uint32), `y` (uint32), `type` (string), `value` (float64). Then the route hubs: `writeUint32(count)`, then for each `x` (uint32), `y` (uint32), `weight` (float64). Then the routes: `writeUint32(count)`, then for each `from` (uint32), `to` (uint32), `cost` (float64), `traffic` (float64), `writeUint32(path length)` and each path value as uint32. 4. Nations: `writeUint32(count)`, then for each: `id` (string), `name` (string), the colour as three `writeUint8`, the flag `type` (string), `background` and `accent` (three float64 each), a `writeUint8` of 0 or 1 for whether there is a `detail` colour (and, if 1, its three float64), `government` (string), the personality (`aggression`, `expansionism`, `diplomacy`, `mercantilism`, `militarism`, float64 each, in that order), `capital` (uint32), `founded` (float64), the stats (`population`, `military`, `economy`, `diplomacy`, float64 each, in that order), the profile of its land (`area`, `food`, `timber`, `stone`, `horses`, `metals`, `luxuries`, `diversity`, `coast`, `river`, `highGround`, `defence`, `traffic`, `contacts`, float64 each, in that order), then `expansionPoints` (float64), then `writeUint32(province count)` and each owned province id as uint32 **in the order the provinces were claimed**. +5. The villagers (the entity store): `writeUint32(rows)`, where `rows` is the store's high-water mark (the number of rows ever allocated, empty rows included), then each column in this order: `kind`, `x`, `y`, `owner`, `state`, `home`, `target`, `wake`, `legStart`, `legEnd`. The 8-bit columns (`kind`, `owner`, `state`) are written as one `writeUint8Array` of the first `rows` bytes (so each carries its length); every other column is `rows` values, each as `writeUint32` of the value taken as an unsigned 32-bit integer. An empty (despawned) row holds all zeros, so the hash does not depend on which rows came and went, only on what is alive where. Timers, routes and anchors are derived and not hashed. + +#### Version 4 (superseded by version 5) + +The canonical layout of a world, written in this order (`World.stateHash()`), after the `SOVH` header and version: + +1. `writeUint32(seed)` (the normalized engine seed), `writeFloat64(tick)`, `writeFloat64(timestep)`, `writeUint32(width)`, `writeUint32(height)`, `writeFloat64(seaLevel)` (the effective sea level after the land-ratio rescue). +2. The tile layers, each as one array writer (so each carries its length): `elevation`, `temperature`, `humidity` as `writeFloat32Array`; `biomeIds`, `riverMask`, `riverWidth`, then the six resource arrays (`surface.type`, `surface.richness`, `surface.stock`, `ground.type`, `ground.richness`, `ground.stock`, in that order), then `ownership`, all as `writeUint8Array`. A resource's stock is state (it changes by extraction and regrowth), so it is hashed along with the static type and richness. + Then the province cut, which is derived from the terrain but fingerprinted so that an engine that cuts it differently is caught: `writeUint32(province count)`, then for each province `area` (uint32) and `seed` (uint32, the tile it was seeded from). +3. Strategic points: `writeUint32(count)`, then for each `x` (uint32), `y` (uint32), `type` (string), `value` (float64). Then the route hubs: `writeUint32(count)`, then for each `x` (uint32), `y` (uint32), `weight` (float64). Then the routes: `writeUint32(count)`, then for each `from` (uint32), `to` (uint32), `cost` (float64), `traffic` (float64), `writeUint32(path length)` and each path value as uint32. +4. Nations: `writeUint32(count)`, then for each: `id` (string), `name` (string), the colour as three `writeUint8`, the flag `type` (string), `background` and `accent` (three float64 each), a `writeUint8` of 0 or 1 for whether there is a `detail` colour (and, if 1, its three float64), `government` (string), the personality (`aggression`, `expansionism`, `diplomacy`, `mercantilism`, `militarism`, float64 each, in that order), `capital` (uint32), `founded` (float64), the stats (`population`, `military`, `economy`, `diplomacy`, float64 each, in that order), the profile of its land (`area`, `food`, `timber`, `stone`, `horses`, `metals`, `luxuries`, `diversity`, `coast`, `river`, `highGround`, `defence`, `traffic`, `contacts`, float64 each, in that order), then `expansionPoints` (float64), then `writeUint32(province count)` and each owned province id as uint32 **in the order the provinces were claimed**. + +Version 5 differs from version 4 only by the entity section appended after the nations. #### Version 3 (superseded by version 4) @@ -211,7 +224,7 @@ They are regression pins: the correctness of what is under them (RNG, noise, mat ## 9. Test vectors -Produced by an independent reference implementation written from this document alone (Python integers and masks), and reproduced by the engine's tests. Hex values are lowercase. "Header" is `SOVH` and `writeUint32(4)` (schema version 4); the reference also reproduces the older versions' values (it takes the version as a parameter). +Produced by an independent reference implementation written from this document alone (Python integers and masks), and reproduced by the engine's tests. Hex values are lowercase. "Header" is `SOVH` and `writeUint32(5)` (schema version 5); the reference also reproduces the older versions' values (it takes the version as a parameter). **xoshiro128\*\* reference** (state `[1, 2, 3, 4]`, decimal): `11520, 0, 5927040, 70819200, 2031721883`. diff --git a/docs/simulation/save-format.md b/docs/simulation/save-format.md index 565541e..b16abf0 100644 --- a/docs/simulation/save-format.md +++ b/docs/simulation/save-format.md @@ -4,11 +4,11 @@ A save is the exact state of a `World` as bytes. The engine produces and reads i This is separate from the state **hash** ([determinism.md](determinism.md), section 7): a hash is a fingerprint, a save is the data. Decoding a save and hashing the result gives the hash of the world that was saved, on any engine. -## Layout (version 5) +## Layout (version 6) ```text bytes 0..3 magic "SOVW" (0x53 0x4f 0x56 0x57) -bytes 4..7 format version, uint32 big-endian (5) +bytes 4..7 format version, uint32 big-endian (6) bytes 8..11 header length N, uint32 big-endian bytes 12.. header: N bytes of UTF-8 JSON then thirteen tile layers, each width * height long, in this order: @@ -19,7 +19,7 @@ then thirteen tile layers, each width * height long, in this order: ownership one byte each ``` -The header is a JSON object with `seed` (the normalized uint32), `tick`, `width`, `height`, `seaLevel` (the effective one), `config` (the full resolved world config), `strategicPoints` (`x`, `y`, `type`, `value`), `hubs` (`x`, `y`, `weight`), `routes` (`from`, `to`, `cost`, `traffic` and `path`, the tiles as x, y pairs) and `nations` (every field of a nation, including its `profile` and its `expansionPoints`, with its `provinces` as a list of province ids in claim order). There is no layer length table: the layers' sizes follow from the config, and the file must be exactly the right size. +The header is a JSON object with `seed` (the normalized uint32), `tick`, `width`, `height`, `seaLevel` (the effective one), `config` (the full resolved world config), `strategicPoints` (`x`, `y`, `type`, `value`), `hubs` (`x`, `y`, `weight`), `routes` (`from`, `to`, `cost`, `traffic` and `path`, the tiles as x, y pairs) and `nations` (every field of a nation, including its `profile` and its `expansionPoints`, with its `provinces` as a list of province ids in claim order) and `entities` (the villagers, as one array per column of the entity store: `kind`, `x`, `y`, `owner`, `state`, `home`, `target`, `wake`, `legStart`, `legEnd`, one entry per row up to the store's high-water mark, empty rows included as zeros). There is no layer length table: the layers' sizes follow from the config, and the file must be exactly the right size. Encoding is deterministic: the same world always encodes to the same bytes, and `encode(decode(bytes))` equals `bytes`. Float layers are copied as raw little-endian bytes, so saving and loading are refused on a big-endian host rather than writing a file other machines would misread. @@ -49,3 +49,5 @@ Any change to the layout bumps `SAVE_FORMAT_VERSION`. Older versions are not mig **Version 4** (from version 3): the world has a route network and its nations have a profile. The header gained `hubs` and `routes`, the `strategicPoints` types changed (`peninsula` is gone, `isthmus` was added) and are found along the routes, every nation carries the `profile` of its land (what its stats, government and personality were derived from), and the config gained `routes`, `strategic` was rebuilt and `nations.startArea` was added. A version 3 file is refused as an unsupported version. **Version 5** (from version 4): nations own provinces. A nation's `provinces` is a list of province ids (it was a list of tile indices), in claim order, and every nation has `expansionPoints`; the config gained `provinces` and `expansion`. The province layer is derived and not saved. A version 4 file is refused as an unsupported version. + +**Version 6** (from version 5): the world has units. The header gained `entities`, the entity store's columns, and the config gained `units`. What is derived is not saved: the timer wheel is rebuilt from the `wake` column, routes are recomputed on demand (the route cache is a pure memo) and each cell's anchor tile is derived from the terrain. A version 5 file is refused as an unsupported version. diff --git a/packages/config/src/types.ts b/packages/config/src/types.ts index db96699..45f2ee2 100644 --- a/packages/config/src/types.ts +++ b/packages/config/src/types.ts @@ -314,6 +314,19 @@ export interface ProvincesConfig { costCap: number } +/** The people who walk the world: how many there are to start with and how they move. */ +export interface UnitsConfig { + /** How many villagers each nation starts with, at its capital. 0 for none. */ + perNation: number + /** Travel cost a walker pays per tick (a route's cost divided by this is the days it takes). */ + walkSpeed: number + /** How far (in route cells of `routes.cell` tiles) a villager wanders from home. */ + wanderRadius: number + /** The fewest and the most ticks a villager rests between walks. */ + restMin: number + restMax: number +} + /** How nations grow into free provinces as time passes. */ export interface ExpansionConfig { /** diff --git a/packages/config/src/world.ts b/packages/config/src/world.ts index 90d92b8..62b4cb9 100644 --- a/packages/config/src/world.ts +++ b/packages/config/src/world.ts @@ -21,6 +21,7 @@ import type { ProvincesConfig, ResourcePlacementSettings, RoutesConfig, + UnitsConfig, RiverConfig, StrategicConfig, TemperatureConfig, @@ -69,6 +70,8 @@ export interface WorldConfig { provinces: ProvincesConfig /** How nations grow into free provinces. */ expansion: ExpansionConfig + /** The people who walk the world. */ + units: UnitsConfig /** Where each resource is found, how rich it is and how it regrows. */ resources: ResourcePlacementSettings nations: NationsConfig @@ -400,6 +403,19 @@ export const defaultWorldConfig: WorldConfig = { costPerTile: 0.05 }, + /** + * Units: each nation starts with `perNation` villagers at its capital. They rest, pick a place within + * `wanderRadius` route cells, walk there (a route costs its cost over `walkSpeed` ticks) and rest again. + * See docs/decisions/0008-units-and-a-living-world.md. + */ + units: { + perNation: 24, + walkSpeed: 5, + wanderRadius: 10, + restMin: 1, + restMax: 6 + }, + /* ------------------------------------------------------------ */ /* Biome noise jitter */ /* ------------------------------------------------------------ */ @@ -820,6 +836,7 @@ export function resolveWorldConfig(overrides: WorldConfigOverrides = {}): WorldC routes: merge(d.routes, overrides.routes), provinces: merge(d.provinces, overrides.provinces), expansion: merge(d.expansion, overrides.expansion), + units: merge(d.units, overrides.units), resources: merge(d.resources, overrides.resources), nations: merge(d.nations, overrides.nations), timestep: overrides.timestep ?? d.timestep @@ -901,6 +918,7 @@ export function validateWorldConfig(config: WorldConfig): string[] { validateRoutes(config.routes, problems) validateProvinces(config.provinces, problems) validateExpansion(config.expansion, problems) + validateUnits(config.units, problems) validateStrategic(config.strategic, problems) return problems @@ -931,6 +949,26 @@ function validateStrategic(strategic: StrategicConfig, problems: string[]): void } } +/** Problems with the unit settings. */ +function validateUnits(units: UnitsConfig, problems: string[]): void { + const at = 'units' + if (!isInteger(units.perNation) || units.perNation < 0 || units.perNation > 5000) { + problems.push(`${at}.perNation must be a whole number from 0 to 5000`) + } + if (!(Number.isFinite(units.walkSpeed) && units.walkSpeed > 0)) { + problems.push(`${at}.walkSpeed must be a finite number above 0`) + } + if (!isInteger(units.wanderRadius) || units.wanderRadius < 1) { + problems.push(`${at}.wanderRadius must be a whole number of at least 1`) + } + if (!isInteger(units.restMin) || units.restMin < 1) { + problems.push(`${at}.restMin must be a whole number of at least 1`) + } + if (!isInteger(units.restMax) || units.restMax < units.restMin) { + problems.push(`${at}.restMax must be a whole number, at least ${at}.restMin`) + } +} + /** Problems with the expansion settings. */ function validateExpansion(expansion: ExpansionConfig, problems: string[]): void { const at = 'expansion' diff --git a/packages/config/tests/world.test.ts b/packages/config/tests/world.test.ts index 0bc203f..a651f46 100644 --- a/packages/config/tests/world.test.ts +++ b/packages/config/tests/world.test.ts @@ -639,3 +639,53 @@ describe('expansion settings (expansion)', () => { expect(resolved.expansion.costPerTile).toBe(expansion.costPerTile) }) }) + +describe('unit settings (units)', () => { + const units = defaultWorldConfig.units + const bad = (edit: (c: WorldConfig) => void): string[] => { + const c = clone() + edit(c) + return validateWorldConfig(c) + } + + it('is valid as shipped', () => { + expect(validateWorldConfig(defaultWorldConfig)).toEqual([]) + }) + + it('starts each nation with a village-sized handful, walking at a pace that crosses a cell in about a day', () => { + expect(units.perNation).toBe(24) + expect(units.walkSpeed).toBe(5) + expect(units.wanderRadius).toBe(10) + expect(units.restMin).toBeLessThanOrEqual(units.restMax) + }) + + it.each([ + ['a negative count', (c: WorldConfig) => (c.units.perNation = -1)], + ['a fractional count', (c: WorldConfig) => (c.units.perNation = 2.5)], + ['too many per nation', (c: WorldConfig) => (c.units.perNation = 5001)], + ['a walking speed of 0', (c: WorldConfig) => (c.units.walkSpeed = 0)], + ['an infinite walking speed', (c: WorldConfig) => (c.units.walkSpeed = Infinity)], + ['a wander radius of 0', (c: WorldConfig) => (c.units.wanderRadius = 0)], + ['a fractional wander radius', (c: WorldConfig) => (c.units.wanderRadius = 1.5)], + ['a rest of 0 ticks', (c: WorldConfig) => (c.units.restMin = 0)], + [ + 'a longest rest shorter than the shortest', + (c: WorldConfig) => ((c.units.restMin = 5), (c.units.restMax = 4)) + ], + ['a fractional rest', (c: WorldConfig) => (c.units.restMax = 6.5)] + ])('rejects %s', (_label, edit) => { + const problems = bad(edit) + expect(problems.length).toBeGreaterThan(0) + expect(problems.join('\n')).toMatch(/units/) + }) + + it('takes a count of 0, so a world can have no units at all', () => { + expect(bad((c) => (c.units.perNation = 0))).toEqual([]) + }) + + it('merges a partial override into the defaults', () => { + const resolved = resolveWorldConfig({ units: { perNation: 100 } }) + expect(resolved.units.perNation).toBe(100) + expect(resolved.units.walkSpeed).toBe(units.walkSpeed) + }) +}) diff --git a/packages/contracts/src/entity.ts b/packages/contracts/src/entity.ts new file mode 100644 index 0000000..f88cb34 --- /dev/null +++ b/packages/contracts/src/entity.ts @@ -0,0 +1,40 @@ +/** + * @module entity + * @description The kinds of thing that live in the entity store (units, later animals, buildings...). A kind + * is one byte; 0 means the row is empty. + */ +export const EntityKind = { + /** An empty row. */ + None: 0, + /** A person: walks, works, carries. */ + Villager: 1 +} as const + +export type EntityKindId = (typeof EntityKind)[keyof typeof EntityKind] + +/** The owner byte of an entity that belongs to no nation (the same value the ownership layer uses). */ +export const NO_OWNER = 255 + +/** What a villager is doing. */ +export const UnitState = { + /** Standing about; `wake` is the tick it next sets off. */ + Rest: 0, + /** On a route toward `target`; it arrives at tick `wake` (= `legEnd`). */ + Walk: 1 +} as const + +export type UnitStateId = (typeof UnitState)[keyof typeof UnitState] + +/** Where every unit is right now, for a host to draw: one entry per living unit, by id. */ +export interface UnitSnapshot { + /** The tick the positions are for. */ + tick: number + count: number + id: Uint32Array + kind: Uint8Array + /** The index of the nation it belongs to, or {@link NO_OWNER}. */ + owner: Uint8Array + /** Position in tiles (fractional while walking). */ + x: Float32Array + y: Float32Array +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 6df3309..f377cb9 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -3,6 +3,7 @@ * @description Pure shared types and static tables. Depends on nothing internal. */ export * from './biomes' +export * from './entity' export * from './nation' export * from './quantile' export * from './resources' diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts index 14c56a7..f744732 100644 --- a/packages/renderer/src/index.ts +++ b/packages/renderer/src/index.ts @@ -7,4 +7,5 @@ export * from './Camera' export * from './layers' export * from './palettes' +export * from './sprites' export * from './view' diff --git a/packages/renderer/src/pixi/MapRenderer.ts b/packages/renderer/src/pixi/MapRenderer.ts index 33fde0a..9d1e29a 100644 --- a/packages/renderer/src/pixi/MapRenderer.ts +++ b/packages/renderer/src/pixi/MapRenderer.ts @@ -12,6 +12,8 @@ import { Application, BufferImageSource, Container, Sprite, Texture } from 'pixi import type { Camera } from '../Camera' import type { LayerName } from '../layers' import { clampedViewport, tileAtScreen, viewTransform } from '../view' +import type { UnitSnapshot } from '@sovereign/contracts' +import { SpriteLayers, type SpriteWorld } from './SpriteLayers' export interface MapRendererOptions { /** CSS class given to the canvas the renderer creates. */ @@ -30,6 +32,7 @@ export class MapRenderer { private readonly tileSize: number private readonly world = new Container() private readonly sprites = new Map() + private readonly spriteLayers: SpriteLayers private mapWidth = 0 private mapHeight = 0 private destroyed = false @@ -45,6 +48,11 @@ export class MapRenderer { this.canvas = canvas this.tileSize = tileSize this.app.stage.addChild(this.world) + this.spriteLayers = new SpriteLayers(tileSize) + // the overlays are added later, so the sprites say they go on top + this.world.sortableChildren = true + this.spriteLayers.container.zIndex = 1000 + this.world.addChild(this.spriteLayers.container) } /** @@ -128,6 +136,21 @@ export class MapRenderer { sprite.position.set((-width * this.tileSize) / 2, (-height * this.tileSize) / 2) } + /** Set what the sprite layers (resources, roads, halls) draw from; shown when the camera is close. */ + setSpriteWorld(world: SpriteWorld): void { + this.spriteLayers.setWorld(world) + } + + /** The nations' colours by index, used to tint their units and banners. */ + setNationColors(colors: ReadonlyArray): void { + this.spriteLayers.setNationColors(colors) + } + + /** The newest unit snapshot; the renderer glides the units to it. */ + setUnits(snapshot: UnitSnapshot): void { + this.spriteLayers.setUnits(snapshot, performance.now()) + } + /** The largest texture side the GPU accepts; larger layers would silently draw nothing. */ private maxTextureSize(): number { const gl = (this.app.renderer as { gl?: WebGL2RenderingContext }).gl @@ -154,9 +177,25 @@ export class MapRenderer { const t = viewTransform(this.camera, width, height) this.world.scale.set(t.scale) this.world.position.set(t.x, t.y) + this.spriteLayers.update(this.camera, width, height, performance.now()) + this.publishSpriteStats() this.app.renderer.render(this.app.stage) } + /** Put what the sprite layers drew on the canvas as data attributes, so a page or a test can see it. */ + private publishSpriteStats(): void { + const { stats } = this.spriteLayers + const data = this.canvas.dataset + const set = (key: string, value: string): void => { + if (data[key] !== value) data[key] = value + } + set('sprites', stats.active ? 'on' : 'off') + set('spriteRoads', String(stats.roads)) + set('spriteResources', String(stats.resources)) + set('spriteHalls', String(stats.halls)) + set('spriteUnits', String(stats.units)) + } + /** The canvas' size in CSS pixels (at least 1 x 1). */ getViewportSize(): { width: number; height: number } { return clampedViewport(this.canvas.clientWidth, this.canvas.clientHeight) diff --git a/packages/renderer/src/pixi/SpriteLayers.ts b/packages/renderer/src/pixi/SpriteLayers.ts new file mode 100644 index 0000000..9c114d9 --- /dev/null +++ b/packages/renderer/src/pixi/SpriteLayers.ts @@ -0,0 +1,263 @@ +/** + * @module SpriteLayers + * @description The sprite layers drawn over the map when the camera is close: roads, resource objects, halls + * and the units. All of it is pooled sprites cut from one procedural atlas, made only for what is on screen + * (see `visibleTileRect`), and none of it is kept between frames except the pool, so the cost of a frame + * follows the screen and not the size of the map. + * + * Resource sprites are drawn from the tile slot arrays (what and how much is left), roads from a road byte + * per tile, halls from the nations' capitals and units from an interpolated snapshot. Nothing here is + * simulation state: it only draws what the world last said. + */ +import { BufferImageSource, Container, Rectangle, Sprite, Texture } from 'pixi.js' +import { NO_OWNER, type ResourceSlots, type UnitSnapshot } from '@sovereign/contracts' +import type { Camera } from '../Camera' +import { + ROAD_PRESENT, + SPRITE_SIZE, + UnitInterpolator, + buildSpriteAtlas, + resourceFrameName, + resourceSpriteState, + roadFrameName +} from '../sprites' +import { spritesShown, visibleTileRect } from '../view' + +/** What the layers draw the map's fixed things from. Held by reference: the caller keeps it up to date. */ +export interface SpriteWorld { + width: number + height: number + resources: ResourceSlots + /** One byte per tile: 0 for no road, else `16 | sides` (see `roadMaskFromRoutes`). */ + roads: Uint8Array + /** The tile and colour of each hall. */ + halls: ReadonlyArray<{ tile: number; color: readonly [number, number, number] }> +} + +const GREY = 0xc8c8c8 + +/** Resource objects fill this much of a tile, so neighbours do not touch. */ +const RESOURCE_SCALE = 0.8 +/** Villagers are drawn this many times a tile's sprite size, so they read among the objects. */ +const UNIT_SCALE = 1.9 + +const hex = (c: readonly [number, number, number]): number => (c[0] << 16) | (c[1] << 8) | c[2] + +/** Sprites that are reused from frame to frame: take what is needed, and the rest are hidden. */ +class SpritePool { + private readonly sprites: Sprite[] = [] + private used = 0 + + constructor(private readonly parent: Container) {} + + begin(): void { + this.used = 0 + } + + take(texture: Texture): Sprite { + let sprite = this.sprites[this.used] + if (sprite === undefined) { + sprite = new Sprite(texture) + this.parent.addChild(sprite) + this.sprites.push(sprite) + } else if (sprite.texture !== texture) { + sprite.texture = texture + } + sprite.visible = true + sprite.tint = 0xffffff + this.used += 1 + return sprite + } + + /** How many sprites are showing. */ + get shown(): number { + return this.used + } + + end(): void { + for (let i = this.used; i < this.sprites.length; i += 1) + (this.sprites[i] as Sprite).visible = false + } +} + +/** What the layers drew in the last frame (for the host's status and for tests). */ +export interface SpriteStats { + /** False when the camera is too far out for sprites (the overlays show instead). */ + active: boolean + roads: number + resources: number + halls: number + units: number +} + +export class SpriteLayers { + readonly stats: SpriteStats = { active: false, roads: 0, resources: 0, halls: 0, units: 0 } + readonly container = new Container() + private readonly roadPool: SpritePool + private readonly resourcePool: SpritePool + private readonly buildingPool: SpritePool + private readonly unitPool: SpritePool + private readonly textures = new Map() + private readonly source: BufferImageSource + private readonly interpolator = new UnitInterpolator() + private world: SpriteWorld | null = null + private nationColors: number[] = [] + private readonly scale: number + + constructor(private readonly tileSize: number) { + const atlas = buildSpriteAtlas() + this.source = new BufferImageSource({ + resource: new Uint8Array(atlas.rgba.buffer, atlas.rgba.byteOffset, atlas.rgba.byteLength), + width: atlas.width, + height: atlas.height, + format: 'rgba8unorm', + scaleMode: 'nearest' + }) + for (const [name, f] of Object.entries(atlas.frames)) { + this.textures.set( + name, + new Texture({ source: this.source, frame: new Rectangle(f.x, f.y, f.w, f.h) }) + ) + } + this.scale = tileSize / SPRITE_SIZE + this.container.visible = false + const layer = (): Container => this.container.addChild(new Container()) + this.roadPool = new SpritePool(layer()) + this.resourcePool = new SpritePool(layer()) + this.buildingPool = new SpritePool(layer()) + this.unitPool = new SpritePool(layer()) + } + + /** Set what the fixed layers draw from (the same object may be passed again after it changes). */ + setWorld(world: SpriteWorld): void { + this.world = world + } + + /** The nations' colours by index, for tinting units. */ + setNationColors(colors: ReadonlyArray): void { + this.nationColors = colors.map(hex) + } + + /** The newest unit snapshot, received at `nowMs`. */ + setUnits(snapshot: UnitSnapshot, nowMs: number): void { + this.interpolator.push(snapshot, nowMs) + } + + private texture(name: string): Texture { + const t = this.textures.get(name) + if (t === undefined) throw new Error(`the sprite atlas has no frame ${name}`) + return t + } + + /** Bring the sprites up to date for this frame. Call before rendering, inside the world container. */ + update(camera: Camera, viewportWidth: number, viewportHeight: number, nowMs: number): void { + const world = this.world + if (world === null || !spritesShown(camera.zoom, this.tileSize)) { + this.container.visible = false + this.stats.active = false + return + } + this.container.visible = true + const ts = this.tileSize + const originX = (-world.width * ts) / 2 + const originY = (-world.height * ts) / 2 + const rect = visibleTileRect(camera, viewportWidth, viewportHeight, { + width: world.width, + height: world.height, + tileSize: ts + }) + + this.roadPool.begin() + this.resourcePool.begin() + for (let y = rect.y0; y < rect.y1; y += 1) { + for (let x = rect.x0; x < rect.x1; x += 1) { + const tile = y * world.width + x + const px = originX + x * ts + const py = originY + y * ts + const road = world.roads[tile] as number + if ((road & ROAD_PRESENT) !== 0) { + const s = this.roadPool.take(this.texture(roadFrameName(road & 15))) + s.scale.set(this.scale) + s.position.set(px, py) + } + const ground = world.resources.ground + const surface = world.resources.surface + const g = ground.type[tile] as number + const f = surface.type[tile] as number + if (g !== 0) { + const state = resourceSpriteState( + ground.stock[tile] as number, + ground.richness[tile] as number + ) + const s = this.resourcePool.take(this.texture(resourceFrameName(g, state))) + // under a surface resource, a mineral is drawn smaller in the corner so both can be seen + const shrink = f !== 0 ? 0.5 : RESOURCE_SCALE + s.scale.set(this.scale * shrink) + const inset = f !== 0 ? ts * 0.45 : (ts * (1 - RESOURCE_SCALE)) / 2 + s.position.set(px + inset, py + inset) + } + if (f !== 0) { + const state = resourceSpriteState( + surface.stock[tile] as number, + surface.richness[tile] as number + ) + const s = this.resourcePool.take(this.texture(resourceFrameName(f, state))) + s.scale.set(this.scale * RESOURCE_SCALE) + s.position.set(px + (ts * (1 - RESOURCE_SCALE)) / 2, py + (ts * (1 - RESOURCE_SCALE)) / 2) + } + } + } + this.roadPool.end() + this.resourcePool.end() + + this.buildingPool.begin() + for (const hall of world.halls) { + const x = hall.tile % world.width + const y = (hall.tile - x) / world.width + if (x < rect.x0 - 1 || x >= rect.x1 + 1 || y < rect.y0 - 1 || y >= rect.y1 + 1) continue + const px = originX + x * ts + const py = originY + y * ts + const h = this.buildingPool.take(this.texture('hall')) + h.scale.set(this.scale * 2.2) + h.position.set(px - ts * 0.6, py - ts * 1.1) + const b = this.buildingPool.take(this.texture('banner')) + b.scale.set(this.scale * 1.6) + b.position.set(px + ts * 0.7, py - ts * 1.6) + b.tint = hex(hall.color) + } + this.buildingPool.end() + + this.unitPool.begin() + const frame = this.interpolator.sample(nowMs) + const left = rect.x0 - 1 + const right = rect.x1 + 1 + const top = rect.y0 - 1 + const bottom = rect.y1 + 1 + const step = Math.floor(nowMs / 180) + for (let i = 0; i < frame.count; i += 1) { + const x = frame.x[i] as number + const y = frame.y[i] as number + if (x < left || x >= right || y < top || y >= bottom) continue + const walking = x % 1 !== 0 || y % 1 !== 0 + const id = frame.id[i] as number + const s = this.unitPool.take(this.texture(`villager.${walking ? (step + id) & 1 : 0}`)) + s.anchor.set(0.5, 0.85) + s.scale.set(this.scale * UNIT_SCALE) + s.position.set(originX + (x + 0.5) * ts, originY + (y + 0.5) * ts) + const owner = frame.owner[i] as number + s.tint = owner === NO_OWNER ? GREY : (this.nationColors[owner] ?? GREY) + } + this.unitPool.end() + this.stats.active = true + this.stats.roads = this.roadPool.shown + this.stats.resources = this.resourcePool.shown + this.stats.halls = this.buildingPool.shown / 2 + this.stats.units = this.unitPool.shown + } + + destroy(): void { + this.container.destroy({ children: true }) + for (const t of this.textures.values()) t.destroy(false) + this.source.destroy() + } +} diff --git a/packages/renderer/src/pixi/index.ts b/packages/renderer/src/pixi/index.ts index 844a7c4..894ca9e 100644 --- a/packages/renderer/src/pixi/index.ts +++ b/packages/renderer/src/pixi/index.ts @@ -5,3 +5,4 @@ */ export { MapRenderer } from './MapRenderer' export type { MapRendererOptions } from './MapRenderer' +export type { SpriteWorld } from './SpriteLayers' diff --git a/packages/renderer/src/sprites/UnitInterpolator.ts b/packages/renderer/src/sprites/UnitInterpolator.ts new file mode 100644 index 0000000..271204e --- /dev/null +++ b/packages/renderer/src/sprites/UnitInterpolator.ts @@ -0,0 +1,113 @@ +/** + * @module sprites/UnitInterpolator + * @description Smooths unit movement on the main thread. The world sends where every unit is each time it + * has run some ticks; a screen draws sixty frames a second. The interpolator glides each unit from where + * it is shown now to where the newest snapshot puts it, over about as long as the snapshots are apart, so + * movement looks continuous at any speed. It is only a picture: it never feeds back into the simulation. + * + * Snapshots list units by ascending id (the engine iterates by id), so two snapshots are matched with a + * merge, without a map. + */ +import type { UnitSnapshot } from '@sovereign/contracts' + +export interface UnitInterpolatorOptions { + /** Shortest glide, in milliseconds. @default 40 */ + minMs?: number + /** Longest glide, in milliseconds. @default 500 */ + maxMs?: number + /** A unit that moved further than this many tiles jumps instead of gliding (a long run of ticks). @default 40 */ + jumpTiles?: number +} + +/** The units to draw this frame. The arrays are views that stay valid until the next `sample`. */ +export interface UnitFrame { + count: number + id: Uint32Array + kind: Uint8Array + owner: Uint8Array + x: Float32Array + y: Float32Array +} + +export class UnitInterpolator { + private readonly minMs: number + private readonly maxMs: number + private readonly jumpTiles: number + private count = 0 + private id = new Uint32Array(0) + private kind = new Uint8Array(0) + private owner = new Uint8Array(0) + private fromX = new Float32Array(0) + private fromY = new Float32Array(0) + private toX = new Float32Array(0) + private toY = new Float32Array(0) + private outX = new Float32Array(0) + private outY = new Float32Array(0) + private start = 0 + private duration = 1 + private lastPush = Number.NaN + + constructor(options: UnitInterpolatorOptions = {}) { + this.minMs = options.minMs ?? 40 + this.maxMs = options.maxMs ?? 500 + this.jumpTiles = options.jumpTiles ?? 40 + } + + /** Take a new snapshot, received at `nowMs`. */ + push(snapshot: UnitSnapshot, nowMs: number): void { + const n = snapshot.count + // where the old units are shown right now: the new glides start there + const shown = this.sample(nowMs) + const oldCount = this.count + const oldId = this.id.slice(0, oldCount) + const oldX = Float32Array.from(shown.x) + const oldY = Float32Array.from(shown.y) + + const fromX = new Float32Array(n) + const fromY = new Float32Array(n) + let i = 0 + for (let j = 0; j < n; j += 1) { + const id = snapshot.id[j] as number + const x = snapshot.x[j] as number + const y = snapshot.y[j] as number + while (i < oldCount && (oldId[i] as number) < id) i += 1 + if (i < oldCount && oldId[i] === id) { + const ox = oldX[i] as number + const oy = oldY[i] as number + const far = Math.max(Math.abs(x - ox), Math.abs(y - oy)) > this.jumpTiles + fromX[j] = far ? x : ox + fromY[j] = far ? y : oy + } else { + fromX[j] = x + fromY[j] = y + } + } + this.count = n + this.id = Uint32Array.from(snapshot.id.subarray(0, n)) + this.kind = Uint8Array.from(snapshot.kind.subarray(0, n)) + this.owner = Uint8Array.from(snapshot.owner.subarray(0, n)) + this.toX = Float32Array.from(snapshot.x.subarray(0, n)) + this.toY = Float32Array.from(snapshot.y.subarray(0, n)) + this.fromX = fromX + this.fromY = fromY + this.outX = new Float32Array(n) + this.outY = new Float32Array(n) + const gap = Number.isNaN(this.lastPush) ? this.maxMs : nowMs - this.lastPush + this.duration = Math.min(this.maxMs, Math.max(this.minMs, gap)) + this.start = nowMs + this.lastPush = nowMs + } + + /** Where every unit is at `nowMs`. */ + sample(nowMs: number): UnitFrame { + const n = this.count + const t = Math.min(1, Math.max(0, (nowMs - this.start) / this.duration)) + for (let i = 0; i < n; i += 1) { + const fx = this.fromX[i] as number + const fy = this.fromY[i] as number + this.outX[i] = fx + ((this.toX[i] as number) - fx) * t + this.outY[i] = fy + ((this.toY[i] as number) - fy) * t + } + return { count: n, id: this.id, kind: this.kind, owner: this.owner, x: this.outX, y: this.outY } + } +} diff --git a/packages/renderer/src/sprites/atlas.ts b/packages/renderer/src/sprites/atlas.ts new file mode 100644 index 0000000..7c5607b --- /dev/null +++ b/packages/renderer/src/sprites/atlas.ts @@ -0,0 +1,95 @@ +/** + * @module sprites/atlas + * @description Packs the whole procedural sprite set into one RGBA sheet with a table of frames, so a + * renderer uploads a single texture and cuts frames out of it. Pure: no DOM and no PixiJS. Any art + * that replaces this (hand-drawn, imported) only has to give the same frame names on the same kind of sheet. + */ +import { RESOURCE_CATALOG } from '@sovereign/contracts' +import { PixelCanvas } from './canvas' +import { drawBanner, drawHall, drawHouse, drawRoad, drawVillager } from './buildings' +import { drawResource } from './resources' + +/** Every sprite is this many pixels square. */ +export const SPRITE_SIZE = 16 + +/** What is drawn for a resource: a full deposit, a drawn-down one, or what is left when it is gone. */ +export const RESOURCE_SPRITE_STATES = ['full', 'low', 'empty'] as const +export type ResourceSpriteState = 0 | 1 | 2 + +/** Road sides, as bits of a road piece's mask: which neighbours the piece connects to. */ +export const ROAD_N = 1 +export const ROAD_E = 2 +export const ROAD_S = 4 +export const ROAD_W = 8 + +export interface SpriteFrame { + readonly x: number + readonly y: number + readonly w: number + readonly h: number +} + +export interface SpriteAtlas { + readonly width: number + readonly height: number + /** The sheet, RGBA, 4 bytes a pixel, row by row. */ + readonly rgba: Uint8ClampedArray + readonly frames: Readonly> +} + +/** Which picture a slot shows, from how much of its deposit is left (stock out of richness). */ +export function resourceSpriteState(stock: number, richness: number): ResourceSpriteState { + if (richness <= 0 || stock <= 0) return 2 + return stock * 2 >= richness ? 0 : 1 +} + +export function resourceFrameName(type: number, state: ResourceSpriteState): string { + const def = Number.isInteger(type) ? RESOURCE_CATALOG[type - 1] : undefined + if (def === undefined) throw new RangeError(`no resource has id ${type}`) + return `resource.${def.key}.${RESOURCE_SPRITE_STATES[state]}` +} + +export function roadFrameName(mask: number): string { + if (!Number.isInteger(mask) || mask < 0 || mask > 15) { + throw new RangeError(`a road mask is 0 to 15, got ${mask}`) + } + return `road.${mask}` +} + +const COLUMNS = 16 + +/** Draw every sprite and pack them in rows, in a fixed order. */ +export function buildSpriteAtlas(): SpriteAtlas { + const sprites: Array<[string, PixelCanvas]> = [] + const add = (name: string, draw: (c: PixelCanvas) => void): void => { + const c = new PixelCanvas(SPRITE_SIZE, SPRITE_SIZE) + draw(c) + sprites.push([name, c]) + } + add('villager.0', (c) => drawVillager(c, 0)) + add('villager.1', (c) => drawVillager(c, 1)) + add('banner', drawBanner) + add('house', drawHouse) + add('hall', drawHall) + for (const def of RESOURCE_CATALOG) { + for (let s = 0; s < 3; s += 1) { + add(`resource.${def.key}.${RESOURCE_SPRITE_STATES[s]}`, (c) => + drawResource(c, def.id, def.color, s as ResourceSpriteState) + ) + } + } + for (let mask = 0; mask < 16; mask += 1) add(roadFrameName(mask), (c) => drawRoad(c, mask)) + + const rows = Math.ceil(sprites.length / COLUMNS) + const width = COLUMNS * SPRITE_SIZE + const height = rows * SPRITE_SIZE + const rgba = new Uint8ClampedArray(width * height * 4) + const frames: Record = {} + sprites.forEach(([name, canvas], i) => { + const x = (i % COLUMNS) * SPRITE_SIZE + const y = Math.floor(i / COLUMNS) * SPRITE_SIZE + canvas.blitTo(rgba, width, x, y) + frames[name] = { x, y, w: SPRITE_SIZE, h: SPRITE_SIZE } + }) + return { width, height, rgba, frames } +} diff --git a/packages/renderer/src/sprites/buildings.ts b/packages/renderer/src/sprites/buildings.ts new file mode 100644 index 0000000..aed6335 --- /dev/null +++ b/packages/renderer/src/sprites/buildings.ts @@ -0,0 +1,91 @@ +/** + * @module sprites/buildings + * @description The villager, a banner, the house and hall, and road pieces. The villager and the banner + * are drawn in greys so the renderer can tint them with a nation's colour; everything else has its own colours. + */ +import { PixelCanvas, shade, type Rgb } from './canvas' +import { ROAD_E, ROAD_N, ROAD_S, ROAD_W } from './atlas' + +const grey = (v: number): Rgb => [v, v, v] +const OUTLINE: Rgb = [30, 24, 20] + +/** A walking villager, side on: frame 0 and 1 swing legs and arms opposite ways. */ +export function drawVillager(c: PixelCanvas, frame: 0 | 1): void { + c.ellipse(8, 4.5, 2, 2, grey(244)) // head + for (let y = 2; y <= 3; y += 1) + for (let x = 5; x <= 10; x += 1) if (c.solid(x, y)) c.set(x, y, grey(84)) // hair + c.fillRect(6, 7, 4, 4, grey(176)) // body + c.fillRect(6, 7, 1, 4, grey(206)) // lit edge + c.fillRect(9, 7, 1, 4, grey(138)) // shaded edge + c.fillRect(6, 9, 4, 1, grey(104)) // belt + if (frame === 0) { + c.fillRect(5, 8, 1, 3, grey(214)) // arms + c.fillRect(10, 8, 1, 2, grey(214)) + c.fillRect(6, 11, 1, 3, grey(120)) // legs apart + c.fillRect(9, 11, 1, 3, grey(92)) + } else { + c.fillRect(5, 8, 1, 2, grey(214)) + c.fillRect(10, 8, 1, 3, grey(214)) + c.fillRect(7, 11, 1, 3, grey(120)) // legs together + c.fillRect(8, 11, 1, 3, grey(92)) + } + c.outline(grey(30)) +} + +/** A flag on a pole, grey so it can take a nation's colour. */ +export function drawBanner(c: PixelCanvas): void { + c.fillRect(4, 2, 1, 12, grey(120)) + c.fillRect(5, 2, 7, 5, grey(250)) + c.fillRect(5, 5, 7, 2, grey(205)) + c.outline(grey(30)) +} + +export function drawHouse(c: PixelCanvas): void { + const wall: Rgb = [200, 165, 112] + const roof: Rgb = [172, 64, 52] + c.fillRect(3, 8, 10, 6, wall) + c.fillRect(3, 8, 10, 1, shade(wall, 1.15)) + c.fillRect(11, 9, 2, 5, shade(wall, 0.82)) + for (let j = 0; j < 4; j += 1) + c.fillRect(2 + j, 4 + j, 12 - 2 * j, 1, j < 2 ? shade(roof, 1.12) : roof) + c.fillRect(7, 11, 2, 3, [92, 62, 36]) // door + c.fillRect(4, 10, 2, 2, [150, 196, 226]) // window + c.outline(OUTLINE) +} + +export function drawHall(c: PixelCanvas): void { + const wall: Rgb = [176, 170, 158] + const roof: Rgb = [60, 84, 150] + c.fillRect(1, 8, 14, 6, wall) + c.fillRect(1, 8, 14, 1, shade(wall, 1.15)) + c.fillRect(12, 9, 3, 5, shade(wall, 0.8)) + for (let j = 0; j < 5; j += 1) + c.fillRect(1 + j, 3 + j, 14 - 2 * j, 1, j < 2 ? shade(roof, 1.18) : roof) + c.fillRect(7, 10, 3, 4, [84, 58, 34]) // great door + c.fillRect(3, 10, 2, 2, [150, 196, 226]) + c.fillRect(11, 10, 2, 2, [150, 196, 226]) + c.set(8, 1, [236, 200, 60]) // a finial on the ridge + c.set(8, 2, [236, 200, 60]) + c.outline(OUTLINE) +} + +/** + * A piece of road as an overlay on the ground: a worn patch in the middle and a two-pixel-wide arm to + * each side named in `mask` (the bits ROAD_N, ROAD_E, ROAD_S, ROAD_W), reaching the edge of the tile so + * that neighbouring pieces join. + */ +export function drawRoad(c: PixelCanvas, mask: number): void { + const dirt: Rgb = [152, 118, 78] + const worn: Rgb = [128, 96, 62] + c.fillRect(6, 6, 4, 4, dirt) + if ((mask & ROAD_N) !== 0) c.fillRect(7, 0, 2, 6, dirt) + if ((mask & ROAD_E) !== 0) c.fillRect(10, 7, 6, 2, dirt) + if ((mask & ROAD_S) !== 0) c.fillRect(7, 10, 2, 6, dirt) + if ((mask & ROAD_W) !== 0) c.fillRect(0, 7, 6, 2, dirt) + // wheel ruts and pebbles, only on ground the road already covers + for (let y = 0; y < c.height; y += 1) { + for (let x = 0; x < c.width; x += 1) { + if (c.solid(x, y) && ((x * 7 + y * 13 + mask * 5) & 7) === 0) c.set(x, y, worn) + } + } +} diff --git a/packages/renderer/src/sprites/canvas.ts b/packages/renderer/src/sprites/canvas.ts new file mode 100644 index 0000000..4c87833 --- /dev/null +++ b/packages/renderer/src/sprites/canvas.ts @@ -0,0 +1,128 @@ +/** + * @module sprites/canvas + * @description A tiny RGBA pixel canvas for drawing sprites in code. Everything is whole pixels and + * fully opaque or fully clear (crisp pixel art), and every operation is deterministic: integer + * coordinates and `+ - * /` only, so the same drawing gives the same bytes on every engine. + */ +export type Rgb = readonly [number, number, number] + +const clampByte = (v: number): number => (v < 0 ? 0 : v > 255 ? 255 : Math.round(v)) + +/** A colour scaled by `k` (above 1 lighter, below 1 darker), per channel and clamped. */ +export function shade(c: Rgb, k: number): Rgb { + return [clampByte(c[0] * k), clampByte(c[1] * k), clampByte(c[2] * k)] +} + +/** A colour moved a fraction `t` of the way to white. */ +export function tint(c: Rgb, t: number): Rgb { + return [ + clampByte(c[0] + (255 - c[0]) * t), + clampByte(c[1] + (255 - c[1]) * t), + clampByte(c[2] + (255 - c[2]) * t) + ] +} + +export class PixelCanvas { + readonly rgba: Uint8ClampedArray + + constructor( + readonly width: number, + readonly height: number + ) { + this.rgba = new Uint8ClampedArray(width * height * 4) + } + + inside(x: number, y: number): boolean { + return x >= 0 && y >= 0 && x < this.width && y < this.height + } + + /** Paint one pixel; anything off the canvas is ignored. */ + set(x: number, y: number, c: Rgb): void { + if (!this.inside(x, y)) return + const p = (y * this.width + x) * 4 + this.rgba[p] = c[0] + this.rgba[p + 1] = c[1] + this.rgba[p + 2] = c[2] + this.rgba[p + 3] = 255 + } + + solid(x: number, y: number): boolean { + return this.inside(x, y) && this.rgba[(y * this.width + x) * 4 + 3] === 255 + } + + fillRect(x: number, y: number, w: number, h: number, c: Rgb): void { + for (let j = 0; j < h; j += 1) for (let i = 0; i < w; i += 1) this.set(x + i, y + j, c) + } + + /** A filled ellipse with a light side (up and left) and a shadow side (down and right). */ + ellipse(cx: number, cy: number, rx: number, ry: number, c: Rgb): void { + for (let y = Math.floor(cy - ry); y <= Math.ceil(cy + ry); y += 1) { + for (let x = Math.floor(cx - rx); x <= Math.ceil(cx + rx); x += 1) { + const dx = (x - cx) / rx + const dy = (y - cy) / ry + if (dx * dx + dy * dy > 1) continue + const side = (dx + dy) / 2 + this.set(x, y, side < -0.3 ? shade(c, 1.22) : side > 0.3 ? shade(c, 0.74) : c) + } + } + } + + /** A one-pixel line (Bresenham). */ + line(x0: number, y0: number, x1: number, y1: number, c: Rgb): void { + const dx = Math.abs(x1 - x0) + const dy = -Math.abs(y1 - y0) + const sx = x0 < x1 ? 1 : -1 + const sy = y0 < y1 ? 1 : -1 + let err = dx + dy + let x = x0 + let y = y0 + for (;;) { + this.set(x, y, c) + if (x === x1 && y === y1) break + const e2 = 2 * err + if (e2 >= dy) { + err += dy + x += sx + } + if (e2 <= dx) { + err += dx + y += sy + } + } + } + + /** How many pixels are painted. */ + count(): number { + let n = 0 + for (let p = 3; p < this.rgba.length; p += 4) if (this.rgba[p] === 255) n += 1 + return n + } + + /** Paint a one-pixel outline around everything drawn (on the clear pixels that touch it, 4-way). */ + outline(c: Rgb): void { + const marks: number[] = [] + for (let y = 0; y < this.height; y += 1) { + for (let x = 0; x < this.width; x += 1) { + if (this.solid(x, y)) continue + if ( + this.solid(x - 1, y) || + this.solid(x + 1, y) || + this.solid(x, y - 1) || + this.solid(x, y + 1) + ) { + marks.push(x, y) + } + } + } + for (let i = 0; i < marks.length; i += 2) + this.set(marks[i] as number, marks[i + 1] as number, c) + } + + /** Copy this canvas into a larger RGBA buffer at (x, y). */ + blitTo(target: Uint8ClampedArray, targetWidth: number, x: number, y: number): void { + for (let j = 0; j < this.height; j += 1) { + const from = j * this.width * 4 + target.set(this.rgba.subarray(from, from + this.width * 4), ((y + j) * targetWidth + x) * 4) + } + } +} diff --git a/packages/renderer/src/sprites/index.ts b/packages/renderer/src/sprites/index.ts new file mode 100644 index 0000000..1dbca2e --- /dev/null +++ b/packages/renderer/src/sprites/index.ts @@ -0,0 +1,4 @@ +export * from './atlas' +export { PixelCanvas, shade, tint, type Rgb } from './canvas' +export { ROAD_PRESENT, roadMaskFromRoutes } from './roads' +export { UnitInterpolator, type UnitFrame, type UnitInterpolatorOptions } from './UnitInterpolator' diff --git a/packages/renderer/src/sprites/resources.ts b/packages/renderer/src/sprites/resources.ts new file mode 100644 index 0000000..516337d --- /dev/null +++ b/packages/renderer/src/sprites/resources.ts @@ -0,0 +1,409 @@ +/** + * @module sprites/resources + * @description One picture per resource and state, drawn in code. A resource has three states (see + * `resourceSpriteState`): full, low and empty, and each one is drawn so that a deposit visibly runs + * down: a tree becomes a sapling and then a stump, a field is cut to stubble, a herd thins out. + */ +import { ResourceType } from '@sovereign/contracts' +import { PixelCanvas, shade, tint, type Rgb } from './canvas' +import type { ResourceSpriteState } from './atlas' + +const OUTLINE: Rgb = [28, 22, 18] +const WOOD: Rgb = [112, 78, 46] +const SOIL: Rgb = [96, 68, 42] +const LEAF: Rgb = [58, 124, 54] +const WATER: Rgb = [150, 198, 238] +const WHITE: Rgb = [244, 244, 236] +const ROCK: Rgb = [128, 124, 118] + +type Draw = (c: PixelCanvas, color: Rgb, state: ResourceSpriteState) => void + +const pick = (state: ResourceSpriteState, full: T, low: T, empty: T): T => + state === 0 ? full : state === 1 ? low : empty + +function ripples(c: PixelCanvas, fewer = false): void { + c.line(2, 6, 5, 6, WATER) + c.line(10, 3, 13, 3, WATER) + c.line(3, 13, 7, 13, WATER) + if (!fewer) c.line(9, 10, 13, 10, WATER) +} + +const timber: Draw = (c, color, state) => { + if (state === 2) { + c.fillRect(6, 9, 4, 4, WOOD) + c.fillRect(6, 9, 4, 1, tint(WOOD, 0.45)) // the cut top + c.fillRect(9, 10, 1, 3, shade(WOOD, 0.75)) + c.set(5, 13, LEAF) // a shoot already + return + } + const full = state === 0 + c.fillRect(7, full ? 9 : 10, 2, full ? 5 : 4, WOOD) + if (full) { + c.ellipse(8, 6, 5.5, 5, color) + c.ellipse(6, 4.5, 2, 1.5, shade(color, 1.35)) + } else { + c.ellipse(8, 8, 3, 2.5, color) + } +} + +const stone: Draw = (c, color, state) => { + if (state === 0) { + c.ellipse(5, 10, 4, 3, color) + c.ellipse(11, 9, 4, 4, color) + c.ellipse(8, 5, 3, 3, shade(color, 1.08)) + } else if (state === 1) { + c.ellipse(8, 10, 4, 3, color) + } else { + c.set(6, 11, color) + c.set(7, 11, shade(color, 0.8)) + c.set(10, 12, color) + } +} + +/** Metals and gems: a rocky outcrop with flecks of the resource's colour in it. */ +const ore = + (base: Rgb): Draw => + (c, color, state) => { + if (state === 0) { + c.ellipse(8, 9, 6, 5, base) + const specks: Array<[number, number]> = [ + [5, 8], + [8, 6], + [11, 9], + [7, 11], + [10, 12], + [6, 10] + ] + specks.forEach(([x, y], i) => c.set(x, y, i === 1 ? tint(color, 0.45) : color)) + } else if (state === 1) { + c.ellipse(8, 10, 4, 3, base) + c.set(7, 9, color) + c.set(10, 10, color) + c.set(8, 12, tint(color, 0.45)) + } else { + c.ellipse(8, 11, 3, 2, shade(base, 0.9)) + } + } + +const grain: Draw = (c, color, state) => { + c.fillRect(2, 13, 12, 2, SOIL) + if (state === 2) { + c.line(3, 13, 12, 13, shade(SOIL, 1.3)) + return + } + const top = pick(state, 4, 9, 13) + for (const x of [3, 6, 9, 12]) { + c.fillRect(x, top, 1, 13 - top, [150, 156, 56]) + if (state === 0) { + c.fillRect(x, top - 1, 1, 3, color) + c.set(x + 1, top, shade(color, 0.8)) + } else { + c.set(x, top, color) + } + } +} + +function fish(c: PixelCanvas, cx: number, cy: number, color: Rgb): void { + c.ellipse(cx, cy, 3, 1.5, color) + c.set(cx - 4, cy - 1, shade(color, 0.8)) + c.set(cx - 4, cy + 1, shade(color, 0.8)) + c.set(cx + 2, cy, [20, 20, 24]) +} + +const fishery: Draw = (c, color, state) => { + ripples(c, state !== 2) + if (state === 0) { + fish(c, 6, 4, color) + fish(c, 10, 8, color) + fish(c, 6, 12, color) + } else if (state === 1) { + fish(c, 8, 8, color) + } +} + +function animal(c: PixelCanvas, cx: number, cy: number, color: Rgb): void { + c.ellipse(cx, cy, 3, 2, color) + c.ellipse(cx + 3, cy - 1, 1.5, 1.5, shade(color, 1.1)) + c.set(cx + 3, cy - 3, shade(color, 0.7)) // an ear + c.line(cx - 3, cy, cx - 5, cy - 2, shade(color, 0.8)) // tail +} + +const fur: Draw = (c, color, state) => { + if (state === 0) { + animal(c, 6, 5, color) + animal(c, 9, 11, color) + } else if (state === 1) { + animal(c, 8, 9, color) + } else { + for (const [x, y] of [ + [5, 9], + [7, 10], + [9, 9], + [11, 10] + ] as const) + c.set(x, y, shade(color, 0.6)) + } +} + +function tuft(c: PixelCanvas, x: number, y: number, color: Rgb): void { + c.set(x, y, color) + c.set(x - 1, y - 1, color) + c.set(x + 1, y - 1, color) +} + +function sheep(c: PixelCanvas, cx: number, cy: number): void { + c.ellipse(cx, cy, 3, 2, WHITE) + c.fillRect(cx + 3, cy - 1, 2, 2, [60, 52, 48]) + c.set(cx - 2, cy + 3, [60, 52, 48]) + c.set(cx + 1, cy + 3, [60, 52, 48]) +} + +const pasture: Draw = (c, color, state) => { + for (const [x, y] of [ + [3, 13], + [13, 4], + [12, 13], + [3, 3] + ] as const) + tuft(c, x, y, color) + if (state === 0) { + sheep(c, 5, 6) + sheep(c, 10, 11) + } else if (state === 1) { + sheep(c, 8, 8) + } +} + +function horse(c: PixelCanvas, cx: number, cy: number, color: Rgb): void { + c.ellipse(cx, cy, 3.5, 1.8, color) + c.fillRect(cx + 2, cy - 3, 2, 3, shade(color, 1.1)) // neck + c.fillRect(cx + 3, cy - 4, 3, 2, shade(color, 1.1)) // head + for (const dx of [-3, -1, 1, 3]) c.fillRect(cx + dx, cy + 2, 1, 2, shade(color, 0.65)) // legs + c.line(cx - 4, cy - 1, cx - 5, cy + 2, shade(color, 0.55)) // tail +} + +const horses: Draw = (c, color, state) => { + if (state === 0) { + horse(c, 6, 5, color) + horse(c, 7, 12, color) + } else if (state === 1) { + horse(c, 7, 9, color) + } else { + for (const [x, y] of [ + [4, 10], + [7, 11], + [10, 10], + [12, 12] + ] as const) { + c.set(x, y, shade(SOIL, 0.8)) + c.set(x + 1, y, shade(SOIL, 0.8)) + } + } +} + +const cotton: Draw = (c, color, state) => { + if (state === 2) { + c.line(5, 13, 6, 8, WOOD) + c.line(8, 13, 8, 7, WOOD) + c.line(11, 13, 10, 8, WOOD) + return + } + c.ellipse(8, 10, state === 0 ? 5.5 : 4, state === 0 ? 3.5 : 2.5, LEAF) + const puffs: Array<[number, number]> = [ + [5, 8], + [8, 6], + [11, 8], + [7, 10], + [10, 11] + ] + for (const [x, y] of puffs.slice(0, state === 0 ? 5 : 2)) c.fillRect(x, y, 2, 2, color) +} + +const spices: Draw = (c, color, state) => { + const plants: Array<[number, number]> = + state === 0 + ? [ + [4, 8], + [8, 9], + [12, 8] + ] + : state === 1 + ? [[8, 5]] + : [ + [5, 2], + [11, 2] + ] + for (const [x, h] of plants) { + c.line(x, 13, x, 13 - h, state === 2 ? WOOD : LEAF) + if (state !== 2) { + c.set(x - 1, 13 - h + 3, LEAF) + c.set(x + 1, 13 - h + 4, LEAF) + c.fillRect(x, 13 - h - 1, 2, 2, color) + } + } + c.fillRect(2, 14, 12, 1, SOIL) +} + +const wine: Draw = (c, color, state) => { + c.fillRect(3, 4, 1, 10, WOOD) + c.fillRect(12, 4, 1, 10, WOOD) + c.line(3, 5, 12, 5, shade(WOOD, 0.8)) + if (state === 2) { + c.line(4, 6, 11, 8, shade(WOOD, 0.7)) + return + } + c.ellipse(6, 7, 2.5, 2.5, LEAF) + c.ellipse(10, 7, 2.5, 2.5, LEAF) + const grapes: Array<[number, number]> = [ + [5, 10], + [6, 11], + [9, 10], + [10, 11], + [8, 12] + ] + for (const [x, y] of grapes.slice(0, state === 0 ? 5 : 2)) c.set(x, y, color) +} + +const tea: Draw = (c, color, state) => { + c.fillRect(2, 13, 12, 2, SOIL) + if (state === 2) { + c.line(4, 12, 5, 10, WOOD) + c.line(11, 12, 10, 10, WOOD) + return + } + const mounds: Array<[number, number]> = + state === 0 + ? [ + [5, 10], + [11, 10], + [8, 6] + ] + : [[8, 10]] + for (const [x, y] of mounds) { + c.ellipse(x, y, 3, 3, color) + c.set(x - 1, y - 2, tint(color, 0.5)) + c.set(x + 1, y - 1, tint(color, 0.5)) + } +} + +const ivory: Draw = (c, color, state) => { + const tusk = (x: number, dir: 1 | -1): void => { + c.line(x, 13, x + dir, 7, color) + c.line(x + dir, 7, x + dir * 3, 3, color) + c.line(x + 1, 13, x + 1 + dir, 7, shade(color, 0.8)) + } + if (state === 0) { + tusk(5, 1) + tusk(10, -1) + } else if (state === 1) { + tusk(6, 1) + } else { + c.set(6, 12, color) + c.set(7, 12, shade(color, 0.8)) + c.set(10, 13, color) + } +} + +const oil: Draw = (c, color, state) => { + const pool: Rgb = shade(color, 0.7) + c.ellipse(8, 12, pick(state, 6, 4, 3), pick(state, 3, 2, 1.5), pool) + if (state === 2) return + const top = pick(state, 2, 5, 0) + c.line(8, top, 5, 10, [96, 96, 104]) + c.line(8, top, 11, 10, [96, 96, 104]) + c.line(6, 8, 10, 8, [96, 96, 104]) + c.set(8, top, [200, 60, 50]) +} + +const salt: Draw = (c, color, state) => { + const pile = (cx: number, base: number, h: number): void => { + for (let j = 0; j < h; j += 1) { + const half = h - 1 - j + for (let x = cx - half; x <= cx + half; x += 1) + c.set(x, base - j, x > cx ? shade(color, 0.78) : color) + } + } + if (state === 0) { + pile(4, 13, 4) + pile(11, 13, 5) + pile(8, 8, 3) + } else if (state === 1) { + pile(8, 12, 4) + } else { + for (const [x, y] of [ + [5, 12], + [9, 13], + [11, 11] + ] as const) + c.set(x, y, color) + } +} + +function shell(c: PixelCanvas, cx: number, cy: number, color: Rgb): void { + c.ellipse(cx, cy, 3, 2.5, color) + c.set(cx - 1, cy, shade(color, 0.7)) + c.set(cx + 1, cy, shade(color, 0.7)) + c.set(cx, cy - 1, WHITE) +} + +const pearls: Draw = (c, color, state) => { + ripples(c, state !== 2) + if (state === 0) { + shell(c, 5, 6, color) + shell(c, 10, 11, color) + } else if (state === 1) { + shell(c, 8, 9, color) + } +} + +const whales: Draw = (c, color, state) => { + ripples(c, state !== 2) + if (state === 2) return + const small = state === 1 + c.ellipse(9, 10, small ? 4 : 5.5, small ? 2 : 3, color) + if (!small) { + c.line(3, 9, 1, 6, shade(color, 0.8)) // tail flukes + c.line(3, 9, 1, 12, shade(color, 0.8)) + c.line(11, 7, 11, 3, WATER) // spout + c.set(10, 2, WATER) + c.set(12, 2, WATER) + } +} + +const DRAWERS: Readonly> = { + [ResourceType.Timber]: timber, + [ResourceType.Stone]: stone, + [ResourceType.Iron]: ore(ROCK), + [ResourceType.Gold]: ore(ROCK), + [ResourceType.Grain]: grain, + [ResourceType.Fish]: fishery, + [ResourceType.Fur]: fur, + [ResourceType.Pasture]: pasture, + [ResourceType.Horses]: horses, + [ResourceType.Cotton]: cotton, + [ResourceType.Spices]: spices, + [ResourceType.Wine]: wine, + [ResourceType.Tea]: tea, + [ResourceType.Ivory]: ivory, + [ResourceType.Copper]: ore(shade(ROCK, 0.95)), + [ResourceType.Coal]: ore([62, 62, 68]), + [ResourceType.Oil]: oil, + [ResourceType.Silver]: ore(shade(ROCK, 1.1)), + [ResourceType.Salt]: salt, + [ResourceType.Gems]: ore(shade(ROCK, 0.85)), + [ResourceType.Pearls]: pearls, + [ResourceType.Whales]: whales +} + +/** Draw resource `type` in `state` on a clear canvas, with its outline. */ +export function drawResource( + c: PixelCanvas, + type: number, + color: Rgb, + state: ResourceSpriteState +): void { + const draw = DRAWERS[type] + if (draw === undefined) throw new RangeError(`no art for resource ${type}`) + draw(c, color, state) + c.outline(OUTLINE) +} diff --git a/packages/renderer/src/sprites/roads.ts b/packages/renderer/src/sprites/roads.ts new file mode 100644 index 0000000..4b9338d --- /dev/null +++ b/packages/renderer/src/sprites/roads.ts @@ -0,0 +1,96 @@ +/** + * @module sprites/roads + * @description Roads for the sprite layer, from the route network: one byte per tile, 0 for no road, else + * `16 | mask` where the mask says which of the four sides join a neighbouring road tile (ROAD_N, E, S, W), so + * that each tile can be drawn with the piece that connects to its neighbours. + */ +import type { StrategicRoute } from '@sovereign/contracts' +import { ROAD_E, ROAD_N, ROAD_S, ROAD_W } from './atlas' + +/** Set in a road byte when the tile has a road at all (a lone tile has mask 0 but is still a road). */ +export const ROAD_PRESENT = 16 + +/** + * Walk the tiles from (x0, y0) to (x1, y1), calling `visit` for each. Steps are always along a side, never + * across a corner (a diagonal becomes two steps), so consecutive tiles are neighbours and a road stays joined. + */ +function walk( + x0: number, + y0: number, + x1: number, + y1: number, + visit: (x: number, y: number) => void +): void { + const dx = Math.abs(x1 - x0) + const dy = -Math.abs(y1 - y0) + const sx = x0 < x1 ? 1 : -1 + const sy = y0 < y1 ? 1 : -1 + let err = dx + dy + let x = x0 + let y = y0 + visit(x, y) + while (x !== x1 || y !== y1) { + const e2 = 2 * err + if (e2 >= dy) { + err += dy + x += sx + visit(x, y) + } + if (e2 <= dx) { + err += dx + y += sy + visit(x, y) + } + } +} + +/** Mark the routes that carry traffic on a `width x height` grid of road bytes. */ +export function roadMaskFromRoutes( + routes: readonly StrategicRoute[], + width: number, + height: number +): Uint8Array { + const mask = new Uint8Array(width * height) + const on = (x: number, y: number): boolean => x >= 0 && y >= 0 && x < width && y < height + for (const route of routes) { + if (!(route.traffic > 0)) continue + const path = route.path + let px = Number.NaN + let py = Number.NaN + const visit = (x: number, y: number): void => { + if (x === px && y === py) return + if (on(x, y)) mask[y * width + x] = (mask[y * width + x] as number) | ROAD_PRESENT + if (on(px, py) && on(x, y)) { + // the step from the previous tile joins the side of each facing the other + const a = py * width + px + const b = y * width + x + if (x > px) { + mask[a] = (mask[a] as number) | ROAD_E + mask[b] = (mask[b] as number) | ROAD_W + } else if (x < px) { + mask[a] = (mask[a] as number) | ROAD_W + mask[b] = (mask[b] as number) | ROAD_E + } else if (y > py) { + mask[a] = (mask[a] as number) | ROAD_S + mask[b] = (mask[b] as number) | ROAD_N + } else { + mask[a] = (mask[a] as number) | ROAD_N + mask[b] = (mask[b] as number) | ROAD_S + } + } + px = x + py = y + } + if (path.length === 2) visit(path[0] as number, path[1] as number) + for (let k = 0; k + 3 < path.length; k += 2) { + walk( + path[k] as number, + path[k + 1] as number, + path[k + 2] as number, + path[k + 3] as number, + visit + ) + } + } + return mask +} diff --git a/packages/renderer/src/view.ts b/packages/renderer/src/view.ts index 4fa284f..b396f12 100644 --- a/packages/renderer/src/view.ts +++ b/packages/renderer/src/view.ts @@ -59,3 +59,47 @@ export function tileAtScreen( export function clampedViewport(width: number, height: number): { width: number; height: number } { return { width: Math.max(1, Math.floor(width)), height: Math.max(1, Math.floor(height)) } } + +/** A screen position's tile is at least this many pixels wide before sprites are drawn instead of overlays. */ +export const SPRITE_MIN_TILE_PIXELS = 10 + +/** Whether the camera is close enough to draw sprites: a tile (`tileSize` world pixels) is big enough on screen. */ +export function spritesShown(zoom: number, tileSize: number): boolean { + return zoom * tileSize >= SPRITE_MIN_TILE_PIXELS +} + +/** A block of tiles: `x0..x1` and `y0..y1`, from the first to one past the last. */ +export interface TileRect { + x0: number + y0: number + x1: number + y1: number +} + +/** + * The tiles the camera can see, plus one tile of margin so a sprite on the edge is not cut off, clamped to + * the map. Sprites are made only for these, so the cost of a frame follows the screen, not the map. + */ +export function visibleTileRect( + camera: Camera, + viewportWidth: number, + viewportHeight: number, + map: MapSize +): TileRect { + const topLeft = camera.screenToWorld(0, 0, viewportWidth, viewportHeight) + const bottomRight = camera.screenToWorld( + viewportWidth, + viewportHeight, + viewportWidth, + viewportHeight + ) + const toTileX = (wx: number): number => (wx + (map.width * map.tileSize) / 2) / map.tileSize + const toTileY = (wy: number): number => (wy + (map.height * map.tileSize) / 2) / map.tileSize + const clamp = (v: number, hi: number): number => Math.min(hi, Math.max(0, v)) + return { + x0: clamp(Math.floor(toTileX(topLeft.x)) - 1, map.width), + y0: clamp(Math.floor(toTileY(topLeft.y)) - 1, map.height), + x1: clamp(Math.ceil(toTileX(bottomRight.x)) + 1, map.width), + y1: clamp(Math.ceil(toTileY(bottomRight.y)) + 1, map.height) + } +} diff --git a/packages/renderer/tests/pixel-canvas.test.ts b/packages/renderer/tests/pixel-canvas.test.ts new file mode 100644 index 0000000..ae03c18 --- /dev/null +++ b/packages/renderer/tests/pixel-canvas.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from 'vitest' +import { PixelCanvas, shade, tint } from '../src/sprites' + +describe('PixelCanvas', () => { + it('ignores a pixel off the canvas rather than wrapping it onto another row', () => { + const c = new PixelCanvas(4, 4) + c.set(-1, 1, [9, 9, 9]) + c.set(4, 1, [9, 9, 9]) + c.set(1, -1, [9, 9, 9]) + c.set(1, 4, [9, 9, 9]) + expect(c.count()).toBe(0) + expect(c.solid(-1, 0)).toBe(false) + expect(c.solid(4, 0)).toBe(false) + }) + it('paints an opaque pixel and reports it solid', () => { + const c = new PixelCanvas(4, 4) + c.set(2, 1, [10, 20, 30]) + expect(c.solid(2, 1)).toBe(true) + expect(Array.from(c.rgba.subarray((1 * 4 + 2) * 4, (1 * 4 + 2) * 4 + 4))).toEqual([ + 10, 20, 30, 255 + ]) + expect(c.count()).toBe(1) + }) + it('fills a rectangle, clipping at the edge', () => { + const c = new PixelCanvas(4, 4) + c.fillRect(2, 2, 5, 5, [1, 1, 1]) + expect(c.count()).toBe(4) + }) + it('draws a line including both ends, in every direction', () => { + const c = new PixelCanvas(8, 8) + c.line(1, 1, 6, 4, [1, 1, 1]) + expect(c.solid(1, 1) && c.solid(6, 4)).toBe(true) + const d = new PixelCanvas(8, 8) + d.line(6, 4, 1, 1, [1, 1, 1]) + expect(d.rgba).toEqual(c.rgba) + const v = new PixelCanvas(8, 8) + v.line(3, 6, 3, 1, [1, 1, 1]) + expect(v.count()).toBe(6) + }) + it('draws an ellipse with its light side up and left and its shadow down and right', () => { + const c = new PixelCanvas(16, 16) + c.ellipse(8, 8, 5, 5, [100, 100, 100]) + const at = (x: number, y: number): number => c.rgba[(y * 16 + x) * 4] as number + expect(at(8, 8)).toBe(100) + expect(at(6, 5)).toBeGreaterThan(100) + expect(at(10, 11)).toBeLessThan(100) + expect(c.solid(8, 2)).toBe(false) // outside the radius + }) + it('outlines the outside of a shape and leaves the shape alone', () => { + const c = new PixelCanvas(6, 6) + c.set(2, 2, [200, 200, 200]) + c.outline([0, 0, 0]) + expect(c.count()).toBe(5) // the pixel and its four neighbours, not the diagonals + expect(c.rgba[(2 * 6 + 2) * 4]).toBe(200) + expect(c.solid(3, 3)).toBe(false) + }) + it('copies itself into a larger buffer at an offset', () => { + const c = new PixelCanvas(2, 2) + c.fillRect(0, 0, 2, 2, [7, 8, 9]) + const target = new Uint8ClampedArray(6 * 4 * 4) + c.blitTo(target, 6, 3, 1) + expect(Array.from(target.subarray((1 * 6 + 3) * 4, (1 * 6 + 3) * 4 + 4))).toEqual([ + 7, 8, 9, 255 + ]) + expect(target[(1 * 6 + 2) * 4 + 3]).toBe(0) + expect(target[(2 * 6 + 4) * 4 + 3]).toBe(255) + }) +}) + +describe('shade and tint', () => { + it('scale a colour and clamp it to a byte', () => { + expect(shade([100, 200, 50], 0.5)).toEqual([50, 100, 25]) + expect(shade([200, 200, 200], 2)).toEqual([255, 255, 255]) + }) + it('move a colour towards white', () => { + expect(tint([0, 100, 200], 0.5)).toEqual([128, 178, 228]) + expect(tint([10, 10, 10], 0)).toEqual([10, 10, 10]) + }) +}) diff --git a/packages/renderer/tests/sprite-view.test.ts b/packages/renderer/tests/sprite-view.test.ts new file mode 100644 index 0000000..73a3ccb --- /dev/null +++ b/packages/renderer/tests/sprite-view.test.ts @@ -0,0 +1,240 @@ +import { describe, expect, it } from 'vitest' +import type { StrategicRoute, UnitSnapshot } from '@sovereign/contracts' +import { Camera } from '../src/Camera' +import { + ROAD_E, + ROAD_N, + ROAD_S, + ROAD_W, + SPRITE_MIN_TILE_PIXELS, + UnitInterpolator, + roadMaskFromRoutes, + spritesShown, + visibleTileRect +} from '../src' + +const map = { width: 100, height: 80, tileSize: 4 } + +describe('spritesShown: sprites are for when a tile is big enough on screen to draw one', () => { + it('turns on at the threshold and not below it', () => { + const at = (zoom: number): boolean => spritesShown(zoom, map.tileSize) + expect(at(SPRITE_MIN_TILE_PIXELS / 4)).toBe(true) + expect(at(SPRITE_MIN_TILE_PIXELS / 4 - 0.01)).toBe(false) + expect(at(10)).toBe(true) + expect(at(0.2)).toBe(false) + }) +}) + +describe('visibleTileRect: which tiles the camera can see', () => { + it('is the tiles under the viewport, with one tile of margin', () => { + // zoom 2: one tile is 8 screen pixels; an 80 x 40 viewport shows 10 x 5 tiles, centred on the map middle + const camera = new Camera({ x: 0, y: 0, zoom: 2 }) + const r = visibleTileRect(camera, 80, 40, map) + // the map centre is tile (50, 40); the view covers x 45..55 and y 37.5..42.5 + expect(r).toEqual({ x0: 44, y0: 36, x1: 56, y1: 44 }) + }) + it('follows the camera', () => { + const camera = new Camera({ x: 40, y: -20, zoom: 2 }) // 10 tiles right, 5 tiles up + const r = visibleTileRect(camera, 80, 40, map) + expect(r.x0).toBe(54) + expect(r.y0).toBe(31) + }) + it('is clamped to the map', () => { + const camera = new Camera({ x: -10000, y: 10000, zoom: 2 }) + const r = visibleTileRect(camera, 80, 40, map) + expect(r.x1).toBeLessThanOrEqual(0) + expect(r.y0).toBeGreaterThanOrEqual(map.height) + const all = visibleTileRect(new Camera({ zoom: 0.2 }), 8000, 8000, map) + expect(all).toEqual({ x0: 0, y0: 0, x1: map.width, y1: map.height }) + }) + it('is never negative in size', () => { + const r = visibleTileRect(new Camera({ x: 5000, y: 0, zoom: 2 }), 80, 40, map) + expect(r.x1).toBeGreaterThanOrEqual(r.x0) + expect(r.y1).toBeGreaterThanOrEqual(r.y0) + }) +}) + +describe('roadMaskFromRoutes', () => { + const route = (path: number[], traffic = 1): StrategicRoute => ({ + from: 0, + to: 1, + cost: 1, + traffic, + path + }) + const at = (m: Uint8Array, x: number, y: number): number => m[y * 10 + x] as number + + it('marks every tile of a route and the sides it joins to its neighbours', () => { + const m = roadMaskFromRoutes([route([2, 3, 5, 3])], 10, 10) + expect(at(m, 2, 3)).toBe(ROAD_E | 16) + expect(at(m, 3, 3)).toBe(ROAD_E | ROAD_W | 16) + expect(at(m, 4, 3)).toBe(ROAD_E | ROAD_W | 16) + expect(at(m, 5, 3)).toBe(ROAD_W | 16) + expect(at(m, 6, 3)).toBe(0) + expect(at(m, 2, 2)).toBe(0) + }) + it('joins vertical runs, and the road is one tile where routes cross', () => { + const m = roadMaskFromRoutes([route([4, 1, 4, 5]), route([2, 3, 6, 3])], 10, 10) + expect(at(m, 4, 1)).toBe(ROAD_S | 16) + expect(at(m, 4, 3)).toBe(ROAD_N | ROAD_S | ROAD_E | ROAD_W | 16) + expect(at(m, 4, 5)).toBe(ROAD_N | 16) + }) + it('follows a polyline through each of its points', () => { + const m = roadMaskFromRoutes([route([1, 1, 3, 1, 3, 4])], 10, 10) + expect(at(m, 3, 1)).toBe(ROAD_W | ROAD_S | 16) + expect(at(m, 3, 4)).toBe(ROAD_N | 16) + }) + it('joins a diagonal step through a corner tile so the road stays connected', () => { + const m = roadMaskFromRoutes([route([1, 1, 3, 3])], 10, 10) + // every marked tile touches the next one on a side + let marked = 0 + for (let i = 0; i < 100; i += 1) if ((m[i] as number) !== 0) marked += 1 + expect(marked).toBeGreaterThanOrEqual(5) + expect(at(m, 1, 1) & (ROAD_E | ROAD_S)).not.toBe(0) + }) + it('skips a route nobody uses and ignores tiles off the map', () => { + expect(roadMaskFromRoutes([route([2, 3, 5, 3], 0)], 10, 10).every((v) => v === 0)).toBe(true) + const m = roadMaskFromRoutes([route([8, 5, 14, 5])], 10, 10) + expect(at(m, 9, 5)).toBe(ROAD_W | 16) + }) + it('handles a route that is a single point', () => { + const m = roadMaskFromRoutes([route([4, 4])], 10, 10) + expect(at(m, 4, 4)).toBe(16) + }) +}) + +const snap = (tick: number, rows: Array<[number, number, number]>): UnitSnapshot => ({ + tick, + count: rows.length, + id: Uint32Array.from(rows.map((r) => r[0])), + kind: Uint8Array.from(rows.map(() => 1)), + owner: Uint8Array.from(rows.map((r) => r[0] % 3)), + x: Float32Array.from(rows.map((r) => r[1])), + y: Float32Array.from(rows.map((r) => r[2])) +}) + +describe('UnitInterpolator', () => { + it('shows a unit where its first snapshot says', () => { + const u = new UnitInterpolator() + u.push(snap(1, [[0, 10, 20]]), 1000) + const f = u.sample(1000) + expect(f.count).toBe(1) + expect([f.x[0], f.y[0]]).toEqual([10, 20]) + }) + it('glides from where a unit was shown to where the new snapshot puts it', () => { + const u = new UnitInterpolator({ minMs: 100, maxMs: 100 }) + u.push(snap(1, [[0, 10, 20]]), 1000) + u.push(snap(2, [[0, 14, 22]]), 1100) + expect(u.sample(1100).x[0]).toBe(10) + expect(u.sample(1150).x[0]).toBe(12) + expect(u.sample(1150).y[0]).toBe(21) + expect(u.sample(1200).x[0]).toBe(14) + expect(u.sample(5000).x[0]).toBe(14) // it waits there for the next snapshot + expect(u.sample(900).x[0]).toBe(10) // never before the start + }) + it('starts from the picture on screen, not from the last snapshot, when one arrives mid-glide', () => { + const u = new UnitInterpolator({ minMs: 100, maxMs: 100 }) + u.push(snap(1, [[0, 0, 0]]), 1000) + u.push(snap(2, [[0, 10, 0]]), 1100) + u.push(snap(3, [[0, 10, 8]]), 1150) // arrives halfway: it is on screen at x = 5 + expect(u.sample(1150).x[0]).toBe(5) + expect(u.sample(1150).y[0]).toBe(0) + expect(u.sample(1250).x[0]).toBe(10) + expect(u.sample(1250).y[0]).toBe(8) + }) + it('times a glide by the gap between snapshots, within its limits', () => { + const u = new UnitInterpolator({ minMs: 50, maxMs: 400 }) + u.push(snap(1, [[0, 0, 0]]), 1000) + u.push(snap(2, [[0, 10, 0]]), 1200) // 200 ms since the last + expect(u.sample(1300).x[0]).toBe(5) + u.push(snap(3, [[0, 20, 0]]), 1210) // 10 ms: clamped up to 50 + const here = u.sample(1210).x[0] as number + expect(u.sample(1235).x[0]).toBeCloseTo(here + (20 - here) / 2, 4) + u.push(snap(4, [[0, 30, 0]]), 9210) // a long pause: clamped down to 400 + expect(u.sample(9410).x[0]).toBe(25) + }) + it('puts a new unit straight at its place and drops a unit that is gone', () => { + const u = new UnitInterpolator({ minMs: 100, maxMs: 100 }) + u.push( + snap(1, [ + [0, 0, 0], + [2, 5, 5] + ]), + 1000 + ) + u.push( + snap(2, [ + [0, 10, 0], + [1, 7, 7], + [3, 9, 9] + ]), + 1100 + ) + const f = u.sample(1150) + expect(f.count).toBe(3) + expect(Array.from(f.id)).toEqual([0, 1, 3]) + expect(f.x[0]).toBe(5) + expect(f.x[1]).toBe(7) // new: no glide + expect(f.x[2]).toBe(9) + }) + it('jumps rather than glides when a unit is further than the jump limit (a long run of ticks)', () => { + const u = new UnitInterpolator({ minMs: 100, maxMs: 100, jumpTiles: 6 }) + u.push( + snap(1, [ + [0, 0, 0], + [1, 0, 0] + ]), + 1000 + ) + u.push( + snap(2, [ + [0, 50, 0], + [1, 5, 0] + ]), + 1100 + ) + const f = u.sample(1100) + expect(f.x[0]).toBe(50) + expect(f.x[1]).toBe(0) // within the limit: still glides + }) + it('glides a unit that moved exactly the jump limit, and jumps one that moved just over it', () => { + const u = new UnitInterpolator({ minMs: 100, maxMs: 100, jumpTiles: 6 }) + u.push( + snap(1, [ + [0, 0, 0], + [1, 0, 0] + ]), + 1000 + ) + u.push( + snap(2, [ + [0, 6, 0], + [1, 6.5, 0] + ]), + 1100 + ) + const f = u.sample(1100) + expect(f.x[0]).toBe(0) + expect(f.x[1]).toBe(6.5) + }) + it('keeps ids, kinds and owners of the latest snapshot', () => { + const u = new UnitInterpolator() + u.push( + snap(1, [ + [4, 1, 1], + [5, 2, 2] + ]), + 0 + ) + const f = u.sample(0) + expect(Array.from(f.id)).toEqual([4, 5]) + expect(Array.from(f.owner)).toEqual([1, 2]) + expect(Array.from(f.kind)).toEqual([1, 1]) + }) + it('is empty before the first snapshot, and after an empty one', () => { + const u = new UnitInterpolator() + expect(u.sample(0).count).toBe(0) + u.push(snap(1, []), 0) + expect(u.sample(10).count).toBe(0) + }) +}) diff --git a/packages/renderer/tests/sprites.test.ts b/packages/renderer/tests/sprites.test.ts new file mode 100644 index 0000000..b62a042 --- /dev/null +++ b/packages/renderer/tests/sprites.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it } from 'vitest' +import { RESOURCE_CATALOG } from '@sovereign/contracts' +import { + RESOURCE_SPRITE_STATES, + ROAD_E, + ROAD_N, + ROAD_S, + ROAD_W, + SPRITE_SIZE, + buildSpriteAtlas, + resourceFrameName, + resourceSpriteState, + roadFrameName, + type SpriteAtlas, + type SpriteFrame +} from '../src/sprites' + +const atlas = buildSpriteAtlas() + +function pixels(a: SpriteAtlas, frame: SpriteFrame): number[][] { + const out: number[][] = [] + for (let y = 0; y < frame.h; y += 1) { + for (let x = 0; x < frame.w; x += 1) { + const p = ((frame.y + y) * a.width + frame.x + x) * 4 + out.push([ + a.rgba[p] as number, + a.rgba[p + 1] as number, + a.rgba[p + 2] as number, + a.rgba[p + 3] as number + ]) + } + } + return out +} +const frameOf = (name: string): SpriteFrame => { + const f = atlas.frames[name] + if (f === undefined) throw new Error(`no frame ${name}`) + return f +} +const opaque = (name: string): number => + pixels(atlas, frameOf(name)).filter((p) => p[3] === 255).length +const key = (name: string): string => JSON.stringify(pixels(atlas, frameOf(name))) + +describe('resourceSpriteState: how much is left decides what is drawn', () => { + it('is full at half the deposit or more, low while any is left, empty at zero', () => { + expect(resourceSpriteState(200, 200)).toBe(0) + expect(resourceSpriteState(100, 200)).toBe(0) + expect(resourceSpriteState(99, 200)).toBe(1) + expect(resourceSpriteState(1, 200)).toBe(1) + expect(resourceSpriteState(0, 200)).toBe(2) + }) + it('treats a slot with no richness as empty rather than dividing by zero', () => { + expect(resourceSpriteState(0, 0)).toBe(2) + expect(resourceSpriteState(5, 0)).toBe(2) + }) + it('names a frame by resource key and state', () => { + expect(resourceFrameName(1, 0)).toBe('resource.timber.full') + expect(resourceFrameName(22, 2)).toBe('resource.whales.empty') + expect(RESOURCE_SPRITE_STATES).toEqual(['full', 'low', 'empty']) + }) + it('refuses a resource that is not in the catalogue', () => { + expect(() => resourceFrameName(0, 0)).toThrow(RangeError) + expect(() => resourceFrameName(23, 0)).toThrow(RangeError) + }) +}) + +describe('the atlas', () => { + it('has a frame for every resource in every state, the villager, buildings and roads', () => { + for (const def of RESOURCE_CATALOG) { + for (let s = 0; s < 3; s += 1) + expect(atlas.frames[resourceFrameName(def.id, s as 0)]).toBeDefined() + } + for (const name of ['villager.0', 'villager.1', 'house', 'hall', 'banner']) { + expect(atlas.frames[name], name).toBeDefined() + } + for (let mask = 0; mask < 16; mask += 1) expect(atlas.frames[roadFrameName(mask)]).toBeDefined() + }) + it('keeps every frame square, inside the sheet, and clear of every other frame', () => { + const frames = Object.values(atlas.frames) + expect(frames.length).toBe(22 * 3 + 2 + 3 + 16) + const seen = new Set() + for (const f of frames) { + expect(f.w).toBe(SPRITE_SIZE) + expect(f.h).toBe(SPRITE_SIZE) + expect(f.x + f.w).toBeLessThanOrEqual(atlas.width) + expect(f.y + f.h).toBeLessThanOrEqual(atlas.height) + const cell = `${f.x},${f.y}` + expect(seen.has(cell)).toBe(false) + seen.add(cell) + } + expect(atlas.rgba.length).toBe(atlas.width * atlas.height * 4) + }) + it('is crisp pixel art: every pixel is fully opaque or fully clear', () => { + for (let p = 3; p < atlas.rgba.length; p += 4) expect([0, 255]).toContain(atlas.rgba[p]) + }) + it('is the same every time it is built (a pinned checksum, so art cannot drift unseen)', () => { + const again = buildSpriteAtlas() + expect(again.rgba).toEqual(atlas.rgba) + let h = 0x811c9dc5 + for (const b of atlas.rgba) h = Math.imul(h ^ b, 0x01000193) >>> 0 + expect(h.toString(16)).toBe('910827fd') + }) +}) + +describe('resource sprites', () => { + it('draw something for every resource in every state', () => { + for (const def of RESOURCE_CATALOG) { + for (const s of RESOURCE_SPRITE_STATES) + expect(opaque(`resource.${def.key}.${s}`)).toBeGreaterThan(0) + } + }) + it('look different in every state, so a drawn-down deposit visibly changes', () => { + for (const def of RESOURCE_CATALOG) { + const keys = RESOURCE_SPRITE_STATES.map((s) => key(`resource.${def.key}.${s}`)) + expect(new Set(keys).size, def.key).toBe(3) + } + }) + it('lose substance as they empty: full has more to see than empty', () => { + for (const def of RESOURCE_CATALOG) { + expect(opaque(`resource.${def.key}.full`), def.key).toBeGreaterThan( + opaque(`resource.${def.key}.empty`) + ) + } + }) + it('are all different from one another, so no two resources can be mistaken', () => { + const keys = new Set() + for (const def of RESOURCE_CATALOG) keys.add(key(`resource.${def.key}.full`)) + expect(keys.size).toBe(22) + }) +}) + +describe('the villager', () => { + it('is grey, so the renderer can tint it with its nation colour', () => { + for (const name of ['villager.0', 'villager.1', 'banner']) { + const px = pixels(atlas, frameOf(name)).filter((p) => p[3] === 255) + expect(px.length).toBeGreaterThan(0) + for (const p of px) { + expect(p[0]).toBe(p[1]) + expect(p[1]).toBe(p[2]) + } + } + }) + it('has two walking frames that differ', () => { + expect(key('villager.0')).not.toBe(key('villager.1')) + }) + it('stands inside its frame with room for an outline', () => { + const px = pixels(atlas, frameOf('villager.0')) + for (let i = 0; i < px.length; i += 1) { + const x = i % SPRITE_SIZE + const y = Math.floor(i / SPRITE_SIZE) + if (x === 0 || y === 0 || x === SPRITE_SIZE - 1 || y === SPRITE_SIZE - 1) { + expect((px[i] as number[])[3]).toBe(0) + } + } + }) +}) + +describe('roads', () => { + const mid = SPRITE_SIZE / 2 + const edge: Array<[number, number, number]> = [ + [ROAD_N, mid, 0], + [ROAD_E, SPRITE_SIZE - 1, mid], + [ROAD_S, mid, SPRITE_SIZE - 1], + [ROAD_W, 0, mid] + ] + it('reach exactly the sides named in their mask, so neighbours join up', () => { + for (let mask = 0; mask < 16; mask += 1) { + const px = pixels(atlas, frameOf(roadFrameName(mask))) + for (const [bit, x, y] of edge) { + // the road is two pixels wide, so check both pixels at the middle of that side + const cells = + bit === ROAD_N || bit === ROAD_S + ? [px[y * SPRITE_SIZE + x - 1], px[y * SPRITE_SIZE + x]] + : [px[(y - 1) * SPRITE_SIZE + x], px[y * SPRITE_SIZE + x]] + const reaches = cells.every((c) => (c as number[])[3] === 255) + expect(reaches, `mask ${mask} side ${bit}`).toBe((mask & bit) !== 0) + } + } + }) + it('all differ, and an isolated tile still shows a patch of trodden ground', () => { + const keys = new Set() + for (let mask = 0; mask < 16; mask += 1) keys.add(key(roadFrameName(mask))) + expect(keys.size).toBe(16) + expect(opaque(roadFrameName(0))).toBeGreaterThan(0) + }) + it('refuse a mask outside 0 to 15', () => { + expect(() => roadFrameName(16)).toThrow(RangeError) + expect(() => roadFrameName(-1)).toThrow(RangeError) + expect(() => roadFrameName(1.5)).toThrow(RangeError) + }) +}) + +describe('buildings', () => { + it('draw a house and a larger hall', () => { + expect(opaque('house')).toBeGreaterThan(0) + expect(opaque('hall')).toBeGreaterThan(opaque('house')) + }) +}) diff --git a/packages/simulation/src/entities/EntityStore.ts b/packages/simulation/src/entities/EntityStore.ts new file mode 100644 index 0000000..1bd8a59 --- /dev/null +++ b/packages/simulation/src/entities/EntityStore.ts @@ -0,0 +1,271 @@ +/** + * @module EntityStore + * @description Everything that lives and acts in the world is a row here: struct-of-arrays, one typed array per + * field, so thousands of units cost no per-object memory and a system sweeps plain numbers. + * + * Ids are row indices. **The lowest free id is always the next one handed out**, whatever order rows were freed + * in, so the ids a world allocates depend only on which rows are alive, never on the history that got it + * there: a world restored from a save allocates exactly as the original would have. Rows are visited in id + * order, always. A row is alive when its `kind` is not 0; a freed row is zeroed (its owner back to "none"). + * + * Only plain numbers live here. Anything derived (a route a unit is walking, the unit's position between two + * events) is rebuilt from these fields, so it never has to be saved. + */ +import { EntityKind, NO_OWNER } from '@sovereign/contracts' + +/** What a new row is given; everything but the kind and the tile defaults to 0 (and the owner to none). */ +export interface SpawnInput { + kind: number + /** The tile the entity is on, 0 to 65535 each way. */ + x: number + y: number + owner?: number + state?: number + /** The route-grid cell it calls home. */ + home?: number + /** The route-grid cell it is heading for. */ + target?: number + /** The tick it next needs attention. */ + wake?: number + /** The tick its current leg started and the tick it arrives. */ + legStart?: number + legEnd?: number +} + +const INITIAL_CAPACITY = 256 + +/** Every column of a store up to its high water mark, as plain numbers (what a save holds). */ +export interface EntityColumns { + highWater: number + kind: number[] + x: number[] + y: number[] + owner: number[] + state: number[] + home: number[] + target: number[] + wake: number[] + legStart: number[] + legEnd: number[] +} + +/** The columns, in the order they are saved and hashed. */ +export const COLUMN_NAMES = [ + 'kind', + 'x', + 'y', + 'owner', + 'state', + 'home', + 'target', + 'wake', + 'legStart', + 'legEnd' +] as const + +/** The columns and the range each value must be in (the width of the typed array that holds it). */ +const COLUMN_RANGES = { + kind: [0, 255], + x: [0, 65535], + y: [0, 65535], + owner: [0, 255], + state: [0, 255], + home: [-2147483648, 2147483647], + target: [-2147483648, 2147483647], + wake: [-2147483648, 2147483647], + legStart: [-2147483648, 2147483647], + legEnd: [-2147483648, 2147483647] +} as const + +export class EntityStore { + kind: Uint8Array + x: Uint16Array + y: Uint16Array + owner: Uint8Array + state: Uint8Array + home: Int32Array + target: Int32Array + wake: Int32Array + legStart: Int32Array + legEnd: Int32Array + + private alive_ = 0 + private highWater_ = 0 + /** No row below this id is free. */ + private firstFree = 0 + + constructor(capacity = INITIAL_CAPACITY) { + const n = Math.max(1, capacity) + this.kind = new Uint8Array(n) + this.x = new Uint16Array(n) + this.y = new Uint16Array(n) + this.owner = new Uint8Array(n).fill(NO_OWNER) + this.state = new Uint8Array(n) + this.home = new Int32Array(n) + this.target = new Int32Array(n) + this.wake = new Int32Array(n) + this.legStart = new Int32Array(n) + this.legEnd = new Int32Array(n) + } + + /** How many rows are alive. */ + get count(): number { + return this.alive_ + } + + /** One past the highest id ever handed out: rows from here on were never used. */ + get highWater(): number { + return this.highWater_ + } + + /** True if `id` is a row that is alive. */ + alive(id: number): boolean { + return ( + Number.isInteger(id) && id >= 0 && id < this.highWater_ && this.kind[id] !== EntityKind.None + ) + } + + /** Add an entity and return its id: the lowest that is free. */ + spawn(input: SpawnInput): number { + const { kind, x, y } = input + if (!Number.isInteger(kind) || kind <= 0 || kind > 255) { + throw new RangeError('an entity needs a kind from 1 to 255') + } + if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0 || x > 65535 || y > 65535) { + throw new RangeError('an entity must be on a tile from 0 to 65535 each way') + } + let id = this.firstFree + while (id < this.highWater_ && this.kind[id] !== EntityKind.None) id += 1 + if (id === this.highWater_) { + if (id === this.kind.length) this.grow() + this.highWater_ += 1 + } + this.kind[id] = kind + this.x[id] = x + this.y[id] = y + this.owner[id] = input.owner ?? NO_OWNER + this.state[id] = input.state ?? 0 + this.home[id] = input.home ?? 0 + this.target[id] = input.target ?? 0 + this.wake[id] = input.wake ?? 0 + this.legStart[id] = input.legStart ?? 0 + this.legEnd[id] = input.legEnd ?? 0 + this.alive_ += 1 + this.firstFree = id + 1 + return id + } + + /** Remove an entity: its row is zeroed and its id may be handed out again. */ + despawn(id: number): void { + if (!this.alive(id)) throw new RangeError(`there is no entity ${id} to remove`) + this.kind[id] = EntityKind.None + this.x[id] = 0 + this.y[id] = 0 + this.owner[id] = NO_OWNER + this.state[id] = 0 + this.home[id] = 0 + this.target[id] = 0 + this.wake[id] = 0 + this.legStart[id] = 0 + this.legEnd[id] = 0 + this.alive_ -= 1 + if (id < this.firstFree) this.firstFree = id + } + + /** Every column up to the high water mark, copied. */ + toColumns(): EntityColumns { + const n = this.highWater_ + return { + highWater: n, + kind: Array.from(this.kind.subarray(0, n)), + x: Array.from(this.x.subarray(0, n)), + y: Array.from(this.y.subarray(0, n)), + owner: Array.from(this.owner.subarray(0, n)), + state: Array.from(this.state.subarray(0, n)), + home: Array.from(this.home.subarray(0, n)), + target: Array.from(this.target.subarray(0, n)), + wake: Array.from(this.wake.subarray(0, n)), + legStart: Array.from(this.legStart.subarray(0, n)), + legEnd: Array.from(this.legEnd.subarray(0, n)) + } + } + + /** Rebuild a store from columns made by {@link toColumns}; the columns are copied and checked. */ + static fromColumns(columns: EntityColumns): EntityStore { + const n = columns.highWater + if (!Number.isInteger(n) || n < 0) + throw new RangeError('the high water mark must be a whole number of 0 or more') + for (const name of COLUMN_NAMES) { + const values = columns[name] + if (!Array.isArray(values) || values.length !== n) { + throw new RangeError(`the column ${name} must have ${n} values`) + } + const [lo, hi] = COLUMN_RANGES[name] + for (const v of values) { + if (!Number.isInteger(v) || v < lo || v > hi) { + throw new RangeError(`the column ${name} has the value ${v}, which does not fit`) + } + } + } + const store = new EntityStore(n) + let alive = 0 + for (let id = 0; id < n; id += 1) { + store.kind[id] = columns.kind[id] as number + store.x[id] = columns.x[id] as number + store.y[id] = columns.y[id] as number + store.owner[id] = columns.owner[id] as number + store.state[id] = columns.state[id] as number + store.home[id] = columns.home[id] as number + store.target[id] = columns.target[id] as number + store.wake[id] = columns.wake[id] as number + store.legStart[id] = columns.legStart[id] as number + store.legEnd[id] = columns.legEnd[id] as number + if (store.kind[id] === EntityKind.None) { + const zero = + store.x[id] === 0 && + store.y[id] === 0 && + store.owner[id] === NO_OWNER && + store.state[id] === 0 && + store.home[id] === 0 && + store.target[id] === 0 && + store.wake[id] === 0 && + store.legStart[id] === 0 && + store.legEnd[id] === 0 + if (!zero) throw new RangeError(`row ${id} is empty but not zeroed`) + } else { + alive += 1 + } + } + store.alive_ = alive + store.highWater_ = n + store.firstFree = 0 + return store + } + + /** The ids of the living rows, lowest first. */ + *ids(): Generator { + for (let id = 0; id < this.highWater_; id += 1) { + if (this.kind[id] !== EntityKind.None) yield id + } + } + + private grow(): void { + const n = this.kind.length * 2 + const widen = (old: T, fill = 0): T => { + const next = new (old.constructor as new (length: number) => T)(n) + next.set(old) + if (fill !== 0) next.fill(fill, old.length) + return next + } + this.kind = widen(this.kind) + this.x = widen(this.x) + this.y = widen(this.y) + this.owner = widen(this.owner, NO_OWNER) + this.state = widen(this.state) + this.home = widen(this.home) + this.target = widen(this.target) + this.wake = widen(this.wake) + this.legStart = widen(this.legStart) + this.legEnd = widen(this.legEnd) + } +} diff --git a/packages/simulation/src/random/counter.ts b/packages/simulation/src/random/counter.ts new file mode 100644 index 0000000..7d1f4b0 --- /dev/null +++ b/packages/simulation/src/random/counter.ts @@ -0,0 +1,43 @@ +/** + * @module counter + * @description Randomness with no state: a number is a pure function of four others (the world seed, and + * three that say what is being decided, such as a unit's id, the tick, and a purpose). Units decide things at + * run time, and a stream with a position would put that position into every save and make the result depend + * on the order units are visited in; this has neither problem, so a world restored from a save, or one whose + * units are visited in another order, makes the same choices. + * + * A four-step mix: the seed is scrambled by the 32-bit finaliser of MurmurHash3 (`fmix32`), then each of the other + * three inputs is folded into the running value and scrambled again. Only `Math.imul`, `^`, `>>>` and `+` on 32-bit values, so it is identical on every + * engine. The vectors in `tests/counter-random.test.ts` come from an independent implementation. + */ +const TWO_POW_32 = 4_294_967_296 + +function fmix32(value: number): number { + let h = value >>> 0 + h ^= h >>> 16 + h = Math.imul(h, 0x85ebca6b) + h ^= h >>> 13 + h = Math.imul(h, 0xc2b2ae35) + h ^= h >>> 16 + return h >>> 0 +} + +/** A 32-bit hash of the seed and three numbers that say what is being decided. */ +export function counterMix(seed: number, a: number, b: number, salt: number): number { + let h = fmix32(((seed >>> 0) + 0x9e3779b9) >>> 0) + h = fmix32(((h ^ (a >>> 0)) + 0x9e3779b9) >>> 0) + h = fmix32(((h ^ (b >>> 0)) + 0x9e3779b9) >>> 0) + h = fmix32(((h ^ (salt >>> 0)) + 0x9e3779b9) >>> 0) + return h +} + +/** A number from 0 up to but not including 1. */ +export function counterFloat(seed: number, a: number, b: number, salt: number): number { + return counterMix(seed, a, b, salt) / TWO_POW_32 +} + +/** A whole number from 0 up to but not including `n`. */ +export function counterInt(seed: number, a: number, b: number, salt: number, n: number): number { + if (!Number.isInteger(n) || n < 1) throw new RangeError('n must be a whole number of at least 1') + return Math.floor(counterFloat(seed, a, b, salt) * n) +} diff --git a/packages/simulation/src/serialization/hash.ts b/packages/simulation/src/serialization/hash.ts index ef4d76c..09de697 100644 --- a/packages/simulation/src/serialization/hash.ts +++ b/packages/simulation/src/serialization/hash.ts @@ -5,7 +5,7 @@ import { utf8Bytes } from './utf8' * Any change to the field list, order or encoding of what a state hash covers bumps this number * and regenerates the golden hashes. */ -export const HASH_SCHEMA_VERSION = 4 +export const HASH_SCHEMA_VERSION = 5 const TWO_POW_32 = 4_294_967_296 diff --git a/packages/simulation/src/serialization/save.ts b/packages/simulation/src/serialization/save.ts index 4cb6066..696c2c5 100644 --- a/packages/simulation/src/serialization/save.ts +++ b/packages/simulation/src/serialization/save.ts @@ -11,7 +11,8 @@ * bytes 4..7 format version, uint32 big-endian * bytes 8..11 header length N, uint32 big-endian * bytes 12.. header: N bytes of UTF-8 JSON (seed, tick, size, sea level, config, strategic - * points, route hubs, routes, nations with their province ids and expansion points; + * points, route hubs, routes, nations with their province ids and expansion points, + * the units as columns (entities); * the provinces themselves are derived from the terrain and rebuilt on load) * then thirteen tile layers, each width*height long, in this order: * elevation, temperature, humidity (float32, little-endian), @@ -37,11 +38,12 @@ import type { StrategicType, TerrainFields } from '@sovereign/contracts' +import { EntityStore, type EntityColumns } from '../entities/EntityStore' import { Nation } from '../nations/Nation' import { PROFILE_FIELDS, World } from '../world/World' import { utf8Bytes, utf8Decode } from './utf8' -export const SAVE_FORMAT_VERSION = 5 +export const SAVE_FORMAT_VERSION = 6 const MAGIC = [0x53, 0x4f, 0x56, 0x57] // "SOVW" const PREAMBLE = 12 @@ -120,6 +122,7 @@ export function encodeWorld(world: World): Uint8Array { traffic: route.traffic, path: [...route.path] })), + entities: world.entities.toColumns(), nations: world.nations.map((n) => ({ id: n.id, name: n.name, @@ -267,6 +270,18 @@ function nationFromJson(value: unknown, index: number): Nation { }) } +/** The units in a header: every column, checked as it is rebuilt into a store. */ +function entitiesFromJson(value: unknown): EntityStore { + if (!isRecord(value)) throw new SaveFormatError('the header has no entities') + try { + return EntityStore.fromColumns(value as unknown as EntityColumns) + } catch (error) { + if (error instanceof RangeError) + throw new SaveFormatError(`the header entities are malformed: ${error.message}`) + throw error + } +} + function hubFromJson(value: unknown): RouteHub { if ( !isRecord(value) || @@ -415,6 +430,7 @@ function decode(bytes: Uint8Array): World { if (!Array.isArray(header.hubs)) throw new SaveFormatError('the header hubs is not a list') if (!Array.isArray(header.routes)) throw new SaveFormatError('the header routes is not a list') const nations = header.nations.map((n, i) => nationFromJson(n, i)) + const entities = entitiesFromJson(header.entities) const strategicPoints = header.strategicPoints.map(strategicPointFromJson) const hubs = header.hubs.map(hubFromJson) const routes = header.routes.map(routeFromJson) @@ -458,5 +474,5 @@ function decode(bytes: Uint8Array): World { hubs, routes } - return World.restore({ seed, config, tick, terrain, nations, ownership }) + return World.restore({ seed, config, tick, terrain, nations, ownership, entities }) } diff --git a/packages/simulation/src/systems/WanderSystem.ts b/packages/simulation/src/systems/WanderSystem.ts new file mode 100644 index 0000000..77d4769 --- /dev/null +++ b/packages/simulation/src/systems/WanderSystem.ts @@ -0,0 +1,201 @@ +/** + * @module WanderSystem + * @description The first behaviour: a villager rests, picks a place near home, walks there over the cheapest + * route, rests, and goes again. It exists to put units on the map and to prove the machinery the real + * behaviours (gathering, building, settling) will use; see docs/decisions/0008-units-and-a-living-world.md. + * + * **Event-driven.** A villager acts only when its `wake` tick comes round; a timer wheel holds who is due when, + * so a tick costs what happens in it, not how many units there are. A walker's position between events is not + * stored: it is worked out on demand from its route and how much of the leg has passed ({@link positionAt}), + * which is all a renderer needs. + * + * **Same world however it was reached.** The wheel is derived from the rows' `wake` fields ({@link rebuild}), + * the units due on a tick are handled in id order whatever order they were put on the wheel in, and every + * choice is a counter-based draw keyed by (seed, unit, tick, purpose), so a world rebuilt from a save goes on + * exactly as the original would. Routes come from a shared cache that is only ever a memo. + */ +import type { UnitsConfig } from '@sovereign/config' +import { EntityKind, UnitState } from '@sovereign/contracts' +import type { EntityStore } from '../entities/EntityStore' +import { counterInt } from '../random/counter' +import type { CostGrid } from '../terrain/cost' +import { routePosition, type RouteCache } from '../terrain/pathing' + +export interface WanderOptions { + entities: EntityStore + grid: CostGrid + routes: RouteCache + config: UnitsConfig + seed: number + /** The map's size in tiles (the last cell of a row or column may be only partly on it). */ + width: number + height: number + /** Slots in the timer wheel. @default 4096 */ + wheelSize?: number + /** Whether a tile is land: a cell counts as land when half its tiles are, so its middle may be water. */ + land: (x: number, y: number) => boolean +} + +/** What a draw is for, so two choices made on one tick by one unit are not the same number. */ +const SALT_X = 1 +const SALT_Y = 2 +const SALT_REST = 3 + +export class WanderSystem { + private readonly o: WanderOptions + private readonly wheel: number[][] + private readonly size: number + /** For each cell, the tile a walker stands on there (packed `y * width + x`), or -1 until it is worked out. */ + private readonly anchors: Int32Array + + constructor(options: WanderOptions) { + this.o = options + this.size = options.wheelSize ?? 4096 + this.wheel = Array.from({ length: this.size }, () => []) + this.anchors = new Int32Array(options.grid.cols * options.grid.rows).fill(-1) + } + + /** Put a villager on a tile, resting, with its first wake-up a little way off (so a crowd does not set off together). */ + spawnVillager(x: number, y: number, owner: number, home: number, tick = 0): number { + const id = this.o.entities.spawn({ + kind: EntityKind.Villager, + x, + y, + owner, + home, + state: UnitState.Rest + }) + this.o.entities.wake[id] = tick + this.rest(id, tick) + this.schedule(id) + return id + } + + /** Find every villager's timer again from its row: after a restore, or to put the wheel back in order. */ + rebuild(): void { + for (const bucket of this.wheel) bucket.length = 0 + for (const id of this.o.entities.ids()) this.schedule(id) + } + + /** Handle everyone who is due on this tick, lowest id first. */ + step(tick: number): void { + const slot = tick % this.size + const due = this.wheel[slot] as number[] + if (due.length === 0) return + this.wheel[slot] = [] + due.sort((a, b) => a - b) + const { entities } = this.o + let previous = -1 + for (const id of due) { + if (id === previous) continue // on the wheel twice + previous = id + if (!entities.alive(id)) continue + const wake = entities.wake[id] as number + if (wake !== tick) { + if (wake > tick) this.schedule(id) // a walk longer than the wheel: round again + continue + } + if (entities.state[id] === UnitState.Walk) this.arrive(id, tick) + else this.depart(id, tick) + } + } + + /** Where a villager is at `tick`, in tiles: where it rests, or along its route while it walks. */ + positionAt(id: number, tick: number): [number, number] { + const { entities, grid, routes } = this.o + const x = entities.x[id] as number + const y = entities.y[id] as number + if (entities.state[id] !== UnitState.Walk) return [x, y] + const route = routes.route(this.cellOf(x, y), entities.target[id] as number) + if (route === null) return [x, y] + const span = (entities.legEnd[id] as number) - (entities.legStart[id] as number) + const progress = span > 0 ? (tick - (entities.legStart[id] as number)) / span : 1 + return routePosition(route, grid, progress, (cell) => this.anchorOf(cell)) + } + + /** + * The tile a walker stands on in a cell: the land tile nearest the middle (ties to the lowest row, then the + * lowest column), or the middle itself if the cell holds no land. Worked out once per cell. + */ + anchorOf(cell: number): [number, number] { + const { grid, width, height, land } = this.o + let packed = this.anchors[cell] as number + if (packed < 0) { + const cx = cell % grid.cols + const cy = (cell - cx) / grid.cols + const half = grid.cell >> 1 + const mx = Math.min(width - 1, cx * grid.cell + half) + const my = Math.min(height - 1, cy * grid.cell + half) + let best = -1 + let bestD = Infinity + for (let y = cy * grid.cell; y < Math.min(height, (cy + 1) * grid.cell); y += 1) { + for (let x = cx * grid.cell; x < Math.min(width, (cx + 1) * grid.cell); x += 1) { + if (!land(x, y)) continue + const d = (x - mx) * (x - mx) + (y - my) * (y - my) + if (d < bestD) { + bestD = d + best = y * width + x + } + } + } + packed = best >= 0 ? best : my * width + mx + this.anchors[cell] = packed + } + const x = packed % width + return [x, (packed - x) / width] + } + + private schedule(id: number): void { + const wake = this.o.entities.wake[id] as number + ;(this.wheel[wake % this.size] as number[]).push(id) + } + + private rest(id: number, tick: number): number { + const { restMin, restMax } = this.o.config + return restMin + counterInt(this.o.seed, id, tick, SALT_REST, restMax - restMin + 1) + } + + private cellOf(x: number, y: number): number { + const { grid } = this.o + return Math.floor(y / grid.cell) * grid.cols + Math.floor(x / grid.cell) + } + + /** Rested: pick somewhere near home and set off, or rest again if there is nowhere to go. */ + private depart(id: number, tick: number): void { + const { entities, grid, routes, config, seed } = this.o + const home = entities.home[id] as number + const hx = home % grid.cols + const hy = (home - hx) / grid.cols + const r = config.wanderRadius + const tx = clamp(hx + counterInt(seed, id, tick, SALT_X, 2 * r + 1) - r, 0, grid.cols - 1) + const ty = clamp(hy + counterInt(seed, id, tick, SALT_Y, 2 * r + 1) - r, 0, grid.rows - 1) + const target = ty * grid.cols + tx + const here = this.cellOf(entities.x[id] as number, entities.y[id] as number) + const route = target === here || grid.land[target] !== 1 ? null : routes.route(here, target) + if (route === null) { + entities.wake[id] = tick + this.rest(id, tick) + } else { + const ticks = Math.max(1, Math.ceil(route.cost / config.walkSpeed)) + entities.state[id] = UnitState.Walk + entities.target[id] = target + entities.legStart[id] = tick + entities.legEnd[id] = tick + ticks + entities.wake[id] = tick + ticks + } + this.schedule(id) + } + + /** Arrived: stand on the cell's anchor tile and rest. */ + private arrive(id: number, tick: number): void { + const { entities } = this.o + const [x, y] = this.anchorOf(entities.target[id] as number) + entities.x[id] = x + entities.y[id] = y + entities.state[id] = UnitState.Rest + entities.wake[id] = tick + this.rest(id, tick) + this.schedule(id) + } +} + +function clamp(v: number, lo: number, hi: number): number { + return Math.min(hi, Math.max(lo, v)) +} diff --git a/packages/simulation/src/terrain/pathing.ts b/packages/simulation/src/terrain/pathing.ts new file mode 100644 index 0000000..bff2aa0 --- /dev/null +++ b/packages/simulation/src/terrain/pathing.ts @@ -0,0 +1,234 @@ +/** + * @module pathing + * @description The cheapest way for a walker over the route cost grid ({@link ./cost}), and a cache that lets + * everyone who walks the same way share one search. + * + * Pathfinding is the whole cost of a crowd (a probe on a 2000 x 2000 world: moving a unit is nearly free, a + * search is about 50 microseconds), so a route between two cells is found once, kept forward and reversed, and + * reused. The cache is only a memo: a route is a pure function of the grid, so the same cells come back + * whether it was cached or not, and what it holds never has to be saved. + * + * A* over 8 neighbours (a step costs the mean of the two cells, so costs are the same either way and a route + * reversed is exactly the route back) with an octile heuristic, on a deterministic heap (ties by cell index), expanding + * neighbours in a fixed order and replacing a cell's cost only when strictly cheaper, so the same grid gives the + * same route on every engine whatever was searched before it. Only `+ - * /` and `sqrt` of a constant. + */ +import type { CostGrid } from './cost' +import { MinHeap } from './heap' + +/** A way from one cell to another. */ +export interface Route { + /** The cells, from the start to the goal (one cell for a route from a cell to itself). */ + cells: Int32Array + /** The total cost: each step costs the mean of the two cells it joins (a diagonal one the square root of two times as much), so a route costs the same either way. */ + cost: number + /** The cost paid on arriving at each cell: 0 at the start, `cost` at the goal. */ + cumulative: Float32Array +} + +export interface PathfinderOptions { + /** Only land cells may be walked (a boat may use sea lanes). @default true */ + landOnly?: boolean + /** Give up (no route) after expanding this many cells, so a search never runs away. @default 6000 */ + maxExpand?: number +} + +const DIAGONAL = 1.4142135623730951 +const OCTILE = DIAGONAL - 1 + +export class Pathfinder { + private readonly heap = new MinHeap(4096) + private readonly g: Float32Array + private readonly from: Int32Array + private readonly seen: Uint32Array + private stamp = 0 + private readonly landOnly: boolean + private readonly maxExpand: number + /** The least a step can cost, so the heuristic never overestimates. */ + private readonly minCost: number + /** How many searches have been run (a cache hit is not one). */ + searches = 0 + + constructor( + readonly grid: CostGrid, + options: PathfinderOptions = {} + ) { + const n = grid.cols * grid.rows + this.g = new Float32Array(n) + this.from = new Int32Array(n) + this.seen = new Uint32Array(n) + this.landOnly = options.landOnly ?? true + this.maxExpand = options.maxExpand ?? 6000 + let least = Infinity + for (let c = 0; c < n; c += 1) { + const v = grid.cost[c] as number + if (v < least && v > 0) least = v + } + this.minCost = least < Infinity ? least : 1 + } + + private walkable(cell: number): boolean { + const c = this.grid.cost[cell] as number + return c < Infinity && (!this.landOnly || this.grid.land[cell] === 1) + } + + /** The cheapest route from one cell to another, or null if there is none (or it is too far to search). */ + find(start: number, goal: number): Route | null { + const { cols, rows, cost } = this.grid + const n = cols * rows + if ( + !Number.isInteger(start) || + !Number.isInteger(goal) || + start < 0 || + goal < 0 || + start >= n || + goal >= n + ) { + throw new RangeError('a route runs between two cells of the grid') + } + if (!this.walkable(start) || !this.walkable(goal)) return null + this.searches += 1 + this.stamp += 1 + const heap = this.heap + heap.clear() + const gx = goal % cols + const gy = (goal - gx) / cols + const minCost = this.minCost + const h = (c: number): number => { + const x = c % cols + const dx = Math.abs(x - gx) + const dy = Math.abs((c - x) / cols - gy) + return (Math.max(dx, dy) + OCTILE * Math.min(dx, dy)) * minCost + } + this.g[start] = 0 + this.seen[start] = this.stamp + this.from[start] = -1 + heap.push(h(start), start) + let expanded = 0 + while (heap.size > 0) { + const cell = heap.pop() + if (cell === goal) return this.build(goal) + expanded += 1 + if (expanded > this.maxExpand) return null + const x = cell % cols + const y = (cell - x) / cols + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) { + if (dx === 0 && dy === 0) continue + const nx = x + dx + const ny = y + dy + if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue + const next = ny * cols + nx + if (!this.walkable(next)) continue + const step = + (dx !== 0 && dy !== 0 ? DIAGONAL : 1) * + (((cost[cell] as number) + (cost[next] as number)) / 2) + const total = (this.g[cell] as number) + step + if (this.seen[next] !== this.stamp || total < (this.g[next] as number)) { + this.seen[next] = this.stamp + this.g[next] = total + this.from[next] = cell + heap.push(total + h(next), next) + } + } + } + } + return null + } + + private build(goal: number): Route { + let length = 0 + for (let c = goal; c >= 0; c = this.from[c] as number) length += 1 + const cells = new Int32Array(length) + const cumulative = new Float32Array(length) + let i = length - 1 + for (let c = goal; c >= 0; c = this.from[c] as number) { + cells[i] = c + cumulative[i] = this.g[c] as number + i -= 1 + } + return { cells, cost: this.g[goal] as number, cumulative } + } +} + +/** The same route walked the other way. */ +function reversed(route: Route): Route { + const n = route.cells.length + const cells = new Int32Array(n) + const cumulative = new Float32Array(n) + for (let i = 0; i < n; i += 1) { + cells[i] = route.cells[n - 1 - i] as number + cumulative[i] = route.cost - (route.cumulative[n - 1 - i] as number) + } + return { cells, cost: route.cost, cumulative } +} + +/** Routes found so far, each kept for the way there and the way back. */ +export class RouteCache { + private readonly routes = new Map() + private readonly cells: number + + constructor( + private readonly finder: Pathfinder, + private readonly capacity = 100_000 + ) { + this.cells = finder.grid.cols * finder.grid.rows + } + + /** How many routes (and remembered absences) are held. */ + get size(): number { + return this.routes.size + } + + /** The route between two cells, from the cache if it was walked before, or null if there is none. */ + route(start: number, goal: number): Route | null { + const key = start * this.cells + goal + const held = this.routes.get(key) + if (held !== undefined) return held + const found = this.finder.find(start, goal) + if (this.routes.size >= this.capacity) this.routes.clear() // start again: the memo is only ever a memo + this.routes.set(key, found) + this.routes.set(goal * this.cells + start, found === null ? null : reversed(found)) + return found + } + + clear(): void { + this.routes.clear() + } +} + +/** + * Where a walker is when it has paid `progress` (0 to 1) of a route's cost, in tiles: between the centres of the + * cells it is crossing (or the tile `anchor` names for each cell, where the centre is not a place to stand), in proportion to the cost of each step (so it dawdles through rough ground). + */ +export function routePosition( + route: Route, + grid: CostGrid, + progress: number, + anchor?: (cell: number) => [number, number] +): [number, number] { + const { cells, cumulative, cost } = route + const centre = + anchor ?? + ((cell: number): [number, number] => { + const x = cell % grid.cols + return [ + x * grid.cell + (grid.cell >> 1), + ((cell - x) / grid.cols) * grid.cell + (grid.cell >> 1) + ] + }) + if (cells.length === 1 || !(cost > 0)) return centre(cells[0] as number) + const paid = Math.min(1, Math.max(0, progress)) * cost + let lo = 0 + let hi = cells.length - 1 + while (hi - lo > 1) { + const mid = (lo + hi) >> 1 + if ((cumulative[mid] as number) <= paid) lo = mid + else hi = mid + } + const [ax, ay] = centre(cells[lo] as number) + const [bx, by] = centre(cells[hi] as number) + const span = (cumulative[hi] as number) - (cumulative[lo] as number) + const f = span > 0 ? Math.min(1, Math.max(0, (paid - (cumulative[lo] as number)) / span)) : 0 + return [ax + (bx - ax) * f, ay + (by - ay) * f] +} diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index aa3f366..47bc2b3 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -13,14 +13,19 @@ import { } from '@sovereign/config' import { BIOME_KEYS, + EntityKind, + NO_OWNER, + UnitState, RESOURCE_CATALOG, resourceDef, type NationProfile, type NationSnapshot, type TerrainFields, + type UnitSnapshot, type WorldSnapshot } from '@sovereign/contracts' import { SimulationClock } from '../clock/SimulationClock' +import { COLUMN_NAMES, EntityStore } from '../entities/EntityStore' import { claimableProvinces } from '../nations/claimable' import { deriveStats } from '../nations/derive' import { Nation } from '../nations/Nation' @@ -32,9 +37,13 @@ import { import { spawnNations } from '../nations/NationSpawner' import { normalizeSeed } from '../random/seed' import { ExpansionSystem } from '../systems/ExpansionSystem' +import { WanderSystem } from '../systems/WanderSystem' +import type { CostGrid } from '../terrain/cost' +import { Pathfinder, RouteCache } from '../terrain/pathing' import { stateHasher } from '../serialization/hash' import { generateTerrain } from '../terrain/pipeline' import { NO_PROVINCE, type ProvinceMap } from '../terrain/provinces' +import { costGridOf } from './costGrid' import { buildProvinceLayer, type ProvinceLayer } from './provinceLayer' import { buildRegrowthTable, ResourceStocks, type ResourceLayerName } from './ResourceStocks' import { WorldMap } from './WorldMap' @@ -102,6 +111,8 @@ export interface WorldState { nations: Nation[] /** One byte per tile: the index of the owning nation, or {@link UNCLAIMED}. */ ownership: Uint8Array + /** The units, when restoring a world that has them (a new world is given its own). */ + entities?: EntityStore } export class World { @@ -126,8 +137,14 @@ export class World { private readonly expansion: ExpansionSystem /** Drawing resources down and letting the renewable ones grow back (it works on `terrain.resources`). */ private readonly stocks: ResourceStocks - - private constructor(state: WorldState, layer: ProvinceLayer) { + /** Everything that lives and acts: villagers for now (saved and hashed). */ + readonly entities: EntityStore + /** The villagers' behaviour: they rest, walk and rest (derived timers: rebuilt from the rows). */ + private readonly wander: WanderSystem + /** The cost of crossing the ground, on cells (derived; never saved). */ + private readonly grid: CostGrid + + private constructor(state: WorldState, layer: ProvinceLayer, grid: CostGrid) { this.seed = state.seed this.config = state.config this.clock = new SimulationClock(state.config.timestep, state.tick) @@ -164,6 +181,19 @@ export class World { config: state.config.expansion, timestep: state.config.timestep }) + this.grid = grid + this.entities = state.entities ?? new EntityStore() + this.wander = new WanderSystem({ + entities: this.entities, + grid, + routes: new RouteCache(new Pathfinder(grid)), + config: state.config.units, + seed: state.seed, + width: state.terrain.width, + height: state.terrain.height, + land: (x, y) => state.terrain.elevation[y * state.terrain.width + x]! > state.terrain.seaLevel + }) + if (state.entities !== undefined) this.wander.rebuild() } /** Generate a new world: terrain first, then nations placed on it. */ @@ -193,7 +223,8 @@ export class World { minLandRatio: config.map.minLandRatio }) - const layer = buildProvinceLayer(terrain, config) + const grid = costGridOf(terrain, config) + const layer = buildProvinceLayer(terrain, config, grid) // The nations are placed on the world as generated, so use its effective sea level. const { nations } = spawnNations({ @@ -213,7 +244,9 @@ export class World { for (const province of nation.provinces) writeOwner(ownership, layer.map, province, index) }) - return new World({ seed, config, tick: 0, terrain, nations, ownership }, layer) + const world = new World({ seed, config, tick: 0, terrain, nations, ownership }, layer, grid) + world.spawnStartingUnits() + return world } /** @@ -222,7 +255,8 @@ export class World { */ static restore(state: WorldState): World { assertValidWorldConfig(state.config) - const world = new World(state, buildProvinceLayer(state.terrain, state.config)) + const grid = costGridOf(state.terrain, state.config) + const world = new World(state, buildProvinceLayer(state.terrain, state.config, grid), grid) const problems = world.validate() if (problems.length > 0) { throw new RangeError(`restored world is not valid:\n ${problems.join('\n ')}`) @@ -234,6 +268,7 @@ export class World { step(): void { // Systems run here, as a flat, ordered list of calls. this.expansion.step(this.clock.tick) + this.wander.step(this.clock.tick) this.stocks.regrow(this.clock.tick) this.refreshDirtyProvinces() this.clock.advance() @@ -313,6 +348,47 @@ export class World { } } + /** Each nation starts with its villagers, resting at its capital. */ + private spawnStartingUnits(): void { + const { width } = this.terrain + const perNation = this.config.units.perNation + this.nations.forEach((nation, index) => { + const x = nation.capital % width + const y = (nation.capital - x) / width + const home = this.cellOf(x, y) + for (let k = 0; k < perNation; k += 1) this.wander.spawnVillager(x, y, index, home) + }) + } + + private cellOf(x: number, y: number): number { + return Math.floor(y / this.grid.cell) * this.grid.cols + Math.floor(x / this.grid.cell) + } + + /** Where every living unit is now (between where it set off and where it is going, if it is walking). */ + unitPositions(): UnitSnapshot { + const count = this.entities.count + const snapshot: UnitSnapshot = { + tick: this.clock.tick, + count, + id: new Uint32Array(count), + kind: new Uint8Array(count), + owner: new Uint8Array(count), + x: new Float32Array(count), + y: new Float32Array(count) + } + let i = 0 + for (const id of this.entities.ids()) { + const [x, y] = this.wander.positionAt(id, this.clock.tick) + snapshot.id[i] = id + snapshot.kind[i] = this.entities.kind[id] as number + snapshot.owner[i] = this.entities.owner[id] as number + snapshot.x[i] = x + snapshot.y[i] = y + i += 1 + } + return snapshot + } + /** Advance the simulation by `ticks` ticks. */ run(ticks: number): void { if (!Number.isSafeInteger(ticks) || ticks < 0) { @@ -323,7 +399,7 @@ export class World { /** * A 128-bit fingerprint of the simulation state (see docs/simulation/determinism.md, section 7.3, - * "Version 4"). Equal hashes mean equal worlds on any engine. + * "Version 5"). Equal hashes mean equal worlds on any engine. */ stateHash(): string { const h = stateHasher() @@ -415,6 +491,19 @@ export class World { for (const province of n.provinces) h.writeUint32(province) } + // the villagers (hash schema 5): every column of every row, empty rows included + const e = this.entities + const rows = e.highWater + h.writeUint32(rows) + for (const name of COLUMN_NAMES) { + const column = e[name] + if (column instanceof Uint8Array) { + h.writeUint8Array(column.subarray(0, rows)) + } else { + for (let i = 0; i < rows; i += 1) h.writeUint32((column[i] as number) >>> 0) + } + } + return h.digest() } @@ -597,9 +686,77 @@ export class World { } } + this.validateEntities(problems) + return problems } + /** The units: what they are, where they stand, where they are going, when they next act. */ + private validateEntities(problems: string[]): void { + const e = this.entities + const t = this.terrain + const cells = this.grid.cols * this.grid.rows + const landCell = (c: number): boolean => + Number.isInteger(c) && c >= 0 && c < cells && this.grid.land[c] === 1 + for (let id = 0; id < e.highWater; id += 1) { + const kind = e.kind[id] as number + if (kind === EntityKind.None) { + const zeroed = + e.x[id] === 0 && + e.y[id] === 0 && + e.owner[id] === NO_OWNER && + e.state[id] === 0 && + e.home[id] === 0 && + e.target[id] === 0 && + e.wake[id] === 0 && + e.legStart[id] === 0 && + e.legEnd[id] === 0 + if (!zeroed) problems.push(`entity row ${id} is empty but not zeroed`) + continue + } + if (kind !== EntityKind.Villager) { + problems.push(`unit ${id} has the kind ${kind}, which is not a kind of unit`) + continue + } + const x = e.x[id] as number + const y = e.y[id] as number + if (x >= t.width || y >= t.height) { + problems.push(`unit ${id} is outside the map at (${x}, ${y})`) + } else if ((t.elevation[y * t.width + x] as number) <= t.seaLevel) { + problems.push(`unit ${id} is not on land at (${x}, ${y})`) + } + const owner = e.owner[id] as number + if (owner !== NO_OWNER && owner >= this.nations.length) { + problems.push(`unit ${id} has the owner ${owner}, which names no nation`) + } + if (!landCell(e.home[id] as number)) { + problems.push(`unit ${id} has the home ${e.home[id]}, which is not a land cell`) + } + const state = e.state[id] as number + if (state === UnitState.Walk) { + const target = e.target[id] as number + const start = e.legStart[id] as number + const end = e.legEnd[id] as number + if (!landCell(target)) + problems.push(`unit ${id} is heading for ${target}, which is not a land cell`) + if (!(end > start)) + problems.push( + `unit ${id} has a leg that ends at ${end}, no later than it starts at ${start}` + ) + if (e.wake[id] !== end) + problems.push(`unit ${id} wakes at ${e.wake[id]} but its leg ends at ${end}`) + if (start > this.clock.tick) + problems.push(`unit ${id} set off at ${start}, which is in the future`) + } else if (state === UnitState.Rest) { + if ((e.wake[id] as number) < this.clock.tick) { + problems.push(`unit ${id} has a wake-up at tick ${e.wake[id]}, which is already past`) + } + } else { + problems.push(`unit ${id} has the state ${state}, which is not resting or walking`) + } + } + } + /** The two resource slots: array sizes, catalogue ids, the layer a resource lives in, and stocks. */ private validateResources(problems: string[]): void { const size = this.terrain.width * this.terrain.height diff --git a/packages/simulation/src/world/costGrid.ts b/packages/simulation/src/world/costGrid.ts new file mode 100644 index 0000000..6212d7a --- /dev/null +++ b/packages/simulation/src/world/costGrid.ts @@ -0,0 +1,25 @@ +/** + * @module costGrid + * @description The cost of crossing the ground on a coarse grid of cells, built from a world's terrain and + * configuration. A pure function of them, so a world made and a world restored get the same grid. Walkers, + * the province cut and the route network all read it. + */ +import type { WorldConfig } from '@sovereign/config' +import type { TerrainFields } from '@sovereign/contracts' +import { buildCostGrid, type CostGrid } from '../terrain/cost' + +export function costGridOf(terrain: TerrainFields, config: WorldConfig): CostGrid { + return buildCostGrid({ + width: terrain.width, + height: terrain.height, + seaLevel: terrain.seaLevel, + elevation: terrain.elevation, + biomeIds: terrain.biomeIds, + riverMask: terrain.riverMask, + riverWidth: terrain.riverWidth, + highlandElevation: config.biomes.highlandElevation, + slopeScale: config.resources.features.slopeScale, + cell: config.routes.cell, + config: config.routes.cost + }) +} diff --git a/packages/simulation/src/world/provinceLayer.ts b/packages/simulation/src/world/provinceLayer.ts index 3af330a..ec8800d 100644 --- a/packages/simulation/src/world/provinceLayer.ts +++ b/packages/simulation/src/world/provinceLayer.ts @@ -7,8 +7,9 @@ import type { WorldConfig } from '@sovereign/config' import type { TerrainFields } from '@sovereign/contracts' import { buildProvinceFacts, type ProvinceFacts } from '../nations/provinceProfile' -import { buildCostGrid } from '../terrain/cost' +import type { CostGrid } from '../terrain/cost' import { buildProvinces, tileCosts, type ProvinceMap } from '../terrain/provinces' +import { costGridOf } from './costGrid' export interface ProvinceLayer { /** The cut: which province each tile is in, their tiles, areas and neighbours. */ @@ -17,21 +18,12 @@ export interface ProvinceLayer { facts: ProvinceFacts } -export function buildProvinceLayer(terrain: TerrainFields, config: WorldConfig): ProvinceLayer { +export function buildProvinceLayer( + terrain: TerrainFields, + config: WorldConfig, + grid: CostGrid = costGridOf(terrain, config) +): ProvinceLayer { const { width, height } = terrain - const grid = buildCostGrid({ - width, - height, - seaLevel: terrain.seaLevel, - elevation: terrain.elevation, - biomeIds: terrain.biomeIds, - riverMask: terrain.riverMask, - riverWidth: terrain.riverWidth, - highlandElevation: config.biomes.highlandElevation, - slopeScale: config.resources.features.slopeScale, - cell: config.routes.cell, - config: config.routes.cost - }) const land = new Uint8Array(width * height) for (let i = 0; i < land.length; i += 1) land[i] = terrain.elevation[i] > terrain.seaLevel ? 1 : 0 const map = buildProvinces({ diff --git a/packages/simulation/tests/counter-random.test.ts b/packages/simulation/tests/counter-random.test.ts new file mode 100644 index 0000000..a8982dc --- /dev/null +++ b/packages/simulation/tests/counter-random.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest' +import { counterFloat, counterInt, counterMix } from '../src/random/counter' + +describe('counterMix: a hash of four numbers', () => { + // Vectors from an independent implementation (Python integers and masks) of the same four-step mix. + it.each([ + [[0, 0, 0, 0], 2688605155], + [[1, 0, 0, 0], 3120657311], + [[1337, 5, 100, 7], 803228589], + [[0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff], 420893632], + [[123456789, 42, 365000, 3], 2560630870], + [[2024, 29999, 1, 0], 1942173129] + ] as const)('%j gives %i', (input, expected) => { + expect(counterMix(input[0], input[1], input[2], input[3])).toBe(expected) + }) + + it('is a pure function: the same inputs always give the same number, in any order', () => { + const first = [1, 2, 3].map((i) => counterMix(9, i, 5, 0)) + const second = [3, 2, 1].map((i) => counterMix(9, i, 5, 0)).reverse() + expect(second).toEqual(first) + }) + + it('changes with every one of its inputs', () => { + const base = counterMix(10, 20, 30, 40) + expect(counterMix(11, 20, 30, 40)).not.toBe(base) + expect(counterMix(10, 21, 30, 40)).not.toBe(base) + expect(counterMix(10, 20, 31, 40)).not.toBe(base) + expect(counterMix(10, 20, 30, 41)).not.toBe(base) + }) + + it('is not symmetric: swapping the inputs gives something else', () => { + expect(counterMix(1, 2, 3, 4)).not.toBe(counterMix(1, 3, 2, 4)) + expect(counterMix(1, 2, 3, 4)).not.toBe(counterMix(2, 1, 3, 4)) + }) + + it('always gives a whole number from 0 to 2^32 - 1', () => { + for (let i = 0; i < 2000; i += 1) { + const v = counterMix(i, i * 7, i * 13, i % 5) + expect(Number.isInteger(v)).toBe(true) + expect(v).toBeGreaterThanOrEqual(0) + expect(v).toBeLessThanOrEqual(0xffffffff) + } + }) +}) + +describe('counterFloat: a number from 0 up to but not including 1', () => { + it('is the mix over 2^32', () => { + expect(counterFloat(1337, 5, 100, 7)).toBe(803228589 / 4294967296) + }) + + it('looks uniform: the mean is near a half and each tenth gets about a tenth', () => { + const n = 100000 + let sum = 0 + const tenths = new Array(10).fill(0) + for (let i = 0; i < n; i += 1) { + const f = counterFloat(77, i, 1234, 2) + expect(f).toBeGreaterThanOrEqual(0) + expect(f).toBeLessThan(1) + sum += f + tenths[Math.floor(f * 10)]! += 1 + } + expect(sum / n).toBeGreaterThan(0.49) + expect(sum / n).toBeLessThan(0.51) + for (const t of tenths) expect(Math.abs(t - n / 10)).toBeLessThan(400) + }) + + it('does not repeat for neighbouring ids or ticks (no visible pattern between them)', () => { + const seen = new Set() + for (let id = 0; id < 300; id += 1) + for (let tick = 0; tick < 300; tick += 1) seen.add(counterMix(5, id, tick, 0)) + expect(seen.size).toBeGreaterThan(89990) // the birthday bound expects about one collision in 90,000 draws of 32 bits + }) + + it('is uncorrelated between neighbouring ids', () => { + const n = 20000 + let sx = 0 + let sy = 0 + let sxy = 0 + let sxx = 0 + let syy = 0 + for (let i = 0; i < n; i += 1) { + const x = counterFloat(3, i, 10, 0) + const y = counterFloat(3, i + 1, 10, 0) + sx += x + sy += y + sxy += x * y + sxx += x * x + syy += y * y + } + const cov = sxy / n - (sx / n) * (sy / n) + const r = cov / Math.sqrt((sxx / n - (sx / n) ** 2) * (syy / n - (sy / n) ** 2)) + expect(Math.abs(r)).toBeLessThan(0.03) + }) +}) + +describe('counterInt: a whole number from 0 up to but not including n', () => { + it('stays below n, takes every value, and gives 0 for n of 1', () => { + const counts = new Array(7).fill(0) + for (let i = 0; i < 7000; i += 1) { + const v = counterInt(8, i, 3, 1, 7) + expect(Number.isInteger(v)).toBe(true) + expect(v).toBeGreaterThanOrEqual(0) + expect(v).toBeLessThan(7) + counts[v]! += 1 + } + for (const c of counts) expect(Math.abs(c - 1000)).toBeLessThan(150) + expect(counterInt(8, 1, 1, 1, 1)).toBe(0) + }) + + it('is the float scaled and cut down', () => { + expect(counterInt(1337, 5, 100, 7, 10)).toBe(Math.floor(counterFloat(1337, 5, 100, 7) * 10)) + }) + + it('refuses an n that is not a whole number of at least 1', () => { + expect(() => counterInt(0, 0, 0, 0, 0)).toThrow(RangeError) + expect(() => counterInt(0, 0, 0, 0, -3)).toThrow(RangeError) + expect(() => counterInt(0, 0, 0, 0, 2.5)).toThrow(RangeError) + expect(() => counterInt(0, 0, 0, 0, Number.NaN)).toThrow(RangeError) + }) +}) diff --git a/packages/simulation/tests/determinism/golden.test.ts b/packages/simulation/tests/determinism/golden.test.ts index 82c64a3..f598689 100644 --- a/packages/simulation/tests/determinism/golden.test.ts +++ b/packages/simulation/tests/determinism/golden.test.ts @@ -72,7 +72,7 @@ describe('golden depletion', () => { expect(taken).toBe(7358) world.run(700) expect(world.validate()).toEqual([]) - expect(world.stateHash()).toBe('c1e637cf883551260f002e64a2344582') + expect(world.stateHash()).toBe('a6ae8bf2b7bd19eebd7b3cfb7fe5d13c') }) }) diff --git a/packages/simulation/tests/determinism/golden/world-hashes.json b/packages/simulation/tests/determinism/golden/world-hashes.json index d92c4ad..9583947 100644 --- a/packages/simulation/tests/determinism/golden/world-hashes.json +++ b/packages/simulation/tests/determinism/golden/world-hashes.json @@ -1,5 +1,5 @@ { - "hashSchemaVersion": 4, + "hashSchemaVersion": 5, "entries": [ { "name": "small world, seed 1, tick 0", @@ -44,7 +44,7 @@ } }, "steps": 0, - "expectedHash": "a8449c196736e11a580cf238ff9485f7" + "expectedHash": "a17cd58178c31c35a85277a312bc4a30" }, { "name": "small world, seed 12345, 100 ticks", @@ -89,7 +89,7 @@ } }, "steps": 100, - "expectedHash": "0415e2cdc3abdca094a27a6619982e3b" + "expectedHash": "ee027cbe8ddb60cb7f15dd744f4ec9fd" }, { "name": "text seed \"sovereign\", 30 ticks", @@ -134,7 +134,7 @@ } }, "steps": 30, - "expectedHash": "ffeb37cd088325a5ddf268049711e9e2" + "expectedHash": "1c76b2cfb5d1f2c91074870b5f25fce2" }, { "name": "island mode, seed 7", @@ -179,7 +179,7 @@ } }, "steps": 10, - "expectedHash": "a3a2fec9ed236fd12212ed325e613ae0" + "expectedHash": "4d9c8d6a9785d8956970c50b7d1955b9" }, { "name": "no nations, seed 3", @@ -224,7 +224,7 @@ } }, "steps": 5, - "expectedHash": "57193335672d5680512d950743cd999f" + "expectedHash": "8e63efae6164a792074a1c710194c0e5" }, { "name": "land-ratio rescue (sea level 0.9 leaves too little land), seed 2024", @@ -269,7 +269,7 @@ } }, "steps": 0, - "expectedHash": "f92a16dfd54c6b0b87f0d83935292eac" + "expectedHash": "00f449b9ad025a8e62fa180dd110e892" }, { "name": "slower clock: timestep 0.25, 40 ticks", @@ -315,7 +315,7 @@ } }, "steps": 40, - "expectedHash": "b8c812c3da8d72d6194d3d3ba32a69b2" + "expectedHash": "e251e8062878a120d251dc45a5b37750" }, { "name": "wider map 320x200, seed 99, 1000 ticks", @@ -360,7 +360,7 @@ } }, "steps": 1000, - "expectedHash": "b83d20dda100eeea9b49dfa587154608" + "expectedHash": "7928eec3a398a5c82f3e843accca36d0" }, { "name": "growing: small world, seed 11, 300 ticks (nations mid-expansion)", @@ -405,7 +405,7 @@ } }, "steps": 300, - "expectedHash": "07a5e389e77fc2f3ed08a34c3fff2e77" + "expectedHash": "8b2792daec1b627b8dbdbecf2ed459c5" }, { "name": "settled: small world, seed 7, 2000 ticks (the borders have stopped moving)", @@ -450,7 +450,7 @@ } }, "steps": 2000, - "expectedHash": "29e64734d05b6b63d6963037a8d82d4b" + "expectedHash": "4b54b2cc1c37be898a6d75a851eb4e66" } ] } diff --git a/packages/simulation/tests/entity-store.test.ts b/packages/simulation/tests/entity-store.test.ts new file mode 100644 index 0000000..e3d7645 --- /dev/null +++ b/packages/simulation/tests/entity-store.test.ts @@ -0,0 +1,276 @@ +import { EntityKind } from '@sovereign/contracts' +import { describe, expect, it } from 'vitest' +import { EntityStore } from '../src/entities/EntityStore' + +const spawn = (store: EntityStore, x = 0, y = 0): number => + store.spawn({ kind: EntityKind.Villager, x, y }) + +describe('EntityStore: spawning', () => { + it('starts empty', () => { + const store = new EntityStore() + expect(store.count).toBe(0) + expect(store.highWater).toBe(0) + expect([...store.ids()]).toEqual([]) + }) + + it('gives ids from 0 up, and keeps what each row was given', () => { + const store = new EntityStore() + const a = store.spawn({ kind: EntityKind.Villager, x: 5, y: 9, owner: 3, home: 77, state: 2 }) + const b = spawn(store, 1, 2) + expect([a, b]).toEqual([0, 1]) + expect(store.count).toBe(2) + expect(store.kind[a]).toBe(EntityKind.Villager) + expect([store.x[a], store.y[a]]).toEqual([5, 9]) + expect(store.owner[a]).toBe(3) + expect(store.home[a]).toBe(77) + expect(store.state[a]).toBe(2) + expect([store.x[b], store.y[b]]).toEqual([1, 2]) + }) + + it('has no owner unless one is given', () => { + const store = new EntityStore() + expect(store.owner[spawn(store)]).toBe(255) + }) + + it('refuses a row with no kind, or a position off the 16 bit grid', () => { + const store = new EntityStore() + expect(() => store.spawn({ kind: EntityKind.None, x: 0, y: 0 })).toThrow(RangeError) + expect(() => store.spawn({ kind: EntityKind.Villager, x: -1, y: 0 })).toThrow(RangeError) + expect(() => store.spawn({ kind: EntityKind.Villager, x: 0, y: 70000 })).toThrow(RangeError) + expect(() => store.spawn({ kind: EntityKind.Villager, x: 1.5, y: 0 })).toThrow(RangeError) + expect(store.count).toBe(0) + }) + + it('takes the edges of the grid and the highest kind, and refuses the first value past them', () => { + const store = new EntityStore() + expect(() => store.spawn({ kind: 255, x: 65535, y: 65535 })).not.toThrow() + expect(() => store.spawn({ kind: 1, x: 0, y: 0 })).not.toThrow() + expect(() => store.spawn({ kind: 256, x: 0, y: 0 })).toThrow(RangeError) + expect(() => store.spawn({ kind: 1, x: 65536, y: 0 })).toThrow(RangeError) + expect(() => store.spawn({ kind: 1, x: 0, y: 65536 })).toThrow(RangeError) + expect(() => store.spawn({ kind: 1, x: 0, y: -1 })).toThrow(RangeError) + expect(() => store.spawn({ kind: 1.5, x: 0, y: 0 })).toThrow(RangeError) + }) + + it('keeps the target, the timers and the owner it was given', () => { + const store = new EntityStore() + const id = store.spawn({ + kind: 1, + x: 3, + y: 4, + target: 8, + wake: 9, + legStart: 10, + legEnd: 11, + owner: 6 + }) + expect([ + store.target[id], + store.wake[id], + store.legStart[id], + store.legEnd[id], + store.owner[id] + ]).toEqual([8, 9, 10, 11, 6]) + }) + + it('grows past its first capacity without losing a row', () => { + const store = new EntityStore(4) + for (let i = 0; i < 1000; i += 1) spawn(store, i, 2 * i) + expect(store.count).toBe(1000) + for (let i = 0; i < 1000; i += 1) { + expect([store.x[i], store.y[i]]).toEqual([i, 2 * i]) + } + }) +}) + +describe('EntityStore: despawning', () => { + it('empties the row and counts one fewer', () => { + const store = new EntityStore() + const a = store.spawn({ kind: EntityKind.Villager, x: 5, y: 5, owner: 1, home: 9 }) + spawn(store) + store.despawn(a) + expect(store.count).toBe(1) + expect(store.alive(a)).toBe(false) + expect(store.kind[a]).toBe(EntityKind.None) + expect([store.x[a], store.y[a], store.home[a]]).toEqual([0, 0, 0]) + expect(store.owner[a]).toBe(255) + }) + + it('hands the lowest free id to the next spawn, however the rows were freed', () => { + const store = new EntityStore() + for (let i = 0; i < 6; i += 1) spawn(store) + store.despawn(4) + store.despawn(1) + store.despawn(3) + expect(spawn(store)).toBe(1) + expect(spawn(store)).toBe(3) + expect(spawn(store)).toBe(4) + expect(spawn(store)).toBe(6) + }) + + it('allocates the same ids whatever order the rows were freed in (what a restore needs)', () => { + const run = (order: number[]): number[] => { + const store = new EntityStore() + for (let i = 0; i < 8; i += 1) spawn(store) + for (const id of order) store.despawn(id) + return [spawn(store), spawn(store), spawn(store)] + } + expect(run([2, 5, 0])).toEqual(run([0, 5, 2])) + expect(run([2, 5, 0])).toEqual([0, 2, 5]) + }) + + it('refuses to despawn a row that is empty or not there', () => { + const store = new EntityStore() + const a = spawn(store) + store.despawn(a) + expect(() => store.despawn(a)).toThrow(RangeError) + expect(() => store.despawn(99)).toThrow(RangeError) + expect(() => store.despawn(-1)).toThrow(RangeError) + }) + + it('keeps the high water mark: it is where the rows stop, not how many are alive', () => { + const store = new EntityStore() + for (let i = 0; i < 5; i += 1) spawn(store) + store.despawn(4) + expect(store.highWater).toBe(5) + expect(store.count).toBe(4) + }) +}) + +describe('EntityStore: iterating', () => { + it('visits the living rows by id, skipping the dead', () => { + const store = new EntityStore() + for (let i = 0; i < 7; i += 1) spawn(store) + store.despawn(0) + store.despawn(3) + store.despawn(6) + expect([...store.ids()]).toEqual([1, 2, 4, 5]) + }) + + it('reports whether a row is alive, and false past the end', () => { + const store = new EntityStore() + const a = spawn(store) + expect(store.alive(a)).toBe(true) + expect(store.alive(a + 1)).toBe(false) + expect(store.alive(-1)).toBe(false) + expect(store.alive(a + 0.5)).toBe(false) + expect(store.alive(Number.NaN)).toBe(false) + }) +}) + +describe('EntityStore: columns, for saving and restoring', () => { + const filled = (): EntityStore => { + const store = new EntityStore(2) + for (let i = 0; i < 6; i += 1) { + store.spawn({ + kind: 1, + x: i, + y: 2 * i, + owner: i % 3, + state: i % 2, + home: 10 + i, + target: 20 + i, + wake: 30 + i, + legStart: 40 + i, + legEnd: 50 + i + }) + } + store.despawn(1) + store.despawn(4) + return store + } + + it('gives every column up to the high water mark, holes included', () => { + const store = filled() + const c = store.toColumns() + expect(c.highWater).toBe(6) + expect(c.kind).toEqual([1, 0, 1, 1, 0, 1]) + expect(c.x).toEqual([0, 0, 2, 3, 0, 5]) + expect(c.owner).toEqual([0, 255, 2, 0, 255, 2]) + expect(c.legEnd).toEqual([50, 0, 52, 53, 0, 55]) + }) + + it('rebuilds the same store from them: the same rows, the same count, the same ids handed out next', () => { + const a = filled() + const b = EntityStore.fromColumns(a.toColumns()) + expect(b.toColumns()).toEqual(a.toColumns()) + expect(b.count).toBe(a.count) + expect(b.highWater).toBe(a.highWater) + expect([...b.ids()]).toEqual([...a.ids()]) + expect([ + a.spawn({ kind: 1, x: 0, y: 0 }), + a.spawn({ kind: 1, x: 0, y: 0 }), + a.spawn({ kind: 1, x: 0, y: 0 }) + ]).toEqual([1, 4, 6]) + expect([ + b.spawn({ kind: 1, x: 0, y: 0 }), + b.spawn({ kind: 1, x: 0, y: 0 }), + b.spawn({ kind: 1, x: 0, y: 0 }) + ]).toEqual([1, 4, 6]) + }) + + it('rebuilds an empty store from empty columns', () => { + const empty = EntityStore.fromColumns(new EntityStore().toColumns()) + expect(empty.count).toBe(0) + expect(empty.spawn({ kind: 1, x: 0, y: 0 })).toBe(0) + }) + + it('refuses columns that are not all the same length, or a high water mark that does not match', () => { + const c = filled().toColumns() + expect(() => EntityStore.fromColumns({ ...c, x: c.x.slice(1) })).toThrow(RangeError) + expect(() => EntityStore.fromColumns({ ...c, legEnd: [...c.legEnd, 1] })).toThrow(RangeError) + expect(() => EntityStore.fromColumns({ ...c, highWater: 5 })).toThrow(RangeError) + }) + + it('refuses a value that does not fit its column, one way at a time', () => { + const c = filled().toColumns() // rows 1 and 4 are empty, so only rows 0, 2, 3 and 5 may change + const bad = (over: Partial): void => { + expect(() => EntityStore.fromColumns({ ...c, ...over })).toThrow(/does not fit/) + } + bad({ kind: [1, 0, 1, 1, 0, 256] }) + bad({ x: [0, 0, 2, 3, 0, 65536] }) + bad({ y: [0, 0, 2, 3, 0, -1] }) + bad({ owner: [0, 255, 2, 0, 255, 256] }) + bad({ state: [0, 0, 1, 0, 0, 1.5] }) + bad({ home: [10, 0, 12, 13, 0, 2.5] }) + bad({ target: [20, 0, 22, 23, 0, Number.NaN] }) + bad({ wake: [30, 0, 32, 33, 0, 2 ** 31] }) + bad({ legStart: [40, 0, 42, 43, 0, -(2 ** 31) - 1] }) + bad({ legEnd: [50, 0, 52, 53, 0, Infinity] }) + const edge = { + ...c, + x: [0, 0, 2, 3, 0, 65535], + wake: [30, 0, 32, 33, 0, 2 ** 31 - 1], + legStart: [40, 0, 42, 43, 0, -(2 ** 31)] + } + expect(() => EntityStore.fromColumns(edge)).not.toThrow() + }) + + it('refuses a column that is missing or not a list', () => { + const c = filled().toColumns() + expect(() => EntityStore.fromColumns({ ...c, x: undefined as unknown as number[] })).toThrow( + RangeError + ) + expect(() => EntityStore.fromColumns({ ...c, home: 'nope' as unknown as number[] })).toThrow( + RangeError + ) + }) + + it('refuses a high water mark that is not a whole number of 0 or more', () => { + const c = filled().toColumns() + expect(() => EntityStore.fromColumns({ ...c, highWater: -1 })).toThrow(RangeError) + expect(() => EntityStore.fromColumns({ ...c, highWater: 5.5 })).toThrow(RangeError) + }) + + it('refuses a row that is empty but not zeroed', () => { + const c = filled().toColumns() + expect(() => EntityStore.fromColumns({ ...c, x: [0, 9, 2, 3, 0, 5] })).toThrow(RangeError) + }) + + it('copies: changing the columns afterwards does not change the store', () => { + const c = filled().toColumns() + const store = EntityStore.fromColumns(c) + c.x[0] = 999 + expect(store.x[0]).toBe(0) + }) +}) diff --git a/packages/simulation/tests/hash.test.ts b/packages/simulation/tests/hash.test.ts index 4045771..9b7be72 100644 --- a/packages/simulation/tests/hash.test.ts +++ b/packages/simulation/tests/hash.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest' import { ByteHasher, HASH_SCHEMA_VERSION, stateHasher } from '../src/serialization/hash' describe('HASH_SCHEMA_VERSION', () => { - it('is 4: nations own provinces (ids, and expansion points), and the province cut is fingerprinted', () => { - expect(HASH_SCHEMA_VERSION).toBe(4) + it('is 5: the villagers (the columns of the entity store) are hashed after the nations', () => { + expect(HASH_SCHEMA_VERSION).toBe(5) }) }) @@ -30,14 +30,14 @@ describe('ByteHasher', () => { b.writeFloat64(0) b.writeFloat64(0.5) b.writeUint8(1) - expect(a.digest()).toBe('8305b0bf315b05c7be428f5367175e6f') - expect(b.digest()).toBe('8305b0bf315b05c7be428f5367175e6f') + expect(a.digest()).toBe('6a2ab08b8ce0f93bb65930a153140823') + expect(b.digest()).toBe('6a2ab08b8ce0f93bb65930a153140823') }) it('encodes a string as its UTF-8 byte length (uint32, big-endian) then its UTF-8 bytes', () => { const h = stateHasher() h.writeString('héllo ✓ \u{1F30D}') - expect(h.digest()).toBe('d4f7583f75a3cfa1705a6e16bfb73cf1') + expect(h.digest()).toBe('bd320239af8c3f3ec6b1b97b1cae68ae') }) it('depends on the order of writes', () => { @@ -95,7 +95,7 @@ describe('bulk array writers', () => { -2.5 ) ) - expect(h.digest()).toBe('bd5a9b81f6b26b37d8076341458d9103') + expect(h.digest()).toBe('e1f3f06ec3df60076603a1fa83cac841') }) it('writeFloat32Array canonicalizes -0 to +0, like writeFloat64', () => { @@ -118,17 +118,17 @@ describe('bulk array writers', () => { it('writeUint8Array: a uint32 length, then the bytes', () => { const h = stateHasher() h.writeUint8Array(Uint8Array.of(0, 1, 2, 255, 128)) - expect(h.digest()).toBe('bee514285e33a9b3fa008ea92a1e69e6') + expect(h.digest()).toBe('417e2000c0456544441153a3468e1ae3') const empty = stateHasher() empty.writeUint8Array(new Uint8Array(0)) - expect(empty.digest()).toBe('19633495f01c50b9e4c332deea69cbda') + expect(empty.digest()).toBe('ba13ed5109c00e1a21cd9b750f00af49') }) it('writes arrays one after another, each self-delimiting', () => { const h = stateHasher() h.writeUint8Array(Uint8Array.of(0, 1, 2, 255, 128)) h.writeFloat32Array(Float32Array.of(1.5, -0.25)) - expect(h.digest()).toBe('c35fe6a01f51ed83f802d244593a3ff8') + expect(h.digest()).toBe('bef68b481eba4838420207642c16ad85') }) it('cannot confuse where one array ends and the next begins', () => { @@ -153,7 +153,7 @@ describe('bulk array writers', () => { describe('stateHasher', () => { it('starts with the versioned header: "SOVH" then the schema version as a uint32', () => { - expect(stateHasher().digest()).toBe('419d97344219625b23baad833530a5dc') + expect(stateHasher().digest()).toBe('ee2b8397305f93b8c6764b2f4dc0bc4f') }) it('differs from a bare ByteHasher, so state hashes are never confused with raw ones', () => { diff --git a/packages/simulation/tests/pathing.test.ts b/packages/simulation/tests/pathing.test.ts new file mode 100644 index 0000000..a5aa081 --- /dev/null +++ b/packages/simulation/tests/pathing.test.ts @@ -0,0 +1,376 @@ +import { describe, expect, it } from 'vitest' +import type { CostGrid } from '../src/terrain/cost' +import { Pathfinder, RouteCache, routePosition } from '../src/terrain/pathing' + +/** + * A cost grid drawn as text, one character per cell (the cell is 4 tiles): + * . open land (cost 1) # rough ground (cost 10) ~ a sea lane (cost 5, water) x closed (Infinity) + */ +function draw(rows: string[]): { grid: CostGrid; at: (x: number, y: number) => number } { + const height = rows.length + const cols = rows[0].length + const cost = new Float32Array(cols * height) + const land = new Uint8Array(cols * height) + rows.forEach((row, y) => { + expect(row).toHaveLength(cols) + ;[...row].forEach((ch, x) => { + const c = y * cols + x + if (ch === '.') [cost[c], land[c]] = [1, 1] + else if (ch === '#') [cost[c], land[c]] = [10, 1] + else if (ch === '~') [cost[c], land[c]] = [5, 0] + else [cost[c], land[c]] = [Infinity, 0] + }) + }) + return { grid: { cell: 4, cols, rows: height, cost, land }, at: (x, y) => y * cols + x } +} + +const xy = (grid: CostGrid, c: number): [number, number] => [ + c % grid.cols, + Math.floor(c / grid.cols) +] + +describe('Pathfinder: the cheapest way over the ground', () => { + it('goes straight along open ground, from the start to the goal', () => { + const { grid, at } = draw(['.......']) + const route = new Pathfinder(grid).find(at(0, 0), at(6, 0)) + expect(route).not.toBeNull() + expect(Array.from(route!.cells)).toEqual([0, 1, 2, 3, 4, 5, 6]) + expect(route!.cost).toBeCloseTo(6, 5) + }) + + it('prices a diagonal step at the square root of two times the mean cost of the two cells', () => { + const { grid, at } = draw(['...', '...', '...']) + const route = new Pathfinder(grid).find(at(0, 0), at(2, 2))! + expect(route.cost).toBeCloseTo(2 * Math.SQRT2, 5) + expect(route.cells).toHaveLength(3) + }) + + it('goes round a wall through the gap rather than over it', () => { + const { grid, at } = draw(['..#..', '..#..', '.....', '..#..']) + const route = new Pathfinder(grid).find(at(0, 0), at(4, 0))! + const crossing = Array.from(route.cells) + .map((c) => xy(grid, c)) + .filter(([x]) => x === 2) + expect(crossing).toEqual([[2, 2]]) + }) + + it('goes over rough ground when there is no way round, and pays for it', () => { + const { grid, at } = draw(['..#..']) + const route = new Pathfinder(grid).find(at(0, 0), at(4, 0))! + expect(route.cost).toBeCloseTo(1 + 5.5 + 5.5 + 1, 5) // each step is the mean of the two cells it joins + }) + + it('has a route of one cell and no cost from a cell to itself', () => { + const { grid, at } = draw(['...']) + const route = new Pathfinder(grid).find(at(1, 0), at(1, 0))! + expect(Array.from(route.cells)).toEqual([at(1, 0)]) + expect(route.cost).toBe(0) + }) + + it('costs the same there and back', () => { + const { grid, at } = draw(['..#...', '.#..#.', '...#..', '#.....']) + const finder = new Pathfinder(grid) + const there = finder.find(at(0, 0), at(5, 3))! + const back = finder.find(at(5, 3), at(0, 0))! + expect(back.cost).toBeCloseTo(there.cost, 4) + }) +}) + +describe('Pathfinder: where a walker may go', () => { + it('never steps onto water or closed ground, though a sea lane has a cost', () => { + const { grid, at } = draw(['.~~~.', '.~~~.', '.....']) + const route = new Pathfinder(grid).find(at(0, 0), at(4, 0))! + for (const c of route.cells) expect(grid.land[c]).toBe(1) + expect(route.cost).toBeGreaterThan(4) + }) + + it('has no route to an island, or from or to a cell that is not land', () => { + const { grid, at } = draw(['..~..', '..~..', '..x..']) + const finder = new Pathfinder(grid) + expect(finder.find(at(0, 0), at(4, 0))).toBeNull() + expect(finder.find(at(2, 0), at(0, 0))).toBeNull() + expect(finder.find(at(0, 0), at(2, 2))).toBeNull() + }) + + it('may cross a sea lane when told it is a boat', () => { + const { grid, at } = draw(['..~..']) + const boat = new Pathfinder(grid, { landOnly: false }).find(at(0, 0), at(4, 0))! + expect(boat.cells).toHaveLength(5) + expect(boat.cost).toBeCloseTo(1 + 3 + 3 + 1, 5) + }) + + it('lets a boat cross water but never closed ground', () => { + const { grid, at } = draw(['.x.', '.x.']) + expect(new Pathfinder(grid, { landOnly: false }).find(at(0, 0), at(2, 0))).toBeNull() + expect(new Pathfinder(grid, { landOnly: false }).find(at(1, 0), at(0, 0))).toBeNull() // starting on closed ground + }) + + it('has no route to a cell the search cannot reach within its limit, and says so rather than guessing', () => { + const { grid, at } = draw(['..................................']) + const finder = new Pathfinder(grid, { maxExpand: 10 }) + expect(finder.find(at(0, 0), at(33, 0))).toBeNull() + expect(new Pathfinder(grid).find(at(0, 0), at(33, 0))).not.toBeNull() + }) + + it('rejects a cell that is not on the grid', () => { + const { grid } = draw(['...']) + const finder = new Pathfinder(grid) + expect(() => finder.find(-1, 0)).toThrow(RangeError) + expect(() => finder.find(0, 3)).toThrow(RangeError) + expect(() => finder.find(0.5, 1)).toThrow(RangeError) + expect(() => finder.find(1, 0.5)).toThrow(RangeError) + expect(() => finder.find(0, -1)).toThrow(RangeError) + expect(() => finder.find(3, 0)).toThrow(RangeError) // the first cell past the end + }) +}) + +describe('Pathfinder: the same answer every time', () => { + const world = draw([ + '..#....#..', + '.#..##..#.', + '...#..#...', + '#.....#.#.', + '..#.##....', + '.#......#.' + ]) + + it('is not affected by the searches made before it', () => { + const used = new Pathfinder(world.grid) + const pairs: Array<[number, number]> = [] + for (let a = 0; a < 60; a += 7) for (let b = 59; b >= 0; b -= 11) pairs.push([a, b]) + for (const [a, b] of pairs) used.find(a, b) + for (const [a, b] of pairs) { + const fresh = new Pathfinder(world.grid).find(a, b) + const again = used.find(a, b) + expect(again === null ? null : Array.from(again.cells)).toEqual( + fresh === null ? null : Array.from(fresh.cells) + ) + } + }) + + it('chooses the same one of equal routes each time', () => { + const { grid, at } = draw(['....', '....', '....', '....']) + const a = new Pathfinder(grid).find(at(0, 0), at(3, 3))! + const b = new Pathfinder(grid).find(at(0, 0), at(3, 3))! + expect(Array.from(a.cells)).toEqual(Array.from(b.cells)) + }) +}) + +describe('RouteCache: a route walked by many is found once', () => { + const { grid, at } = draw(['..#....', '.#..#..', '...#...', '#......']) + + it('gives the route a fresh search would, and the same object again', () => { + const cache = new RouteCache(new Pathfinder(grid)) + const first = cache.route(at(0, 0), at(6, 3))! + const fresh = new Pathfinder(grid).find(at(0, 0), at(6, 3))! + expect(Array.from(first.cells)).toEqual(Array.from(fresh.cells)) + expect(first.cost).toBeCloseTo(fresh.cost, 4) + expect(cache.route(at(0, 0), at(6, 3))).toBe(first) + }) + + it('knows the way back too, which is the same route reversed, without searching again', () => { + const finder = new Pathfinder(grid) + const cache = new RouteCache(finder) + const there = cache.route(at(0, 0), at(6, 3))! + const searches = finder.searches + const back = cache.route(at(6, 3), at(0, 0))! + expect(finder.searches).toBe(searches) + expect(Array.from(back.cells)).toEqual(Array.from(there.cells).reverse()) + expect(back.cost).toBeCloseTo(there.cost, 4) + }) + + it('remembers that there is no route', () => { + const island = draw(['..x..']) + const finder = new Pathfinder(island.grid) + const cache = new RouteCache(finder) + expect(cache.route(0, 4)).toBeNull() + const searches = finder.searches + expect(cache.route(0, 4)).toBeNull() + expect(finder.searches).toBe(searches) + }) + + it('forgets everything when it is full or cleared, and still gives the right answers', () => { + const finder = new Pathfinder(grid) + const cache = new RouteCache(finder, 4) + const keep = cache.route(at(0, 0), at(6, 3))! + cache.route(at(0, 3), at(6, 0)) + cache.route(at(1, 0), at(5, 3)) // the cache is now over its limit and starts again + expect(cache.size).toBeLessThanOrEqual(4) + const again = cache.route(at(0, 0), at(6, 3))! + expect(Array.from(again.cells)).toEqual(Array.from(keep.cells)) + cache.clear() + expect(cache.size).toBe(0) + }) +}) + +describe('routePosition: where a walker is part of the way along', () => { + const { grid, at } = draw(['.....']) + const route = new Pathfinder(grid).find(at(0, 0), at(4, 0))! + const centre = (cell: number): [number, number] => [ + (cell % grid.cols) * grid.cell + 2, + Math.floor(cell / grid.cols) * grid.cell + 2 + ] + + it('is the first cell centre at the start and the last at the end', () => { + expect(routePosition(route, grid, 0)).toEqual(centre(at(0, 0))) + expect(routePosition(route, grid, 1)).toEqual(centre(at(4, 0))) + }) + + it('is halfway between when half the cost is paid', () => { + const [x, y] = routePosition(route, grid, 0.5) + expect(x).toBeCloseTo(centre(at(2, 0))[0], 4) + expect(y).toBeCloseTo(centre(at(2, 0))[1], 4) + }) + + it('moves slowly through rough ground and quickly over open ground', () => { + const rough = draw(['..#..']) + const r = new Pathfinder(rough.grid).find(0, 4)! + // the steps cost 1, 5.5, 5.5 and 1 (13 in all): a thirteenth of the way is one open step, half the cost is + // the middle of the rough cell, which took 11 of the 13 + expect(routePosition(r, rough.grid, 1 / 13)[0]).toBeCloseTo(2 + 4 * 1, 4) + expect(routePosition(r, rough.grid, 0.5)[0]).toBeCloseTo(2 + 4 * 2, 4) + expect(routePosition(r, rough.grid, 12 / 13)[0]).toBeCloseTo(2 + 4 * 3, 4) + }) + + it('walks between the tiles a function names for each cell when it is given one', () => { + const anchor = (cell: number): [number, number] => [cell * 4 + 1, 7] + expect(routePosition(route, grid, 0, anchor)).toEqual([at(0, 0) * 4 + 1, 7]) + expect(routePosition(route, grid, 1, anchor)).toEqual([at(4, 0) * 4 + 1, 7]) + const [x, y] = routePosition(route, grid, 0.5, anchor) + expect(x).toBeCloseTo(at(2, 0) * 4 + 1, 4) + expect(y).toBe(7) + const one = new Pathfinder(grid).find(at(2, 0), at(2, 0))! + expect(routePosition(one, grid, 0.5, anchor)).toEqual([at(2, 0) * 4 + 1, 7]) + }) + + it('clamps progress outside 0 to 1, and handles a route of one cell', () => { + expect(routePosition(route, grid, -3)).toEqual(centre(at(0, 0))) + expect(routePosition(route, grid, 7)).toEqual(centre(at(4, 0))) + const one = new Pathfinder(grid).find(at(2, 0), at(2, 0))! + expect(routePosition(one, grid, 0.5)).toEqual(centre(at(2, 0))) + }) +}) + +/** The cheapest cost between two cells by plain Dijkstra over every cell (slow, simple, obviously right). */ +function dijkstra(grid: CostGrid, start: number, goal: number): number { + const n = grid.cols * grid.rows + const best = new Float64Array(n).fill(Infinity) + const done = new Uint8Array(n) + best[start] = 0 + for (;;) { + let cell = -1 + for (let c = 0; c < n; c += 1) { + if (done[c] === 0 && best[c]! < Infinity && (cell < 0 || best[c]! < best[cell]!)) cell = c + } + if (cell < 0) return Infinity + if (cell === goal) return best[cell]! + done[cell] = 1 + const x = cell % grid.cols + const y = (cell - x) / grid.cols + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) { + const nx = x + dx + const ny = y + dy + if ((dx === 0 && dy === 0) || nx < 0 || ny < 0 || nx >= grid.cols || ny >= grid.rows) + continue + const next = ny * grid.cols + nx + if (grid.land[next] !== 1 || !(grid.cost[next]! < Infinity)) continue + const cost = + best[cell]! + + (dx !== 0 && dy !== 0 ? Math.SQRT2 : 1) * ((grid.cost[cell]! + grid.cost[next]!) / 2) + if (cost < best[next]!) best[next] = cost + } + } + } +} + +describe('Pathfinder against a plain Dijkstra, on grids drawn at random', () => { + function randomGrid(seed: number, cols: number, rows: number): CostGrid { + let s = seed >>> 0 + const next = (): number => { + s = (Math.imul(s, 1664525) + 1013904223) >>> 0 + return s / 4294967296 + } + const text: string[] = [] + for (let y = 0; y < rows; y += 1) { + let row = '' + for (let x = 0; x < cols; x += 1) { + const v = next() + row += v < 0.55 ? '.' : v < 0.8 ? '#' : v < 0.9 ? '~' : 'x' + } + text.push(row) + } + return draw(text).grid + } + + it('finds a route exactly as cheap as the best one, or none when there is none, and the route is walkable', () => { + let compared = 0 + for (let trial = 0; trial < 25; trial += 1) { + const grid = randomGrid(trial + 1, 7, 6) + const finder = new Pathfinder(grid, { maxExpand: 100000 }) + for (let a = 0; a < 42; a += 5) { + for (let b = 41; b >= 0; b -= 4) { + if (grid.land[a] !== 1 || grid.land[b] !== 1) continue + const expected = dijkstra(grid, a, b) + const route = finder.find(a, b) + if (expected === Infinity) { + expect(route).toBeNull() + continue + } + expect(route, `trial ${trial}, ${a} to ${b}`).not.toBeNull() + expect(route!.cost).toBeCloseTo(expected, 3) + expect(route!.cells[0]).toBe(a) + expect(route!.cells[route!.cells.length - 1]).toBe(b) + for (let i = 1; i < route!.cells.length; i += 1) { + const [x0, y0] = xy(grid, route!.cells[i - 1]!) + const [x1, y1] = xy(grid, route!.cells[i]!) + expect(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0))).toBe(1) // one step, never across an edge + expect(grid.land[route!.cells[i]!]).toBe(1) + } + compared += 1 + } + } + } + expect(compared).toBeGreaterThan(200) + }) +}) + +describe('Pathfinder: bookkeeping', () => { + it('counts the searches it runs', () => { + const { grid, at } = draw(['.....']) + const finder = new Pathfinder(grid) + expect(finder.searches).toBe(0) + finder.find(at(0, 0), at(4, 0)) + finder.find(at(4, 0), at(0, 0)) + expect(finder.searches).toBe(2) + }) + + it('is not led astray by what a search that gave up left behind', () => { + const { grid, at } = draw(['..#.....#.....', '.#..##..#.##..', '......#.......']) + const limited = new Pathfinder(grid, { maxExpand: 6 }) + expect(limited.find(at(0, 0), at(13, 2))).toBeNull() // gives up with cells still queued + const after = limited.find(at(0, 0), at(3, 0)) + const fresh = new Pathfinder(grid, { maxExpand: 6 }).find(at(0, 0), at(3, 0)) + expect(after).not.toBeNull() + expect(Array.from(after!.cells)).toEqual(Array.from(fresh!.cells)) + }) + + it('gives a route its cost paid at each cell, rising from 0 to the total, the same backwards', () => { + const { grid, at } = draw(['..#..', '.....']) + const cache = new RouteCache(new Pathfinder(grid)) + const there = cache.route(at(0, 0), at(4, 1))! + const back = cache.route(at(4, 1), at(0, 0))! + for (const r of [there, back]) { + expect(r.cumulative[0]).toBe(0) + expect(r.cumulative[r.cumulative.length - 1]).toBeCloseTo(r.cost, 4) + for (let i = 1; i < r.cumulative.length; i += 1) { + expect(r.cumulative[i]).toBeGreaterThan(r.cumulative[i - 1]!) + } + } + // a route costs the same either way, so the way back is the way there from the other end + expect(back.cumulative[1]).toBeCloseTo( + there.cost - there.cumulative[there.cumulative.length - 2]!, + 4 + ) + }) +}) diff --git a/packages/simulation/tests/save.test.ts b/packages/simulation/tests/save.test.ts index 9e9ad5c..8e60526 100644 --- a/packages/simulation/tests/save.test.ts +++ b/packages/simulation/tests/save.test.ts @@ -35,13 +35,13 @@ describe('SAVE_FORMAT_VERSION and layout', () => { const bytes = encodeWorld(make(7)) const view = new DataView(bytes.buffer, bytes.byteOffset) - it('is version 5', () => { - expect(SAVE_FORMAT_VERSION).toBe(5) + it('is version 6', () => { + expect(SAVE_FORMAT_VERSION).toBe(6) }) it('starts with the magic "SOVW", the version (uint32, big-endian) and the header length', () => { expect([...bytes.subarray(0, 4)]).toEqual(MAGIC) - expect(view.getUint32(4, false)).toBe(5) + expect(view.getUint32(4, false)).toBe(6) expect(view.getUint32(8, false)).toBeGreaterThan(0) }) @@ -161,7 +161,7 @@ describe('decodeWorld rejects a file that is not a good save', () => { rejects(bad, /not a Sovereign save/) }) - it.each([0, 1, 2, 3, 4, 6, 99])('a file of unsupported format version %d', (version) => { + it.each([0, 1, 2, 3, 4, 5, 7, 99])('a file of unsupported format version %d', (version) => { const bad = good.slice() new DataView(bad.buffer).setUint32(4, version, false) rejects(bad, /unsupported save format version/) @@ -348,6 +348,49 @@ describe('decodeWorld rejects a file that is not a good save', () => { ) }) + it('keeps the villagers, holes and all, and they go on as before', () => { + const world = make(7) + world.run(30) + const hole = world.entities.spawn({ kind: 1, x: 0, y: 0 }) + world.entities.despawn(hole) // a hole in the rows + const decoded = decodeWorld(encodeWorld(world)) + expect(decoded.entities.toColumns()).toEqual(world.entities.toColumns()) + expect(decoded.stateHash()).toBe(world.stateHash()) + world.run(120) + decoded.run(120) + expect(decoded.stateHash()).toBe(world.stateHash()) + }) + + it.each([ + ['no entities', (h: Record) => delete h.entities], + ['entities that are not an object', (h: Record) => (h.entities = 5)], + [ + 'a column that is missing', + (h: Record) => delete (h.entities as Record).x + ], + [ + 'a column of the wrong length', + (h: Record) => ((h.entities as { x: number[] }).x = [1, 2]) + ], + [ + 'a value that does not fit', + (h: Record) => ((h.entities as { kind: number[] }).kind[0] = 300) + ], + [ + 'a kind that is not a kind', + (h: Record) => ((h.entities as { kind: number[] }).kind[0] = 99) + ], + [ + 'a unit in the sea', + (h: Record) => ((h.entities as { x: number[] }).x[0] = 15999) + ] + ])('a header with %s', (_label, edit) => { + rejects( + withHeader(good, (h) => edit(h)), + /entit|unit|not valid|column|does not fit/ + ) + }) + it('a nation whose province list repeats a province held by another', () => { rejects( withHeader(good, (h) => { diff --git a/packages/simulation/tests/support/costGrid.ts b/packages/simulation/tests/support/costGrid.ts new file mode 100644 index 0000000..95e8c55 --- /dev/null +++ b/packages/simulation/tests/support/costGrid.ts @@ -0,0 +1,23 @@ +import type { CostGrid } from '../../src/terrain/cost' + +/** + * A cost grid drawn as text, one character per cell (the cell is 4 tiles): + * . open land (cost 1) # rough ground (cost 10) ~ a sea lane (cost 5, water) x closed (Infinity) + */ +export function drawGrid(rows: string[]): { grid: CostGrid; at: (x: number, y: number) => number } { + const height = rows.length + const cols = rows[0]!.length + const cost = new Float32Array(cols * height) + const land = new Uint8Array(cols * height) + rows.forEach((row, y) => { + if (row.length !== cols) throw new Error('every row must be as long as the first') + ;[...row].forEach((ch, x) => { + const c = y * cols + x + if (ch === '.') [cost[c], land[c]] = [1, 1] + else if (ch === '#') [cost[c], land[c]] = [10, 1] + else if (ch === '~') [cost[c], land[c]] = [5, 0] + else [cost[c], land[c]] = [Infinity, 0] + }) + }) + return { grid: { cell: 4, cols, rows: height, cost, land }, at: (x, y) => y * cols + x } +} diff --git a/packages/simulation/tests/wander.test.ts b/packages/simulation/tests/wander.test.ts new file mode 100644 index 0000000..4af17ee --- /dev/null +++ b/packages/simulation/tests/wander.test.ts @@ -0,0 +1,531 @@ +import { EntityKind, UnitState } from '@sovereign/contracts' +import { describe, expect, it } from 'vitest' +import { EntityStore } from '../src/entities/EntityStore' +import { WanderSystem } from '../src/systems/WanderSystem' +import { Pathfinder, RouteCache, routePosition } from '../src/terrain/pathing' +import { drawGrid } from './support/costGrid' + +const OPEN = Array.from({ length: 12 }, () => '.'.repeat(16)) + +interface Options { + rows?: string[] + units?: Array<{ x: number; y: number }> + radius?: number + walkSpeed?: number + restMin?: number + restMax?: number + wheelSize?: number + seed?: number + /** The map's size in tiles when it is not a whole number of cells. */ + tiles?: { width: number; height: number } + /** Which tiles are land (default: all of them). */ + land?: (x: number, y: number) => boolean +} + +function setup(o: Options = {}) { + const { grid, at } = drawGrid(o.rows ?? OPEN) + const entities = new EntityStore(4) + const routes = new RouteCache(new Pathfinder(grid, { maxExpand: 100000 })) + const config = { + perNation: 0, + walkSpeed: o.walkSpeed ?? 5, + wanderRadius: o.radius ?? 4, + restMin: o.restMin ?? 1, + restMax: o.restMax ?? 4 + } + const system = new WanderSystem({ + entities, + grid, + routes, + config, + seed: o.seed ?? 1337, + width: o.tiles?.width ?? grid.cols * grid.cell, + height: o.tiles?.height ?? grid.rows * grid.cell, + wheelSize: o.wheelSize, + land: o.land ?? (() => true) + }) + const ids = (o.units ?? [{ x: 34, y: 22 }]).map((u) => system.spawnVillager(u.x, u.y, 0, 0)) + return { grid, at, entities, routes, config, system, ids } +} + +const cellOf = (grid: { cols: number; cell: number }, x: number, y: number): number => + Math.floor(y / grid.cell) * grid.cols + Math.floor(x / grid.cell) + +/** Run until the unit walks (or `limit` ticks), returning the tick it set off on. */ +function runUntil( + s: ReturnType, + id: number, + from: number, + state: number, + limit = 500 +): number { + for (let tick = from; tick < from + limit; tick += 1) { + s.system.step(tick) + if (s.entities.state[id] === state) return tick + } + throw new Error('the unit never reached that state') +} + +describe('spawnVillager', () => { + it('puts a villager on its tile, resting, at home, with a first wake-up within the rest it would take', () => { + const s = setup({ restMin: 2, restMax: 9 }) + const id = s.ids[0]! + expect(s.entities.kind[id]).toBe(EntityKind.Villager) + expect([s.entities.x[id], s.entities.y[id]]).toEqual([34, 22]) + expect(s.entities.state[id]).toBe(UnitState.Rest) + expect(s.entities.wake[id]).toBeGreaterThanOrEqual(0 + 2) + expect(s.entities.wake[id]).toBeLessThanOrEqual(0 + 9) + }) + + it('records the owner and the home cell it is given', () => { + const s = setup() + const id = s.system.spawnVillager(10, 10, 3, 7) + expect(s.entities.owner[id]).toBe(3) + expect(s.entities.home[id]).toBe(7) + }) + + it('staggers the first wake-ups, so a crowd does not set off on one tick', () => { + const s = setup({ + units: Array.from({ length: 40 }, () => ({ x: 34, y: 22 })), + restMin: 1, + restMax: 20 + }) + expect(new Set(s.ids.map((id) => s.entities.wake[id])).size).toBeGreaterThan(8) + }) +}) + +describe('WanderSystem: a villager rests, walks, arrives, rests', () => { + it('sets off from rest toward a land cell near home, never the one it is on', () => { + const s = setup({ units: [{ x: 34, y: 22 }] }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + const tick = runUntil(s, id, 0, UnitState.Walk) + const home = s.entities.home[id] as number + const target = s.entities.target[id] as number + expect(target).not.toBe(home) + expect(s.grid.land[target]).toBe(1) + const dx = Math.abs((target % s.grid.cols) - (home % s.grid.cols)) + const dy = Math.abs(Math.floor(target / s.grid.cols) - Math.floor(home / s.grid.cols)) + expect(Math.max(dx, dy)).toBeLessThanOrEqual(s.config.wanderRadius) + expect(s.entities.legStart[id]).toBe(tick) + expect(s.entities.wake[id]).toBe(s.entities.legEnd[id]) + expect(s.entities.legEnd[id]).toBeGreaterThan(tick) + }) + + it('takes as long as the route costs over its walking speed, rounded up, and at least a tick', () => { + const s = setup({ walkSpeed: 3 }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + runUntil(s, id, 0, UnitState.Walk) + const route = s.routes.route( + cellOf(s.grid, s.entities.x[id]!, s.entities.y[id]!), + s.entities.target[id]! + )! + expect(s.entities.legEnd[id]! - s.entities.legStart[id]!).toBe( + Math.max(1, Math.ceil(route.cost / 3)) + ) + }) + + it('arrives on the tick the leg ends, at the middle of the target cell, and rests for a while', () => { + const s = setup({ restMin: 3, restMax: 8 }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + runUntil(s, id, 0, UnitState.Walk) + const target = s.entities.target[id]! + const end = s.entities.legEnd[id]! + for (let tick = s.entities.legStart[id]! + 1; tick < end; tick += 1) { + s.system.step(tick) + expect(s.entities.state[id]).toBe(UnitState.Walk) // still on the way + } + s.system.step(end) + expect(s.entities.state[id]).toBe(UnitState.Rest) + expect(s.entities.x[id]).toBe((target % s.grid.cols) * 4 + 2) + expect(s.entities.y[id]).toBe(Math.floor(target / s.grid.cols) * 4 + 2) + const rest = s.entities.wake[id]! - end + expect(rest).toBeGreaterThanOrEqual(3) + expect(rest).toBeLessThanOrEqual(8) + }) + + it('keeps walking, resting and walking for as long as time runs', () => { + const s = setup({ units: Array.from({ length: 10 }, () => ({ x: 34, y: 22 })) }) + for (const id of s.ids) s.entities.home[id] = cellOf(s.grid, 34, 22) + const walks = new Array(10).fill(0) + const before = s.ids.map(() => UnitState.Rest as number) + for (let tick = 0; tick < 600; tick += 1) { + s.system.step(tick) + s.ids.forEach((id, k) => { + const now = s.entities.state[id] as number + if (now === UnitState.Walk && before[k] === UnitState.Rest) walks[k]! += 1 + before[k] = now + }) + } + for (const w of walks) expect(w).toBeGreaterThan(5) + }) + + it('stays on land and on the map, whatever the ground, over a long run', () => { + const rows = [ + '..#...~~..', + '.#..#.~~.#', + '....#..~..', + '.##...#...', + '..~...#.#.', + '....##....' + ] + const s = setup({ + rows, + units: Array.from({ length: 12 }, (_, k) => ({ x: 4 + (k % 3) * 4, y: 6 + (k % 2) * 4 })), + radius: 3 + }) + s.ids.forEach( + (id) => (s.entities.home[id] = cellOf(s.grid, s.entities.x[id]!, s.entities.y[id]!)) + ) + for (let tick = 0; tick < 800; tick += 1) { + s.system.step(tick) + for (const id of s.ids) { + const x = s.entities.x[id]! + const y = s.entities.y[id]! + expect(x).toBeLessThan(s.grid.cols * 4) + expect(y).toBeLessThan(s.grid.rows * 4) + expect(s.grid.land[cellOf(s.grid, x, y)]).toBe(1) + } + } + }) +}) + +describe('WanderSystem: the choices it makes', () => { + it('rests exactly as long as asked when the shortest and longest rest are the same', () => { + const s = setup({ + restMin: 3, + restMax: 3, + units: Array.from({ length: 6 }, () => ({ x: 34, y: 22 })) + }) + for (const id of s.ids) expect(s.entities.wake[id]! - 0).toBe(3) + for (const id of s.ids) s.entities.home[id] = cellOf(s.grid, 34, 22) + for (let t = 0; t < 200; t += 1) { + s.system.step(t) + for (const id of s.ids) { + if (s.entities.state[id] === UnitState.Rest) { + // a rest is 3 ticks from when it began; its wake is never further off than 3 + expect(s.entities.wake[id]! - t).toBeLessThanOrEqual(3) + } + } + } + }) + + it('wanders the whole of its radius, both ways on both axes, and no farther', () => { + const s = setup({ radius: 3, units: Array.from({ length: 60 }, () => ({ x: 26, y: 22 })) }) + const home = cellOf(s.grid, 26, 22) + for (const id of s.ids) s.entities.home[id] = home + let minDx = 0 + let maxDx = 0 + let minDy = 0 + let maxDy = 0 + const hx = home % s.grid.cols + const hy = Math.floor(home / s.grid.cols) + for (let t = 0; t < 400; t += 1) { + s.system.step(t) + for (const id of s.ids) { + if (s.entities.state[id] !== UnitState.Walk) continue + const target = s.entities.target[id]! + const dx = (target % s.grid.cols) - hx + const dy = Math.floor(target / s.grid.cols) - hy + minDx = Math.min(minDx, dx) + maxDx = Math.max(maxDx, dx) + minDy = Math.min(minDy, dy) + maxDy = Math.max(maxDy, dy) + } + } + expect([minDx, maxDx, minDy, maxDy]).toEqual([-3, 3, -3, 3]) + }) + + it('never picks a place off the map when home is in a corner', () => { + for (const corner of [ + { x: 2, y: 2 }, + { x: 62, y: 2 }, + { x: 2, y: 46 }, + { x: 62, y: 46 } + ]) { + const s = setup({ radius: 6, units: Array.from({ length: 20 }, () => corner) }) + const home = cellOf(s.grid, corner.x, corner.y) + for (const id of s.ids) s.entities.home[id] = home + const hx = home % s.grid.cols + const hy = Math.floor(home / s.grid.cols) + for (let t = 0; t < 300; t += 1) { + s.system.step(t) + for (const id of s.ids) { + if (s.entities.state[id] !== UnitState.Walk) continue + const target = s.entities.target[id]! + expect( + Math.max( + Math.abs((target % s.grid.cols) - hx), + Math.abs(Math.floor(target / s.grid.cols) - hy) + ) + ).toBeLessThanOrEqual(6) + } + } + } + }) + + it('takes every walk the whole number of ticks the route calls for, rounded up', () => { + const s = setup({ walkSpeed: 7, units: Array.from({ length: 12 }, () => ({ x: 34, y: 22 })) }) + for (const id of s.ids) s.entities.home[id] = cellOf(s.grid, 34, 22) + let checked = 0 + for (let t = 0; t < 300; t += 1) { + s.system.step(t) + for (const id of s.ids) { + if (s.entities.state[id] !== UnitState.Walk || s.entities.legStart[id] !== t) continue + const route = s.routes.route( + cellOf(s.grid, s.entities.x[id]!, s.entities.y[id]!), + s.entities.target[id]! + )! + expect(s.entities.legEnd[id]! - t).toBe(Math.ceil(route.cost / 7)) + checked += 1 + } + } + expect(checked).toBeGreaterThan(20) + }) + + it('stands on the map even when the last cell of a row is only partly there', () => { + // 16 x 12 cells of 4 tiles is 64 x 48, but the map is 62 x 45: the middle of the last cell is off it + const s = setup({ + tiles: { width: 62, height: 45 }, + units: Array.from({ length: 20 }, () => ({ x: 60, y: 40 })), + radius: 3 + }) + for (const id of s.ids) s.entities.home[id] = cellOf(s.grid, 60, 40) + for (let t = 0; t < 300; t += 1) { + s.system.step(t) + for (const id of s.ids) { + expect(s.entities.x[id]).toBeLessThan(62) + expect(s.entities.y[id]).toBeLessThan(45) + } + } + }) +}) + +describe('WanderSystem: standing in a cell whose middle is water', () => { + // each cell is 4 x 4 tiles; its middle tiles are (2,2) from the corner. Make the middle of every cell sea. + const middleIsSea = (x: number, y: number): boolean => + !(x % 4 >= 1 && x % 4 <= 2 && y % 4 >= 1 && y % 4 <= 2) + + it('arrives on the land tile nearest the middle of the cell, never in the water', () => { + const s = setup({ + land: middleIsSea, + units: Array.from({ length: 15 }, () => ({ x: 34, y: 22 })) + }) + for (const id of s.ids) s.entities.home[id] = cellOf(s.grid, 34, 22) + let arrivals = 0 + for (let t = 0; t < 300; t += 1) { + s.system.step(t) + for (const id of s.ids) { + if (s.entities.state[id] === UnitState.Walk) continue + const x = s.entities.x[id]! + const y = s.entities.y[id]! + if (x === 34 && y === 22) continue // where it started + expect(middleIsSea(x, y)).toBe(true) + arrivals += 1 + } + } + expect(arrivals).toBeGreaterThan(20) + }) + + it('chooses the same tile for a cell every time, the nearest to the middle, ties to the lowest row then column', () => { + const s = setup({ land: middleIsSea }) + // the middle is (14, 10); the land tiles nearest it, one away, are (15, 10) and (14, 11): the lower row wins + expect(s.system.anchorOf(s.at(3, 2))).toEqual([15, 10]) + expect(s.system.anchorOf(s.at(3, 2))).toEqual([15, 10]) + }) + + it('draws a walker between those tiles, not between the middles', () => { + const s = setup({ land: middleIsSea, walkSpeed: 0.2 }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + runUntil(s, id, 0, UnitState.Walk) + const [x, y] = s.system.positionAt(id, s.entities.legEnd[id]!) + expect([x, y]).toEqual(s.system.anchorOf(s.entities.target[id]!)) + }) + + it('stands in the middle of a cell that is all land', () => { + const s = setup() + expect(s.system.anchorOf(s.at(3, 2))).toEqual([14, 10]) + }) + + it('falls back to the middle of a cell with no land in it at all (which a cost grid should not call land)', () => { + const s = setup({ land: () => false }) + expect(s.system.anchorOf(s.at(1, 1))).toEqual([6, 6]) + }) +}) + +describe('WanderSystem: where a walker is', () => { + it('is where it rests while it rests', () => { + const s = setup() + const id = s.ids[0]! + expect(s.system.positionAt(id, 0)).toEqual([34, 22]) + }) + + it('is on its route in proportion to the leg done, from where it set off to where it will arrive', () => { + const s = setup({ walkSpeed: 0.2 }) // slow, so the leg is long enough to have a middle + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + runUntil(s, id, 0, UnitState.Walk) + const start = s.entities.legStart[id]! + const end = s.entities.legEnd[id]! + const target = s.entities.target[id]! + const [sx, sy] = s.system.positionAt(id, start) + const startCell = s.routes.route(cellOf(s.grid, s.entities.x[id]!, s.entities.y[id]!), target)! + .cells[0]! + expect(sx).toBeCloseTo((startCell % s.grid.cols) * 4 + 2, 3) + expect(sy).toBeCloseTo(Math.floor(startCell / s.grid.cols) * 4 + 2, 3) + const [ex, ey] = s.system.positionAt(id, end) + expect(ex).toBeCloseTo((target % s.grid.cols) * 4 + 2, 3) + expect(ey).toBeCloseTo(Math.floor(target / s.grid.cols) * 4 + 2, 3) + expect(end - start).toBeGreaterThanOrEqual(4) + const mid = Math.floor((start + end) / 2) + const route = s.routes.route(startCell, target)! + const expected = routePosition(route, s.grid, (mid - start) / (end - start)) + const [mx, my] = s.system.positionAt(id, mid) + expect(mx).toBeCloseTo(expected[0], 4) + expect(my).toBeCloseTo(expected[1], 4) + }) + + it('is clamped to the leg: before it set off it is at the start, after it arrives at the end', () => { + const s = setup() + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 34, 22) + runUntil(s, id, 0, UnitState.Walk) + const start = s.entities.legStart[id]! + const end = s.entities.legEnd[id]! + expect(s.system.positionAt(id, start - 50)).toEqual(s.system.positionAt(id, start)) + expect(s.system.positionAt(id, end + 50)).toEqual(s.system.positionAt(id, end)) + }) +}) + +describe('WanderSystem: the same world, however it was reached', () => { + const crowd = Array.from({ length: 30 }, (_, k) => ({ x: 20 + (k % 5) * 4, y: 18 + (k % 3) * 4 })) + const snapshot = (s: ReturnType): string => + JSON.stringify([ + s.entities.highWater, + ...[ + s.entities.kind, + s.entities.x, + s.entities.y, + s.entities.state, + s.entities.home, + s.entities.target, + s.entities.wake, + s.entities.legStart, + s.entities.legEnd + ].map((c) => Array.from(c.subarray(0, s.entities.highWater))) + ]) + + it('is the same twice', () => { + const a = setup({ units: crowd }) + const b = setup({ units: crowd }) + for (let t = 0; t < 400; t += 1) { + a.system.step(t) + b.system.step(t) + } + expect(snapshot(a)).toBe(snapshot(b)) + }) + + it('goes on exactly the same after being rebuilt from its rows in the middle (what a restore does)', () => { + const a = setup({ units: crowd }) + for (let t = 0; t < 250; t += 1) a.system.step(t) + // a second world with the same rows, and a new system that finds its timers from them + const b = setup({ units: [] }) + for (const id of a.entities.ids()) { + b.entities.spawn({ + kind: a.entities.kind[id]!, + x: a.entities.x[id]!, + y: a.entities.y[id]!, + owner: a.entities.owner[id]!, + state: a.entities.state[id]!, + home: a.entities.home[id]!, + target: a.entities.target[id]!, + wake: a.entities.wake[id]!, + legStart: a.entities.legStart[id]!, + legEnd: a.entities.legEnd[id]! + }) + } + b.system.rebuild() + expect(snapshot(b)).toBe(snapshot(a)) + for (let t = 250; t < 700; t += 1) { + a.system.step(t) + b.system.step(t) + } + expect(snapshot(b)).toBe(snapshot(a)) + }) + + it('does not depend on the order the units were put on the timers', () => { + const a = setup({ units: crowd }) + const b = setup({ units: crowd }) + b.system.rebuild() // the same timers, put back in a different order (by id, not by when they were set) + for (let t = 0; t < 300; t += 1) { + a.system.step(t) + b.system.step(t) + } + expect(snapshot(b)).toBe(snapshot(a)) + }) + + it('draws different choices for a different seed', () => { + const a = setup({ units: crowd, seed: 1 }) + const b = setup({ units: crowd, seed: 2 }) + for (let t = 0; t < 100; t += 1) { + a.system.step(t) + b.system.step(t) + } + expect(snapshot(a)).not.toBe(snapshot(b)) + }) +}) + +describe('WanderSystem: awkward cases', () => { + it('lets a villager on an island of one cell rest and try again, never setting off', () => { + const s = setup({ rows: ['.x.', 'xxx', '.x.'], units: [{ x: 2, y: 2 }], radius: 2 }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 2, 2) + for (let t = 0; t < 300; t += 1) s.system.step(t) + expect(s.entities.state[id]).toBe(UnitState.Rest) + expect([s.entities.x[id], s.entities.y[id]]).toEqual([2, 2]) + expect(s.entities.wake[id]).toBeGreaterThanOrEqual(300) // still being woken, and still resting + }) + + it('skips a timer whose villager has gone', () => { + const s = setup({ units: Array.from({ length: 5 }, () => ({ x: 34, y: 22 })) }) + s.entities.despawn(s.ids[2]!) + expect(() => { + for (let t = 0; t < 200; t += 1) s.system.step(t) + }).not.toThrow() + expect(s.entities.alive(s.ids[2]!)).toBe(false) + }) + + it('handles walks longer than its timer wheel (a timer that must go round again)', () => { + const rows = ['.'.repeat(40)] + const s = setup({ + rows, + units: [{ x: 2, y: 2 }], + radius: 30, + walkSpeed: 0.5, + wheelSize: 8, + restMin: 1, + restMax: 2 + }) + const id = s.ids[0]! + s.entities.home[id] = cellOf(s.grid, 2, 2) + const set = runUntil(s, id, 0, UnitState.Walk, 50) + const end = s.entities.legEnd[id]! + expect(end - set).toBeGreaterThan(8) // longer than the wheel + for (let t = set + 1; t < end; t += 1) { + s.system.step(t) + expect(s.entities.state[id]).toBe(UnitState.Walk) + } + s.system.step(end) + expect(s.entities.state[id]).toBe(UnitState.Rest) + }) + + it('does nothing, cheaply, with no villagers', () => { + const s = setup({ units: [] }) + expect(() => { + for (let t = 0; t < 50; t += 1) s.system.step(t) + }).not.toThrow() + }) +}) diff --git a/packages/simulation/tests/world-units.test.ts b/packages/simulation/tests/world-units.test.ts new file mode 100644 index 0000000..120a499 --- /dev/null +++ b/packages/simulation/tests/world-units.test.ts @@ -0,0 +1,255 @@ +import { EntityKind, UnitState } from '@sovereign/contracts' +import { describe, expect, it } from 'vitest' +import { COLUMN_NAMES } from '../src/entities/EntityStore' +import { decodeWorld, encodeWorld } from '../src/serialization/save' +import { World } from '../src/world/World' +import { smallWorldOverrides } from './support/worldOptions' + +const make = (seed = 11, units: { perNation?: number } = {}, nations = 6): World => + World.create({ seed, config: { ...smallWorldOverrides({ nations }), units } }) + +const cellOf = (w: World, tile: number): number => { + const cell = w.config.routes.cell + const x = tile % w.terrain.width + const y = Math.floor(tile / w.terrain.width) + return Math.floor(y / cell) * Math.ceil(w.terrain.width / cell) + Math.floor(x / cell) +} + +describe('a world has villagers', () => { + const w = make(11, { perNation: 24 }) + + it('starts each nation with its share, resting at its capital', () => { + expect(w.nations.length).toBeGreaterThan(2) + expect(w.entities.count).toBe(24 * w.nations.length) + for (const id of w.entities.ids()) { + const owner = w.entities.owner[id]! + const capital = w.nations[owner]!.capital + expect(w.entities.kind[id]).toBe(EntityKind.Villager) + expect(w.entities.state[id]).toBe(UnitState.Rest) + expect([w.entities.x[id], w.entities.y[id]]).toEqual([ + capital % w.terrain.width, + Math.floor(capital / w.terrain.width) + ]) + expect(w.entities.home[id]).toBe(cellOf(w, capital)) + } + }) + + it('has none when asked for none, or when there are no nations', () => { + expect(make(11, { perNation: 0 }).entities.count).toBe(0) + expect(make(11, { perNation: 24 }, 0).entities.count).toBe(0) + }) + + it('is a sound world as made', () => { + expect(w.validate()).toEqual([]) + }) +}) + +describe('villagers live as time passes', () => { + it('rests, walks and rests again, and the world stays sound all along', () => { + const w = make(11) + const start = Array.from(w.entities.x.subarray(0, w.entities.highWater)) + let walking = 0 + for (let t = 0; t < 120; t += 1) { + w.step() + for (const id of w.entities.ids()) if (w.entities.state[id] === UnitState.Walk) walking += 1 + if (t % 40 === 0) expect(w.validate()).toEqual([]) + } + expect(walking).toBeGreaterThan(0) + expect(w.validate()).toEqual([]) + expect(Array.from(w.entities.x.subarray(0, w.entities.highWater))).not.toEqual(start) + }) + + it('walks on land, inside the map', () => { + const w = make(11) + for (let t = 0; t < 200; t += 1) { + w.step() + const snap = w.unitPositions() + for (let i = 0; i < snap.count; i += 1) { + expect(snap.x[i]).toBeGreaterThanOrEqual(0) + expect(snap.x[i]).toBeLessThan(w.terrain.width) + expect(snap.y[i]).toBeGreaterThanOrEqual(0) + expect(snap.y[i]).toBeLessThan(w.terrain.height) + } + } + }) +}) + +describe('unitPositions: for a host to draw', () => { + it('lists every living villager by id, with kind, owner and where it is', () => { + const w = make(11) + w.run(60) + const snap = w.unitPositions() + expect(snap.tick).toBe(60) + expect(snap.count).toBe(w.entities.count) + expect(Array.from(snap.id)).toEqual([...w.entities.ids()]) + snap.id.forEach((id, i) => { + expect(snap.kind[i]).toBe(EntityKind.Villager) + expect(snap.owner[i]).toBe(w.entities.owner[id]) + }) + }) + + it('puts a walker between where it set off and where it is going, and a rester where it rests', () => { + const w = make(11) + w.run(80) + const snap = w.unitPositions() + let walkers = 0 + snap.id.forEach((id, i) => { + if (w.entities.state[id] === UnitState.Rest) { + expect([snap.x[i], snap.y[i]]).toEqual([w.entities.x[id], w.entities.y[id]]) + } else { + walkers += 1 + } + }) + expect(walkers).toBeGreaterThan(0) + }) + + it('has no one in a world with no villagers', () => { + const w = make(11, { perNation: 0 }) + const snap = w.unitPositions() + expect(snap.count).toBe(0) + expect(snap.x).toHaveLength(0) + }) +}) + +describe('villagers are part of the state: replay, hash and save', () => { + it('replays to the same hash', () => { + const a = make(7) + const b = make(7) + a.run(150) + b.run(150) + expect(a.stateHash()).toBe(b.stateHash()) + }) + + it('has a hash that moves as villagers move', () => { + const w = make(7) + const before = w.stateHash() + w.run(1) + expect(w.stateHash()).not.toBe(before) + }) + + it('has a hash that sees every column of a villager', () => { + const w = make(7) + const id = [...w.entities.ids()][3]! + const base = w.stateHash() + for (const name of COLUMN_NAMES) { + if (name === 'kind') continue + const column = w.entities[name] + const was = column[id]! + column[id] = was === 5 ? 6 : 5 + expect(w.stateHash(), name).not.toBe(base) + column[id] = was + expect(w.stateHash(), name).toBe(base) + } + }) + + it('goes on exactly the same after being saved and restored in the middle', () => { + const a = make(7) + a.run(90) + const b = decodeWorld(encodeWorld(a)) + expect(b.stateHash()).toBe(a.stateHash()) + expect(b.entities.count).toBe(a.entities.count) + a.run(260) + b.run(260) + expect(b.stateHash()).toBe(a.stateHash()) + expect(b.validate()).toEqual([]) + }) + + it('keeps every column of every villager through a save', () => { + const a = make(7) + a.run(75) + const b = decodeWorld(encodeWorld(a)) + expect(b.entities.toColumns()).toEqual(a.entities.toColumns()) + }) +}) + +describe('validate: villagers that do not add up', () => { + const fresh = (): { w: World; id: number } => { + const w = make(11) + w.run(40) + return { w, id: [...w.entities.ids()][0]! } + } + const walkerOf = (w: World): number => { + for (let t = 0; t < 200; t += 1) { + for (const id of w.entities.ids()) if (w.entities.state[id] === UnitState.Walk) return id + w.step() + } + throw new Error('nobody walked') + } + + it('is sound as made', () => { + expect(fresh().w.validate()).toEqual([]) + }) + + it('catches a kind that does not exist', () => { + const { w, id } = fresh() + w.entities.kind[id] = 99 + expect(w.validate().join('\n')).toMatch(/unit .* kind/) + }) + + it('catches a unit off the map, or in the sea', () => { + const { w, id } = fresh() + const was = [w.entities.x[id]!, w.entities.y[id]!] + w.entities.x[id] = w.terrain.width + expect(w.validate().join('\n')).toMatch(/outside the map/) + w.entities.x[id] = was[0]! + let sea = -1 + for (let i = 0; i < w.terrain.elevation.length && sea < 0; i += 1) + if (w.terrain.elevation[i]! <= w.terrain.seaLevel) sea = i + w.entities.x[id] = sea % w.terrain.width + w.entities.y[id] = Math.floor(sea / w.terrain.width) + expect(w.validate().join('\n')).toMatch(/not on land/) + }) + + it('catches an owner that names no nation', () => { + const { w, id } = fresh() + w.entities.owner[id] = w.nations.length + 3 + expect(w.validate().join('\n')).toMatch(/owner/) + }) + + it('catches a state that is neither resting nor walking', () => { + const { w, id } = fresh() + w.entities.state[id] = 9 + expect(w.validate().join('\n')).toMatch(/state/) + }) + + it('catches a home that is not a cell of the grid', () => { + const { w, id } = fresh() + w.entities.home[id] = -1 + expect(w.validate().join('\n')).toMatch(/home/) + w.entities.home[id] = 10 ** 8 + expect(w.validate().join('\n')).toMatch(/home/) + }) + + it('catches a walker whose leg ends before it begins, or that wakes at the wrong time', () => { + const w = make(11) + const id = walkerOf(w) + const end = w.entities.legEnd[id]! + w.entities.legEnd[id] = w.entities.legStart[id]! + expect(w.validate().join('\n')).toMatch(/leg/) + w.entities.legEnd[id] = end + w.entities.wake[id] = end + 1 + expect(w.validate().join('\n')).toMatch(/wake/) + }) + + it('catches a walker heading for a cell that is not land, or not on the grid', () => { + const w = make(11) + const id = walkerOf(w) + w.entities.target[id] = -4 + expect(w.validate().join('\n')).toMatch(/heading for/) + }) + + it('catches a resting villager whose wake-up is already past', () => { + const { w, id } = fresh() + w.entities.state[id] = UnitState.Rest + w.entities.wake[id] = w.clock.tick - 1 + expect(w.validate().join('\n')).toMatch(/wake/) + }) + + it('catches a row that is empty but not zeroed', () => { + const { w } = fresh() + const hole = w.entities.spawn({ kind: 1, x: 0, y: 0 }) + w.entities.despawn(hole) + w.entities.home[hole] = 5 + expect(w.validate().join('\n')).toMatch(/empty/) + }) +}) diff --git a/packages/simulation/tests/world.test.ts b/packages/simulation/tests/world.test.ts index 2ecbf38..08a2537 100644 --- a/packages/simulation/tests/world.test.ts +++ b/packages/simulation/tests/world.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { resolveWorldConfig } from '@sovereign/config' import type { WorldSnapshot } from '@sovereign/contracts' +import { EntityStore } from '../src/entities/EntityStore' import { spawnNations } from '../src/nations/NationSpawner' import { generateTerrain } from '../src/terrain/pipeline' import { decodeWorld, encodeWorld } from '../src/serialization/save' @@ -97,7 +98,8 @@ describe('World.restore', () => { tick: w.clock.tick, terrain: w.terrain, nations: [...w.nations], - ownership: w.map.ownership + ownership: w.map.ownership, + entities: EntityStore.fromColumns(w.entities.toColumns()) }) it('rebuilds a world with the same state hash, keeping its tick', () => { @@ -365,7 +367,8 @@ describe('resources in the world', () => { tick: world.clock.tick, terrain: structuredClone(world.terrain), nations, - ownership: world.map.ownership.slice() + ownership: world.map.ownership.slice(), + entities: EntityStore.fromColumns(world.entities.toColumns()) }) world.run(500) copy.run(500)