diff --git a/CHANGELOG.md b/CHANGELOG.md index d4f1296..38c6681 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to Econ-Engine are documented here. The changelog records what changed in each update. Design rationale, experiments, observations, and lessons are documented separately in [Lab Notes](LAB_NOTES.md). +## [LIFE15-Worker-069] - (2026-10-28) + +- The Life engine runs in a Web Worker. The page keeps the clock and asks the worker for a goal 0.1 s ahead at the speed shown; the worker runs in slices of at most 50 ms and sends a view copy every stride minutes (the speed over 60, at least one). +- A view copy keeps only what the page reads: the routes of walks under way, each person's next wake-up in place of the wake-up queue, exchanges and walk records among the events, and current memory only for the followed person. It travels as its changes from the last copy sent. +- The page draws the newest copy at or before the clock; when the worker is behind, the clock waits instead of the page. Step shows the next minute once it arrives, and a change of speed jumps to the newest copy. +- The loading card stays until the worker has built its valley. +- New `viewCopy.ts`, `engineWorker.ts` and `engineLink.ts`; the playback functions in `valleyViewModel.ts` replace the per-frame engine step. New unit tests for the view copies, and rewritten playback tests. +- The engine is unchanged, so every fingerprint stays the same. +- The Life 15 specification is revised for update 069. + ## [LIFE15-Planning-068] - (2026-10-27) - A new route's coarse plan runs over a person's pieces, the joined-up patches of known ground within each 200 m chunk, in place of whole chunks. Two pieces are linked where the person knows ground on both sides of a chunk border. A chain of pieces always holds a path, so the band search no longer fails and the search over everything a person knows is no longer needed. diff --git a/LAB_NOTES.md b/LAB_NOTES.md index bd93230..bafd574 100644 --- a/LAB_NOTES.md +++ b/LAB_NOTES.md @@ -6,6 +6,30 @@ Every meaningful model, architecture, experimental, or design update should receive a newest-first entry. Use at most one base update number per Git commit. Refinements completed before that commit keep the same base number with a decimal suffix—for example, `003` and `003.1` belong to the same commit family. Allocate the next base number only for a later commit. Preserve the context, observed problem or research question, rationale, important implementation decisions, trade-offs, findings, and unresolved questions. Distinguish verified observations from hypotheses. If the original rationale is unknown, say so rather than inferring intent from the finished code. +## [LIFE15-Worker-069] - (2026-10-28) + +After update 068 the page still ran the engine on its own thread, so every slow stretch of the engine was a slow frame: at 1 month/s the page drew about 16–19 frames a second. The owner asked for the engine in a worker thread and approved the revised specification. + +**What was built.** The engine runs in a Web Worker; the page keeps the clock and asks for a goal 0.1 s ahead. Copying whole states between threads would have cost more than the engine: on day 13 the engine's state held 550 kB of routes and about 750 kB of memory tables a copy, which the screen does not read. The view copy keeps only the routes under way, each person's next wake-up, exchanges and walk records, and current memory for the followed person alone, and travels as its changes from the last copy. + +**Copy cost, measured in Node on the canonical forty, seed 20260813, one day at 1 month/s (two copies a day).** Day 13: engine 2,723 ms, making the changes 17 ms, copying them 71 ms (about 940 kB a copy), applying them 4 ms. Day 30: engine 240 ms, changes 11 ms, copying 6 ms (about 140 kB), applying 1 ms. Before memory was thinned to the followed person, day 13's changes and copying took 284 ms and 591 ms over 59 copies. + +**In off-screen Chrome, production builds, before (main) and after (this branch).** + +| | main | worker | +|---|---|---| +| 1 min/s | 58 fps, longest frame 169 ms | 60 fps, longest 17 ms | +| 1 day/s | 47 fps, p95 50 ms, longest 167 ms | 58 fps, p95 17 ms, longest 83 ms | +| 1 month/s, days 5 to 36 | 15–19 fps, longest 133 ms | 52–60 fps, longest 67 ms | +| 1 month/s past day 36 | 16 fps, p95 100 ms; 3.3 days a second | 54 fps, p95 33 ms; 2.9 days a second | +| Start to first view | 7.4 s | 12.2 s | + +Pause holds the clock, Step moves it one minute, and the console shows only the 404 that main shows too. + +**Findings.** The page is now smooth at every speed: frames no longer wait for the engine. The simulation itself is no faster. The specification expected roughly 4–5 days a second at 1 month/s, but the worker reached 2.9 against main's 3.3; an earlier reading of 4.9 came from a check script that read the clock from the wrong text and is discarded. The copies cost the worker about 5–7% past day 30, which does not account for the whole gap; the rest is unexplained and may be run-to-run spread, since each figure is one ten-second run. Reaching a month a second needs the engine about ten times faster at these days, which is a question of cheaper behaviour or a simpler model at map speeds, as the specification says. + +**Not settled.** Start takes about 5 s longer, because the loading card now waits for the worker to build its own valley, and the worker builds more slowly than the page. A new run from Settings started, but three seconds after Start its clock still read zero, consistent with the slower build; it was not watched until it played. + ## [LIFE15-Planning-068] - (2026-10-27) Update 067 left days 11 to 17 at 1.2–4.6 s each and ordinary days at about 200–400 ms. The owner approved a revised Life 15 specification that plans coarse routes through pieces of known ground. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cf9d776..bb68546 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -98,6 +98,8 @@ The 3D world draws each firm and Government across its plot: `buildingScale` str The page opens on `LifePage.tsx`, which shows the settings screen (`RunSettingsScreen.tsx`) until Start and then a `ValleyApp` for the run it built. `runSettings.ts` is pure: it turns the five run settings into a configuration, scaling the counts of places and landforms with the world's area, and returns the first thing wrong with them. A running `ValleyApp` never changes its settings; New run returns to the settings screen. `LifePage` keeps the loading card up until `ValleyApp` calls `onReady`, after the 3D view has drawn its first frame or failed to start. -The observer, `src/valleyView/`, keeps one state and a continuous displayed minute within the minute that state has reached. Every wake-up up to the drawn minute has run, and none after it, so each person is drawn from the task actually under way: position from `positionAt`, a gesture from the task's kind, energy from `energyAt`. Below a day per second people walk continuously. From a day per second up, people are hidden and the valley is drawn as a map of stocks, groups and huts. Each frame runs the engine in one step, which checks the 40 ms budget between wake-ups and always runs at least one wake-up minute. When the budget runs out first, the step ends at the last minute it ran, exactly as a step to that minute would, so the clock runs slower than asked rather than freezing the view; one copy of the valley a frame replaces the many a frame of short steps had needed. Plants and ground are drawn in 500 m tiles near the camera, and the followed forager's overlays are redrawn at most every 250 ms; each place's ring is draped on the ground once, since places and their radii never move. The panels refresh ten times a second, or twice a second at map speeds, and the history charts are drawn again only when a day ends, the followed forager changes or a run starts. Thickets, stands and outcrops are drawn as decoration: a fixed number of bushes, hazels, trees or rocks per place, sharing out the place's stock in turn, so what is drawn stays in proportion to what is there. The decoration uses no simulation stream. +The engine runs in a Web Worker, `engineWorker.ts`; `engineLink.ts` is the page's end of it. Both threads build the valley with the pure `createValley`, so the layout never crosses between them. The page keeps the clock and each frame asks the worker for a goal minute 0.1 s ahead at the speed shown; the worker runs towards it in slices of at most 50 ms and sends a view copy every stride (the speed over 60 minutes, at least one) and at the end of each slice. `viewCopy.ts` makes the view copy: only the routes of walks under way, each person's next wake-up in place of the queue, exchanges and walk records among the events, and current memory only for the followed person. A copy travels as its changes from the last copy sent (`changeOf`, `applyChange`), so parts the engine shared or recopied unchanged are not sent and keep their identity on the page. + +The observer, `src/valleyView/`, keeps the copies received and a continuous displayed minute (`advancePlayback` in `valleyViewModel.ts`). It draws the newest state at or before the clock, at a minute less than one minute after it, so every wake-up up to the drawn minute has run and none after it, and each person is drawn from the task actually under way: position from `positionAt`, a gesture from the task's kind, energy from `energyAt`. When the worker is behind, the clock waits within the newest state's minute, so a slow day stops the clock and not the page. Step shows the next minute once it arrives; a change of speed jumps to the newest copy. Below a day per second people walk continuously. From a day per second up, people are hidden and the valley is drawn as a map of stocks, groups and huts. Plants and ground are drawn in 500 m tiles near the camera, and the followed forager's overlays are redrawn at most every 250 ms; each place's ring is draped on the ground once, since places and their radii never move. The panels refresh ten times a second, or twice a second at map speeds, and the history charts are drawn again only when a day ends, the followed forager changes or a run starts. Thickets, stands and outcrops are drawn as decoration: a fixed number of bushes, hazels, trees or rocks per place, sharing out the place's stock in turn, so what is drawn stays in proportion to what is there. The decoration uses no simulation stream. The person panel shows body measurements and five trait bars; figures scale with height and weight. Recent exchange lines show kcal per kilogram and which party received the larger share. diff --git a/docs/LIFE15_SPEC.md b/docs/LIFE15_SPEC.md index d825b2e..cb1aebe 100644 --- a/docs/LIFE15_SPEC.md +++ b/docs/LIFE15_SPEC.md @@ -1,6 +1,6 @@ -# [LIFE15-Planning-068] +# [LIFE15-Worker-069] -**Revised and approved by the owner, 2026-10-27.** This specification replaced the Life 14 specification at update 066 and describes the whole simulation. It is step 15 of the [roadmap](ROADMAP.md), habitual routes, inserted before relationships, and is built under the [Life section](../SIMULATION_DESIGN_RULES.md#life-realism-and-time) of the design rules. Update 068 revises how a new route is planned, below, and is implemented as one pull request on top of update 067. +**Approved by the owner, 2026-10-28.** This specification replaced the Life 14 specification at update 066 and describes the whole simulation. It is step 15 of the [roadmap](ROADMAP.md), habitual routes, inserted before relationships, and is built under the [Life section](../SIMULATION_DESIGN_RULES.md#life-realism-and-time) of the design rules. Update 068 revised how a new route is planned. Update 069, below, moves the engine off the page's main thread; it changes only the observer. Forty strangers are dropped on 4 km square of young glacial land in Mesolithic northern Europe: drumlins, moraine fronts, kames, hummocks, kettle hollows and tunnel valleys, with lakes in the hollows and rivers running downhill to the edge. The ground is grass, dirt and stone. People discover drinking banks, drink, pick berries, gather hazelnuts, fish, gather firewood, meet, form groups, exchange wood and axes for food, and build huts around shared fires. Their knowledge comes from observation and memory. Each of them is a woman or a man with a body of their own and a personality of their own. From this step they find their way as people do: they remember the ways they walk, take them again, and plan afresh only for somewhere new, or now and then to notice a shortcut. @@ -17,6 +17,30 @@ Time is one clock in minutes. Nobody is stepped: a person is woken when their ta This step changes how people find and keep their way, and how often they look around. It does not change the map, the ground anyone may walk, walking speeds, the resources, bodies, personality or what people can do. +## Update 069: the engine in a worker thread + +**The problem.** The engine runs on the page's main thread, between frames, for up to 40 ms a frame. Drawing, the panels and the controls share that thread, so at high speeds the page manages about 16 frames a second, and a slow day (days 12 to 14 take 1.9–2.5 s) holds every frame it spans to the budget. At 1 month/s the page reaches 3.2 days a second, and the engine already takes about 70% of each second. + +**The change.** The engine runs in a worker thread with a state of its own. The main thread keeps the clock, draws, and handles the controls; it never runs `stepValley`. + +- **Building.** Both threads build the valley from the run's settings with `createValley`, which is pure, so they start from the same state. The layout (about 190 MB, mostly terrain) is never sent between them: copying it takes about 3 s. +- **Running.** Each frame the main thread advances its clock as before and tells the worker a whole minute to run to, the *goal*: the clock plus 0.1 s at the speed shown, so a state is already waiting at each minute the clock reaches. The worker runs towards the goal in slices of at most 50 ms, sends a view copy every *stride* minutes (the speed over 60, at least 1: about one copy a frame) and at the end of each slice, and reads new messages between slices, so a new goal or followed person takes effect within one slice. It never runs past the goal. +- **Drawing.** The main thread keeps the copies it has received and not yet passed. It draws the newest at or before the clock, at a minute less than one minute after it, so the rule is unchanged: every wake-up at or before the drawn minute has been processed, and none after it. When the worker is behind, the clock waits within the newest state's minute. People are drawn from the task records of the state drawn, as before. +- **Step, Pause and speed.** Step asks for the next whole minute and shows it once the worker has sent it. Paused, the worker still keeps its 0.1 s lead. On a change of speed the clock moves on to the newest copy received, so copies sent a stride apart for a fast speed are not shown at a slow one; what is skipped is at most 0.1 s at the old speed. +- **The view copy.** Copying the whole state takes 1.5–10 s past the first days, almost all of it in what the screen never reads: every route ever walked (27,000 by day 45, of which the screen needs the few under way), the engine's event records, and every person's memory: what they know of the ground, their ways, and their memory of places, banks, fish and people (together about 600 kB a copy on day 13), which the screen reads only for the person followed. The worker sends a copy that has: + - only the routes of walks under way; + - each person's next wake-up in place of the wake-up queue; + - only exchanges and walk records among the recent events; + - current memory only for the followed person; everyone else's memory is kept as the last copy held it, so it is not sent again, and what the main thread holds of it is stale and never read; + - everything else as in the engine's state. + + Only what has changed since the last copy is sent. A part that is the same object as in the last copy is skipped at once; the engine shares knowledge, ways, bank memory, routes, huts and finished days between states until they change. A part the engine recopied, as it does each person's small tables every step, is compared by content and skipped if equal. The main thread applies the changes to its previous copy, and unchanged parts keep their identity there. +- **New run, Settings.** A new run ends the worker and starts another. + +**Expected.** Frames no longer wait for the engine: at every speed the page draws as fast as the renderer allows, and a slow day stops the clock, not the page; camera, panels and controls stay responsive. The engine gets a whole core, less the cost of the copies, so 1 month/s was expected to rise from 3.2 to roughly 4–5 days a second. Measured, the page draws 52–60 frames a second at 1 month/s where it drew 15–19, but the engine still runs about 3 days a second (2.9 against 3.3 before, single runs). This update does not reach a month a second; that needs cheaper behaviour or a simpler model at map speeds, which are the owner's decisions for a later update. + +**Who notices.** Only the observer changes. The engine, every trajectory and every fingerprint stay the same, and a run stepped in the worker is identical to the same run stepped in a test. + ## Update 068: planning by pieces of known ground **The problem.** The owner's goal is a month a second, which needs the engine to run a simulated day in about 30 ms. After update 067 an ordinary day (20 to 45) takes about 190–410 ms, and days 11 to 17, when people are building huts and still exploring, take 1.2–4.6 s. Counted on the canonical run: @@ -402,7 +426,7 @@ Events are as Life 14; a walk's start records how it was found (`plan`: `way`, ` ## Observer -Label the page **Life 15 · strangers**. Everything else in the settings screen, loading card, header, history panel, group card, playback and landscape is as Life 14. +Label the page **Life 15 · strangers**. Everything else in the settings screen, loading card, header, history panel, group card, playback and landscape is as Life 14, except that from update 069 the engine runs in a worker thread and the page draws from view copies of its states, as described there. - **Ways.** When a person is followed, their remembered ways are drawn as faint lines on the ground, from the corridors pulled tight, the most recently used strongest; the current walk is drawn as before. - **Person panel.** Adds a "Ways" row ("Knows 23"), and the current walk says how it was found: "on a known way", "joining a known way" or "planning a new way". @@ -429,6 +453,8 @@ Bodies and traits (`nature.ts`), the terrain, hydrology and mesh (`terrain.ts`, Update 068 changes `routes.ts` only for behaviour: a person's pieces, worked out per chunk from knowledge and cached by knowledge like the known pieces of ground; the coarse A\* over pieces in place of chunks; the full search kept as the guard. `invariants.ts` rejects a `full` walk. The speed work that follows may touch any engine file, but none of it changes a result. The observer is unchanged. +Update 069 touches only `src/valleyView/`: a new `engineWorker.ts` that builds the valley, runs towards the goal in slices and posts view copies; a new `engineLink.ts`, the page's end of the worker, which starts it and turns the changes received into states; a new `viewCopy.ts` that makes a view copy, finds its changes from the last one in the worker, and applies them on the page; playback in `valleyViewModel.ts` (`advancePlayback`, `receiveState`, `stepPlayback`, `changeSpeed`) in place of stepping the engine within a frame budget, used by `ValleyApp.tsx`; and `LifePage.tsx` starting the worker before building the page's own valley, so the two builds run at once. The engine is unchanged. + ## Tests and implementation acceptance The Life 14 fingerprint suite passes before engine edits. Every trajectory changes, because reused ways and coarse plans give different paths and the survey rule changes what people know when: this step records new fingerprints for all its configurations. The founders, their bodies and traits stay the same as Life 14's on every fingerprint seed, because the code that draws them is untouched; `life13-founders.json` still checks starts and born skills. Fingerprints are not updated to conceal a failed rule. @@ -465,6 +491,8 @@ Life 14 fixtures, kept: **Update 068.** `fingerprints.test.ts` passes before the engine is changed. Planning by pieces changes every trajectory but the flat land's, so new fingerprints are recorded once for it; the founders, bodies and traits stay the same. Every speed-up after that leaves those new fingerprints unchanged, whole and in 15-minute slices. Measured once and recorded in the lab notes, on the canonical seed: the walks of each kind on days 5, 12, 13, 16 and 30, with no full walk; the median and largest excess of coarse plans over the shortest known path; each of the first 45 days' time in whole-day steps; profiles of days 13 and 30; and, in off-screen Chrome as in update 067, frames and days a second at 1 month/s past day 35. In the browser: a walk planned around a lake, and the console clean. +**Update 069.** The engine is unchanged, so every fingerprint stays the same. A few fast unit tests: applying the changes of a short run's states, one after another and copied as between threads, gives each state's view copy exactly, at strides from 1 to 1,440 minutes and across a change of the person followed; the copy keeps only the routes, wake-ups and events above, and current memory only for the person followed; a state the engine recopied unchanged sends nothing; and the playback rule never goes back, draws less than a minute after the state it draws from, asks no further ahead than the lead, runs at the speed shown when the engine keeps up, waits when it does not, and shows Step's minute once it arrives. Measured once and recorded in the lab notes, in off-screen Chrome as in update 067: frames a second at 1 min/s, 1 day/s and 1 month/s, the longest frame across days 12 to 14, and days a second at 1 month/s past day 35, before and after; and the time the copies take in the worker and on the main thread. In the browser: people walk smoothly at 1 min/s, the Step button and pause work, a new run from Settings starts cleanly, and the console is clean. + Final validation is `npm run agent:check`. Measured once at update 066 and recorded in the lab notes, on the canonical seed: the walks of each kind by day; the median and largest excess of way walks over the shortest known path; the share of new plans needing the full search; the year of forty's time and memory; and a profile of day 12 against update 065's. In the browser: a followed person's ways drawn, the panel's wording during a walk, 1 month/s against the 8 frames a second of update 065, and the console clean. ## Questions for later @@ -473,7 +501,8 @@ Final validation is `npm run agent:check`. Measured once at update 066 and recor - Is once a day the right pace for noticing a shortcut, and should it depend on openness? - Should ways be chosen by expected time, with slopes and ground, rather than distance? - Should the coarse level be landmarks (places, banks, the hearth) rather than pieces of squares of land? -- Should the engine run in a worker thread, so the view never waits for it and it gets a whole core rather than about half the main thread? That changes only the observer, and is the next step towards a month a second after update 068. +- After update 069, which reaches a month a second: people thinking less often (surveying and replanning less), or a simpler model of daily movement at map speeds? Both change what people do. +- Every route ever walked stays in the state, 27,000 by day 45. Should finished routes be dropped once no task or record refers to them? - A way is rechecked whenever a day has passed and the person has learnt anything, which after the first days is almost always. Should only new ground near the way count? - Do shared ways wear trails that make walking faster, and do trails gather people and places along them? - Should a person tell or show a way to someone they trust (steps 16 and 24)? diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 321de8f..545d205 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -118,7 +118,7 @@ Use `npm run agent:check` as the implementation gate. On memory-constrained mach `ValleyChecker` checks every interval that `stepValley` returns against the preceding immutable state, without running the engine again. `replay.ts` replays stocks, fish, bodies, tools, huts and water withdrawals from the recorded events and scheduled regrowth, and the checker compares the result with the returned state. It also checks positions and route segments against walkable, known mesh triangles, the order of wake-ups (world before people, no wake-up in the past), groups, hearths, fires and gifts, deaths and their causes, and observations against what could be seen. For ways it checks the count against `waysRemembered`, unique ends, ids and minutes, that each corridor holds its ends, has no gap and crosses only known ground, that walks on a way stay within its triangles, and that surveys happen exactly when the rule says. It also checks that nobody sets out on two leisure walks in a day and that `leisureMinute` matches the last one. Geography is checked once, including the mesh: winding, areas summing to the valley, mutual neighbours, shore edges parting ground from water, heights within `meshHeightToleranceCm` and the hydrology's shoreline within `shoreToleranceCm`. `invariants.test.ts` breaks one record at a time (fabricated or lost food, wood, logs, stones and tools; wrong body charges; wet or off-route positions; old queue entries; invalid groups) and expects the checker to catch it, after first checking that the untouched interval passes. -Rule tests use small explicit fixtures. A canonical thirty-day run is checked at daily intervals with all eight founders alive. Observer tests check that people are drawn on their recorded route at every displayed minute, that the drawn minute stays within the minute the state has reached, that a frame runs the engine until its budget is spent (at least one wake-up minute), stops the clock at the last minute run, and matches a step straight to that minute, and that map speeds hide people. +Rule tests use small explicit fixtures. A canonical thirty-day run is checked at daily intervals with all eight founders alive. Observer tests check that people are drawn on their recorded route at every displayed minute, that the drawn minute stays within the minute the state has reached, that the playback clock never goes back, asks no further ahead than its 0.1 s lead, runs at the speed shown when the engine keeps up and waits when it does not, that Step's minute is shown once it arrives, and that map speeds hide people. `viewCopy.test.ts` rebuilds each state's view copy from its changes alone, copied as between threads, at strides from 1 to 1,440 minutes and across a change of the person followed; checks that a copy keeps only the routes under way, each person's next wake-up, exchanges and walk records, and current memory only for the person followed; and that a state the engine recopied unchanged sends nothing. The worker leaves the engine unchanged, so update 069 keeps every fingerprint. The 22 fingerprints are checked thirty-day runs, partitioned by configuration for parallel validation: three seeds each for the eight-person canonical, together, no-practice, craft-talent, equal-skill and flat configurations and the twelve-person one, and one run of the forty-founder default on seed 20260813 (about three to four minutes). Life 14 fingerprints passed before the engine changed. Life 15 re-records all 22 after the rule and checker tests pass, because remembered ways and fewer surveys change routes and so trajectories. A refactor or speed-up must leave them all unchanged. `runSettings.test.ts` checks the page's ranges, including 7 and 366 days rejected, and that a 1 km world can be laid out. diff --git a/src/valleyView/LifePage.tsx b/src/valleyView/LifePage.tsx index b81c3ee..840bff0 100644 --- a/src/valleyView/LifePage.tsx +++ b/src/valleyView/LifePage.tsx @@ -3,7 +3,7 @@ import { createValley } from '../valley/engine' import { RunSettingsScreen } from './RunSettingsScreen' import { configOfSettings, defaultRunSettings, runSettingsError, type RunSettings } from './runSettings' import ValleyApp from './ValleyApp' -import { startDisplay, type Display } from './valleyViewModel' +import { startEngine, type EngineLink } from './engineLink' /** Runs `work` after the browser has painted, so a loading screen shown just before it is on screen meanwhile. */ const afterPaint = (work: () => void) => requestAnimationFrame(() => setTimeout(work, 0)) @@ -11,7 +11,7 @@ const afterPaint = (work: () => void) => requestAnimationFrame(() => setTimeout( /** The Life page: the settings screen until Start, then the run those settings began. */ export default function LifePage() { const [settings, setSettings] = useState(defaultRunSettings) - const [start, setStart] = useState(null) + const [start, setStart] = useState(null) const [error, setError] = useState(null) const [loading, setLoading] = useState(false) @@ -26,7 +26,10 @@ export default function LifePage() { const problem = runSettingsError(next) setError(problem) if (!problem) { - setStart(startDisplay(createValley(configOfSettings(next)))) + // The engine's thread builds its own valley meanwhile. + const config = configOfSettings(next) + const connect = startEngine(config) + setStart(connect(createValley(config))) started = true } } finally { @@ -39,7 +42,14 @@ export default function LifePage() { return ( <> {start ? ( - setStart(null)} onReady={ready} /> + { + start.stop() + setStart(null) + }} + onReady={ready} + /> ) : ( )} diff --git a/src/valleyView/ValleyApp.tsx b/src/valleyView/ValleyApp.tsx index 32ab7df..3dcd66b 100644 --- a/src/valleyView/ValleyApp.tsx +++ b/src/valleyView/ValleyApp.tsx @@ -8,8 +8,10 @@ import { palette } from '../ui/theme' import { isDaylight } from '../valley/forager' import type { ValleyState } from '../valley/types' import { createValleyScene, type ValleyPick, type ValleyScene, type ValleySelection } from './valleyScene' +import type { EngineLink } from './engineLink' import { - advanceDisplay, + advancePlayback, + changeSpeed, aliveCount, clearView, calendarLabel, @@ -37,13 +39,18 @@ import { stoneInspection, specializationPoints, thirstLevel, - stepDisplay, + receiveState, + startDisplay, + startPlayback, stepFollowed, + stepPlayback, + strideOf, taskSummary, TERMS_COLORS, VALLEY_SPEEDS, type ClearView, type Display, + type Playback, } from './valleyViewModel' /** What the HUD shows, refreshed a few times a second rather than every frame. */ @@ -119,22 +126,23 @@ const fireLabel = (fire: { lit: boolean; wood: number; nights: number }, dayligh `${fire.lit ? 'burning' : daylight && fire.wood > 0 ? 'banked for the night' : 'out'}, ${formatKg(fire.wood)} of wood${fire.wood ? ` (${fire.nights.toFixed(1)} nights)` : ''}` /** - * Plays the run that `start` begins; its settings are fixed, and `onNewRun` leaves it for the settings screen. + * Plays the run that `engine` runs; its settings are fixed, and `onNewRun` leaves it for the settings screen. * `onReady` is called once the valley's first frame is drawn, or the 3D view has failed to start. */ export default function ValleyApp({ - start, + engine, onNewRun, onReady, }: { - start: Display + engine: EngineLink onNewRun: () => void onReady: () => void }) { const mountRef = useRef(null) const sceneRef = useRef(null) - const [initialPair] = useState(start) + const [initialPair] = useState(() => startDisplay(engine.first)) const pairRef = useRef(initialPair) + const playbackRef = useRef(startPlayback(engine.first)) const [running, setRunning] = useState(true) const [showFlow, setShowFlow] = useState(false) const flowRef = useRef(false) @@ -149,6 +157,7 @@ export default function ValleyApp({ const [historyOpen, setHistoryOpen] = useState(() => window.matchMedia?.('(min-width: 721px)').matches ?? true) const aboutRef = useRef(null) const readyRef = useRef(onReady) + const engineRef = useRef(engine) useEffect(() => { readyRef.current = onReady }, [onReady]) @@ -166,6 +175,7 @@ export default function ValleyApp({ useEffect(() => { runningRef.current = running flowRef.current = showFlow + if (speedRef.current !== VALLEY_SPEEDS[speedIndex]) playbackRef.current = changeSpeed(playbackRef.current) speedRef.current = VALLEY_SPEEDS[speedIndex]! selectedRef.current = selected highlightedRef.current = highlightedId @@ -173,6 +183,12 @@ export default function ValleyApp({ followingRef.current = following }, [running, speedIndex, selected, highlightedId, followedId, following, showFlow]) + useEffect(() => { + return engine.listen((state) => { + playbackRef.current = receiveState(playbackRef.current, state) + }) + }, [engine]) + useEffect(() => { const mount = mountRef.current if (!mount) return @@ -181,6 +197,7 @@ export default function ValleyApp({ let lastFrame = performance.now() let lastHud = 0 let rate = { atMs: performance.now(), minute: pairRef.current.minute, perSecond: 0 } + let asked = { goal: -1, stride: 0, followedId: -1 } const onPick = (pick: ValleyPick | null) => { if (pick?.kind === 'forager') { followedRef.current = pick.id @@ -210,7 +227,16 @@ export default function ValleyApp({ const elapsed = (now - lastFrame) / 1000 lastFrame = now const speed = speedRef.current - if (runningRef.current) pairRef.current = advanceDisplay(pairRef.current, elapsed, speed) + const advanced = advancePlayback(playbackRef.current, elapsed, speed, runningRef.current) + playbackRef.current = advanced.playback + pairRef.current = advanced.display + const goal = advanced.playback.goal, + stride = strideOf(speed), + followed = followedRef.current + if (goal !== asked.goal || stride !== asked.stride || followed !== asked.followedId) { + asked = { goal, stride, followedId: followed } + engineRef.current.ask(goal, stride, followed) + } scene.draw(pairRef.current, { showFlow: flowRef.current, drawPeople: !speed.map, @@ -223,7 +249,8 @@ export default function ValleyApp({ }) if (!drawn) { drawn = true - readyRef.current() + // The loading card stays until the engine's thread has built its valley too. + void engineRef.current.ready.then(() => readyRef.current()) } if (now - lastHud >= (speed.map ? MAP_HUD_INTERVAL_MS : HUD_INTERVAL_MS)) { lastHud = now @@ -279,10 +306,9 @@ export default function ValleyApp({ sceneRef.current?.showGroup(id, clear) }) - /** Finishes the minute in progress, then shows the next one from its start. */ + /** Finishes the minute in progress, then shows the next one from its start once the engine has run it. */ const stepMinute = useCallback(() => { - pairRef.current = stepDisplay(pairRef.current) - setSnapshot(snap(pairRef.current, followedRef.current)) + playbackRef.current = stepPlayback(playbackRef.current) }, []) useEffect(() => { diff --git a/src/valleyView/engineLink.ts b/src/valleyView/engineLink.ts new file mode 100644 index 0000000..5b69a52 --- /dev/null +++ b/src/valleyView/engineLink.ts @@ -0,0 +1,68 @@ +import type { ValleyConfig, ValleyState } from '../valley/types' +import { applyChange, stateOf, wireOf, type Change, type Wire } from './viewCopy' + +/** From the page to the engine's thread. */ +export type PageMessage = + { kind: 'start'; config: Partial } | { kind: 'goal'; goal: number; stride: number; followedId: number } +/** From the engine's thread to the page. */ +export type EngineMessage = + { kind: 'ready' } | { kind: 'state'; change: Change | null } | { kind: 'error'; message: string } + +/** The page's end of the engine's thread: it sends goals, and turns the copies received into states. */ +export interface EngineLink { + /** The first state, taken from the page's own build as the engine's thread takes it from its own. */ + first: ValleyState + /** Settles once the engine's thread has built its valley. */ + ready: Promise + /** Asks the engine to run to `goal`, sending a state every `stride` minutes, with `followedId`'s memory current. */ + ask(goal: number, stride: number, followedId: number): void + /** Calls `take` with each state the engine sends, in order, until the returned function is called. */ + listen(take: (state: ValleyState) => void): () => void + stop(): void +} + +/** + * Starts the engine's thread on `config`. `start` is the page's own build of the same valley, from which the first + * copy is taken; the engine's thread builds its own, and the two are equal because building is pure. + */ +export function startEngine(config: Partial): (start: ValleyState) => EngineLink { + const worker = new Worker(new URL('./engineWorker.ts', import.meta.url), { type: 'module' }) + const post = (message: PageMessage) => worker.postMessage(message) + post({ kind: 'start', config }) + let wire: Wire | null = null + let built = () => {} + const pending: (Change | null)[] = [] + let listener: (state: ValleyState) => void = () => {} + const link: EngineLink = { + first: null!, + ready: new Promise((resolve) => (built = resolve)), + listen: (take) => { + listener = take + return () => { + if (listener === take) listener = () => {} + } + }, + ask: (goal, stride, followedId) => post({ kind: 'goal', goal, stride, followedId }), + stop: () => worker.terminate(), + } + const take = (change: Change | null) => { + wire = applyChange(wire!, change) + listener(stateOf(wire)) + } + worker.addEventListener('message', (event: MessageEvent) => { + const message = event.data + if (message.kind === 'ready') built() + else if (message.kind === 'error') { + console.error(`The engine stopped: ${message.message}`) + built() + } else if (wire) take(message.change) + else pending.push(message.change) + }) + worker.addEventListener('error', (event) => console.error('The engine stopped:', event.message)) + return (start) => { + wire = wireOf(start, 0) + link.first = stateOf(wire) + for (const change of pending.splice(0)) take(change) + return link + } +} diff --git a/src/valleyView/engineWorker.ts b/src/valleyView/engineWorker.ts new file mode 100644 index 0000000..66f76ce --- /dev/null +++ b/src/valleyView/engineWorker.ts @@ -0,0 +1,80 @@ +/// +import { createValley, stepValley } from '../valley/engine' +import type { ValleyConfig, ValleyState } from '../valley/types' +import { changeOf, wireOf, type Wire } from './viewCopy' +import type { EngineMessage, PageMessage } from './engineLink' + +/** + * The engine's thread. It builds the valley from the run's settings, as the page does, then runs towards the goal the + * page last gave in slices of at most `SLICE_MS`, sending a view copy every `stride` minutes and at the end of each + * slice. Messages are read between slices, so a new goal or followed person takes effect within one. + */ +const SLICE_MS = 50 + +let state: ValleyState | null = null +/** The last copy sent, which the page also holds. */ +let sent: Wire | null = null +let goal = 0 +let stride = 1 +let followedId = 0 +let running = false + +const post = (message: EngineMessage) => postMessage(message) + +function send() { + const wire = wireOf(state!, followedId, sent) + post({ kind: 'state', change: changeOf(wire, sent) }) + sent = wire +} + +function run() { + running = false + if (!state) return + const started = performance.now() + try { + while (state.minute < goal) { + const before = state.minute + state = stepValley(state, Math.min(goal, before + stride), () => performance.now() - started >= SLICE_MS) + send() + if (performance.now() - started >= SLICE_MS) break + } + } catch (error) { + post({ kind: 'error', message: error instanceof Error ? error.message : String(error) }) + return + } + if (state.minute < goal) schedule() +} + +/** Runs again once waiting messages are read. */ +function schedule() { + if (running) return + running = true + setTimeout(run, 0) +} + +function start(config: Partial) { + state = createValley(config) + sent = wireOf(state, followedId) + goal = Math.max(goal, state.minute) + post({ kind: 'ready' }) + schedule() +} + +onmessage = (event: MessageEvent) => { + const message = event.data + if (message.kind === 'start') { + try { + start(message.config) + } catch (error) { + post({ kind: 'error', message: error instanceof Error ? error.message : String(error) }) + } + return + } + const followed = message.followedId !== followedId + goal = Math.max(goal, message.goal) + stride = message.stride + followedId = message.followedId + if (!state) return + if (followed) send() + schedule() +} diff --git a/src/valleyView/playback.test.ts b/src/valleyView/playback.test.ts index 0912e01..2ad6289 100644 --- a/src/valleyView/playback.test.ts +++ b/src/valleyView/playback.test.ts @@ -3,16 +3,43 @@ import { FLAT_LAND } from '../valley/config' import { stepValley } from '../valley/engine' import { createSurveyedValley } from '../valley/ruleFixtures' import { - advanceDisplay, + advancePlayback, + changeSpeed, foragerPose, + LEAD_SECONDS, mapSpeedMinutesPerSecond, + receiveState, routePoints, - startDisplay, + startPlayback, + stepPlayback, + strideOf, VALLEY_SPEEDS, - type Display, + type Playback, + type ValleySpeed, } from './valleyViewModel' +import type { ValleyState } from '../valley/types' -const start = () => startDisplay(createSurveyedValley({ ...FLAT_LAND, founders: 2 })) +const first = () => createSurveyedValley({ ...FLAT_LAND, founders: 2 }) + +/** The engine's thread, answering at once: it runs to the goal, sending a state every `stride` minutes. */ +function answer(playback: Playback, engine: { state: ValleyState }, stride: number) { + while (engine.state.minute < playback.goal) { + engine.state = stepValley(engine.state, Math.min(playback.goal, engine.state.minute + stride)) + playback = receiveState(playback, engine.state) + } + return playback +} + +/** Plays frames of `elapsed` seconds at `speed`, as the page does, with an engine that keeps up. */ +function* play(state: ValleyState, speed: Pick, frames: Iterable) { + const engine = { state } + let playback = startPlayback(state) + for (const elapsed of frames) { + const advanced = advancePlayback(playback, elapsed, speed, true) + playback = answer(advanced.playback, engine, strideOf(speed)) + yield { display: advanced.display, playback: advanced.playback } + } +} /** The distance from `point` to the nearest segment of the polyline `points`. */ function distanceToPath(point: { x: number; y: number }, points: readonly { x: number; y: number }[]) { @@ -30,22 +57,32 @@ function distanceToPath(point: { x: number; y: number }, points: readonly { x: n } describe('drawing people from task records', () => { - it('draws within the minute the state has reached, and never goes back', () => { - let display: Display = start() - for (const elapsed of [0.016, 0.1, 0.25, 3, 0.033, 0.2]) { - const before = display.minute - display = advanceDisplay(display, elapsed, { minutesPerSecond: 10 }) - expect(display.minute).toBeGreaterThanOrEqual(before) - expect(display.state.minute).toBe(Math.floor(display.minute)) + it('draws within the minute after the state drawn, never goes back, and asks only the lead ahead', () => { + for (const minutesPerSecond of [10, 60, 1_440]) { + let before = 0 + for (const { display, playback } of play( + first(), + { minutesPerSecond }, + [0.016, 0.1, 0.25, 3, 0.033, 0.2, 0.016], + )) { + expect(display.minute).toBeGreaterThanOrEqual(before) + expect(display.state.minute).toBeLessThanOrEqual(display.minute) + expect(display.minute).toBeLessThan(display.state.minute + 1) + expect(playback.goal).toBeLessThanOrEqual(Math.floor(playback.clock + LEAD_SECONDS * minutesPerSecond)) + before = display.minute + } + // With an engine that keeps up and frames at 60 a second, the clock runs at the speed shown. + // Only the first frame, before the engine has run ahead, waits within the first minute. + const frames = [...play(first(), { minutesPerSecond }, Array(61).fill(1 / 60))] + expect(frames.at(-1)!.playback.clock - frames[0]!.playback.clock).toBeCloseTo(minutesPerSecond, 2) } }) it('positions lie on the recorded route at every displayed minute', () => { - let display: Display = start() let walked = 0 - for (let frame = 0; frame < 6_000 && walked < 40; frame += 1) { - // Three-tenths of a minute a frame, from midnight through the first morning's walks. - display = advanceDisplay(display, 0.1, { minutesPerSecond: 3 }) + // Three-tenths of a minute a frame, from midnight through the first morning's walks. + for (const { display } of play(first(), { minutesPerSecond: 3 }, Array(6_000).fill(0.1))) { + if (walked >= 40) break for (const id of [0, 1]) { const task = display.state.foragers[id]!.task if (task?.kind !== 'walk' || display.minute < task.startMinute) continue @@ -57,35 +94,30 @@ describe('drawing people from task records', () => { expect(walked).toBeGreaterThan(0) }) - it('runs the engine until the frame budget is spent, and at least one wake-up minute a frame', () => { - const ticking = (ms: number) => { - let t = 0 - return () => (t += ms) - } - const first = start() - const wakeUpsTo = (minute: number) => stepValley(first.state, minute).totals.wakeUps - // Each clock reading is 100 ms later, past the budget at once: the frame runs only the first wake-up minute after - // the one it starts at. - let display: Display = advanceDisplay(first, 0.25, { minutesPerSecond: 1_440 }, 40, ticking(100)) - expect(display.minute).toBeGreaterThan(first.minute) - // Wake-ups due at the starting minute itself run in the next step. - expect(wakeUpsTo(display.minute - 1)).toBe(wakeUpsTo(first.minute + 1)) - expect(display.state.minute).toBe(display.minute) - // Each reading is 10 ms later: the step stops between wake-ups, short of the minute wanted. - const before = display.minute - display = advanceDisplay(display, 0.25, { minutesPerSecond: 1_440 }, 40, ticking(10)) - expect(display.minute).toBeGreaterThan(before) - expect(display.minute).toBeLessThan(before + 360) - expect(display.state.minute).toBe(display.minute) - // With time to spare, the frame reaches the minute wanted, and matches a step there in one go. - const reached = display.minute - display = advanceDisplay(display, 0.1, { minutesPerSecond: 1_440 }, 40, ticking(0)) - expect(display.minute).toBeCloseTo(reached + 144) - expect(display.state.minute).toBe(Math.floor(display.minute)) - const direct = stepValley(first.state, display.state.minute) - expect(display.state.foragers.map((p) => [p.x, p.y, p.energyKcal])).toEqual( - direct.foragers.map((p) => [p.x, p.y, p.energyKcal]), - ) + it('waits within the newest state while the engine is behind, and steps once it has run', () => { + const state = first() + let playback = startPlayback(state) + // No answer: the clock stops short of the next minute. + for (let frame = 0; frame < 10; frame++) + playback = advancePlayback(playback, 0.25, { minutesPerSecond: 60 }, true).playback + expect(playback.clock).toBeLessThan(state.minute + 1) + expect(playback.goal).toBeGreaterThan(state.minute) + const engine = { state } + playback = answer(playback, engine, 1) + const { playback: moved, display } = advancePlayback(playback, 0.1, { minutesPerSecond: 60 }, true) + expect(display.state.minute).toBeGreaterThan(state.minute) + // Paused, Step shows the next minute only once the engine sends it. + let paused = stepPlayback(moved) + const wanted = paused.stepTo! + expect(paused.goal).toBeGreaterThanOrEqual(wanted) + paused = answer(paused, engine, 1) + const stepped = advancePlayback(paused, 1, { minutesPerSecond: 60 }, false) + expect(stepped.display.minute).toBe(wanted) + expect(stepped.display.state.minute).toBe(wanted) + // A new speed moves the clock on to the newest state, dropping those sent apart for the old one. + const changed = changeSpeed(receiveState(stepped.playback, stepValley(engine.state, engine.state.minute + 30))) + expect(changed.states).toHaveLength(1) + expect(changed.clock).toBe(changed.states[0]!.minute) }) it('stops drawing people from map speeds up', () => { diff --git a/src/valleyView/valleyViewModel.ts b/src/valleyView/valleyViewModel.ts index 334402f..d614a7d 100644 --- a/src/valleyView/valleyViewModel.ts +++ b/src/valleyView/valleyViewModel.ts @@ -5,7 +5,6 @@ import { dayOfYear, MINUTES_PER_DAY, seasonOf, yearOf, yearsToDays } from '../va import { carriedByFood, carriedKcal, spoilsIn } from '../valley/food' import { mixSeed, randomDraw } from '../sim/rng' import { ringOf, fishCapacityKcal } from '../valley/config' -import { stepValley } from '../valley/engine' import { campfireBurn } from '../valley/fire' import { isDaylight, loadKg, loadOf, speedForLoad } from '../valley/forager' import { hutOf, hutWhole, weathersOn } from '../valley/huts' @@ -26,8 +25,8 @@ export { clockLabel, daylightAt, foragerName, formatKcal, sunAt, TERMS_COLORS } export { foragerColor, formatHours } /** - * The simulation advances from wake-up to wake-up; the display does not. It keeps the state of the last `stepValley` - * and a continuous minute less than one minute after it, and draws each person from their task record at that minute. + * The simulation advances from wake-up to wake-up; the display does not. It keeps a state the engine sent and a + * continuous minute less than one minute after it, and draws each person from their task record at that minute. * Every wake-up at or before the drawn minute has been processed, and none after it, so the task drawn is the task under * way. */ @@ -68,36 +67,89 @@ export const DEFAULT_SPEED_INDEX = 0 export const MAX_FRAME_SECONDS = 0.25 /** - * High speeds are best effort: the engine gets about this long a frame, so the controls and renderer can run. At map - * speeds no people are drawn, so a slower frame rate is acceptable. + * The engine, in a worker, runs this far ahead of the clock, in wall seconds at the speed shown, so a state is waiting + * at each whole minute the clock reaches. */ -export const SIMULATION_FRAME_BUDGET_MS = 40 +export const LEAD_SECONDS = 0.1 + +/** How many minutes apart the engine sends states: about one a frame at 60 frames a second, and at least one a minute. */ +export const strideOf = (speed: Pick) => + Math.max(1, Math.floor(speed.minutesPerSecond / 60)) /** - * Advances the displayed minute by the wall time elapsed at `speed`, running the engine up to the last whole minute at - * or before it. The engine checks the budget between wake-ups, so one step a frame suffices: copying the valley for - * each of many short steps had cost more than the wake-ups themselves at high speeds. When the engine cannot keep up - * within `budgetMs`, it stops at the last minute it ran, and the clock advances less. + * Playback from states the engine sends. `states` are those received and not yet passed, oldest first; the first is + * the one drawn, and is at or before the clock. The engine is asked to run to `goal`, and never runs past it. */ -export function advanceDisplay( - display: Display, +export interface Playback { + states: ValleyState[] + /** The minute the clock shows, continuously. */ + clock: number + goal: number + /** A minute the Step button asked for and not yet shown, or null. */ + stepTo: number | null +} + +export const startPlayback = (state: ValleyState): Playback => ({ + states: [state], + clock: state.minute, + goal: state.minute, + stepTo: null, +}) + +/** Takes a state from the engine. A state at the newest minute replaces it (a copy with another person's memory). */ +export function receiveState(playback: Playback, state: ValleyState): Playback { + const states = playback.states.filter((s) => s.minute < state.minute) + return { ...playback, states: states.length ? [...states, state] : [state] } +} + +/** Less than a minute: a state is drawn up to its minute plus this. */ +const WITHIN_MINUTE = 1 - 1 / 1024 + +/** + * Advances the clock by the wall time elapsed at `speed` while running, and asks the engine to run `LEAD_SECONDS` + * ahead. When the engine has not reached the clock's whole minute, the clock waits within the newest state's minute. + * The state drawn is the newest at or before the clock, and the minute drawn is less than one minute after it. + */ +export function advancePlayback( + playback: Playback, elapsedSeconds: number, speed: Pick, - budgetMs = SIMULATION_FRAME_BUDGET_MS, - now: () => number = () => performance.now(), -): Display { - const target = display.minute + Math.min(MAX_FRAME_SECONDS, Math.max(0, elapsedSeconds)) * speed.minutesPerSecond - const toMinute = Math.floor(target) - if (toMinute <= display.state.minute) return { state: display.state, minute: target } - const started = now() - const state = stepValley(display.state, toMinute, () => now() - started >= budgetMs) - return { state, minute: state.minute < toMinute ? state.minute : target } -} - -/** Runs the engine to the next whole minute and shows it. */ -export function stepDisplay(display: Display): Display { - const state = stepValley(display.state, Math.floor(display.minute) + 1) - return { ...display, state, minute: state.minute } + running: boolean, +): { playback: Playback; display: Display } { + const newest = playback.states.at(-1)! + let { clock, goal, stepTo } = playback + if (stepTo !== null && newest.minute >= stepTo) { + clock = Math.max(clock, stepTo) + stepTo = null + } + if (running) { + const target = clock + Math.min(MAX_FRAME_SECONDS, Math.max(0, elapsedSeconds)) * speed.minutesPerSecond + clock = Math.max(clock, Math.min(target, newest.minute + WITHIN_MINUTE)) + } + // Paused too, so playing on finds the states ahead already sent. + goal = Math.max(goal, Math.floor(clock + LEAD_SECONDS * speed.minutesPerSecond)) + const states = [...playback.states] + while (states.length > 1 && states[1]!.minute <= clock) states.shift() + const state = states[0]! + return { + playback: { states, clock, goal, stepTo }, + display: { state, minute: Math.max(state.minute, Math.min(clock, state.minute + WITHIN_MINUTE)) }, + } +} + +/** Shows the next whole minute once the engine has run it. */ +export function stepPlayback(playback: Playback): Playback { + const stepTo = Math.floor(playback.clock) + 1 + return { ...playback, stepTo, goal: Math.max(playback.goal, stepTo) } +} + +/** + * On a change of speed the clock moves on to the newest state, so the states sent apart for the old speed are not + * shown at the new one; what is skipped is at most `LEAD_SECONDS` at the old speed. + */ +export function changeSpeed(playback: Playback): Playback { + const newest = playback.states.at(-1)! + return { ...playback, states: [newest], clock: Math.max(playback.clock, newest.minute) } } /** Minutes since midnight of day 0, continuously. */ diff --git a/src/valleyView/viewCopy.test.ts b/src/valleyView/viewCopy.test.ts new file mode 100644 index 0000000..ce3bf60 --- /dev/null +++ b/src/valleyView/viewCopy.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { FLAT_LAND } from '../valley/config' +import { cloneValley, stepValley } from '../valley/engine' +import { createSurveyedValley } from '../valley/ruleFixtures' +import { applyChange, changeOf, stateOf, wireOf, type Wire } from './viewCopy' + +/** What crosses between threads: a copy that shares nothing with the engine's objects. The layout is built on both sides. */ +const across = (wire: Wire): Wire => ({ ...structuredClone({ ...wire, layout: null }), layout: wire.layout }) + +describe('view copies', () => { + it('rebuilds each state’s view copy on the page from the changes alone', () => { + let state = createSurveyedValley(FLAT_LAND) + let sent = wireOf(state, 0) + let page = across(sent) + let followed = 0 + // Strides as at each speed, and a change of the person followed part-way. + for (const stride of [1, 1, 7, 60, 1, 300, 24, 900, 1, 1_440, 61]) { + state = stepValley(state, state.minute + stride) + if (stride === 300) followed = 3 + const wire = wireOf(state, followed, sent) + page = applyChange(page, structuredClone(changeOf(wire, sent))) + sent = wire + expect({ ...page, layout: null }).toEqual({ ...wire, layout: null }) + } + expect(state.minute).toBeGreaterThan(2_700) + expect(page.layout).toBe(sent.layout) + }) + + it('keeps only what the page reads', () => { + const earlier = stepValley(createSurveyedValley(FLAT_LAND), 1_440) + const last = wireOf(earlier, 2) + const state = stepValley(earlier, 2 * 1_440) + const wire = wireOf(state, 2, last) + const inUse = state.foragers.map((p) => p.task?.routeId ?? -1).filter((id) => id >= 0) + expect(Object.keys(wire.routes).map(Number).sort()).toEqual([...new Set(inUse)].sort()) + expect(state.routes.length).toBeGreaterThan(inUse.length) + for (const p of state.foragers) { + expect(wire.queue[p.id]).toEqual(state.queue.entriesOf(p.id)[0] ?? null) + expect(stateOf(wire).queue.entriesOf(p.id)[0] ?? null).toEqual(wire.queue[p.id]) + // Memory is current for the person followed, and as the last copy held it for everyone else. + const memory = p.id === 2 ? p : earlier.foragers[p.id]! + for (const key of ['knowledge', 'ways', 'knownPlaces', 'placeStock'] as const) + expect(wire.foragers[p.id]![key]).toBe(memory[key]) + } + const moved = (p: (typeof state.foragers)[number]) => + (['knowledge', 'ways', 'knownPlaces', 'placeStock'] as const).some( + (key) => p[key] !== earlier.foragers[p.id]![key], + ) + expect(state.foragers.some((p) => p.id !== 2 && moved(p))).toBe(true) + expect(wire.eventDays.flat().every((e) => e.kind === 'exchange' || e.kind === 'walk')).toBe(true) + expect(wire.eventDays.flat().some((e) => e.kind === 'walk')).toBe(true) + expect(wire.lastInterval.every((e) => e.kind === 'exchange')).toBe(true) + }) + + it('sends nothing for a state the engine recopied unchanged', () => { + const state = stepValley(createSurveyedValley(FLAT_LAND), 600) + expect(changeOf(wireOf(cloneValley(state), 0), wireOf(state, 0))).toBeNull() + }) +}) diff --git a/src/valleyView/viewCopy.ts b/src/valleyView/viewCopy.ts new file mode 100644 index 0000000..1bb1415 --- /dev/null +++ b/src/valleyView/viewCopy.ts @@ -0,0 +1,163 @@ +import { WakeQueue, type WakeEntry } from '../valley/clock' +import type { Route } from '../valley/routes' +import type { Forager, ValleyEvent, ValleyState } from '../valley/types' + +/** + * The engine runs in a worker, and the page draws from view copies of its states. A view copy holds what the page + * reads: the state as the engine left it, less what the page never reads and would cost seconds to copy between + * threads. Only the routes of tasks under way, each person's next wake-up in place of the wake-up queue, exchanges + * and walk records among the events, and the followed person's memory are kept up to date. + * + * Between threads a copy travels as its changes from the last copy sent, which both sides keep. The worker sends + * a `Change`; the page applies it to its own last copy. Parts the engine left alone, or recopied unchanged, are not + * sent, and keep their identity on the page. + */ + +/** A view copy as it travels: the wake-up queue is a list of each person's next wake-up. */ +export type Wire = Omit & { queue: (WakeEntry | null)[] } + +/** + * A person's memory, which the page reads only for the person followed. For anyone else a copy keeps the memory the + * last copy held, so it is not resent; what the page holds of it is stale, and never read. + */ +const MEMORY = [ + 'knowledge', + 'ways', + 'knownBanks', + 'knownPlaces', + 'placeCheckedMinute', + 'placeStock', + 'placeWood', + 'placeLogs', + 'fishMemory', + 'metPosition', +] as const satisfies readonly (keyof Forager)[] + +function viewForager(person: Forager, followedId: number, last: Forager | undefined): Forager { + if (person.id === followedId || !last) return person + const kept: Partial = {} + for (const key of MEMORY) if (person[key] !== last[key]) Object.assign(kept, { [key]: last[key] }) + return Object.keys(kept).length ? { ...person, ...kept } : person +} + +const VIEW_EVENTS = new Set(['exchange', 'walk']) +/** Finished days never change, so each is filtered once. */ +const filteredDays = new WeakMap() +const viewEvents = (events: ValleyEvent[]) => events.filter((e) => VIEW_EVENTS.has(e.kind)) +function viewDay(events: ValleyEvent[], finished: boolean) { + if (!finished) return viewEvents(events) + let filtered = filteredDays.get(events) + if (!filtered) filteredDays.set(events, (filtered = viewEvents(events))) + return filtered +} + +/** The view copy of `state`, with `followedId`'s memory and everyone else's from `previous`, the copy before. */ +export function wireOf(state: ValleyState, followedId: number, previous: Wire | null = null): Wire { + const routes: Route[] = [] + for (const person of state.foragers) { + const id = person.task?.routeId ?? -1 + if (id >= 0) routes[id] = state.routes[id]! + } + const last = state.eventDays.length - 1 + return { + ...state, + queue: state.foragers.map((person) => state.queue.entriesOf(person.id)[0] ?? null), + routes, + lastInterval: state.lastInterval.filter((e) => e.kind === 'exchange'), + eventDays: state.eventDays.map((day, index) => viewDay(day, index < last)), + foragers: state.foragers.map((person) => viewForager(person, followedId, previous?.foragers[person.id])), + } +} + +/** The page's state from a copy: its wake-up queue holds each person's next wake-up. */ +const states = new WeakMap() +export function stateOf(wire: Wire): ValleyState { + let state = states.get(wire) + if (!state) { + const queue = new WakeQueue() + for (const entry of wire.queue) if (entry) queue.schedule(entry) + states.set(wire, (state = { ...wire, queue })) + } + return state +} + +/** + * How a value differs from the last one sent: `v` replaces it whole; `p` changes some of its keys (`n`, an array's new + * length; `d`, keys an object lost). A key missing from `p` is unchanged. + */ +export type Change = { v: unknown } | { p: Record; n?: number; d?: string[] } + +const isPlain = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') return false + const proto = Object.getPrototypeOf(value) + return proto === Object.prototype || proto === null +} + +function sameView(a: ArrayBufferView, b: ArrayBufferView) { + if (a.constructor !== b.constructor || a.byteLength !== b.byteLength) return false + const x = new Uint8Array(a.buffer, a.byteOffset, a.byteLength), + y = new Uint8Array(b.buffer, b.byteOffset, b.byteLength) + for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false + return true +} + +function sameMap(a: Map, b: Map) { + if (a.size !== b.size) return false + for (const [key, value] of a) if (!b.has(key) || !Object.is(b.get(key), value)) return false + return true +} + +/** How `next` differs from `prev`, or null if the page's copy of `prev` already equals it. */ +export function changeOf(next: unknown, prev: unknown): Change | null { + if (Object.is(next, prev)) return null + if (ArrayBuffer.isView(next) && ArrayBuffer.isView(prev)) return sameView(next, prev) ? null : { v: next } + if (next instanceof Map && prev instanceof Map) return sameMap(next, prev) ? null : { v: next } + if (Array.isArray(next) && Array.isArray(prev)) { + const p: Record = {} + let changed = next.length !== prev.length + for (let i = 0; i < next.length; i++) { + const change = changeOf(next[i], prev[i]) + if (change) { + p[i] = change + changed = true + } + } + return changed ? { p, n: next.length } : null + } + if (isPlain(next) && isPlain(prev)) { + const p: Record = {} + let changed = false + // A key missing and a key set to undefined read the same. + for (const key in next) { + const change = changeOf(next[key], prev[key]) + if (change) { + p[key] = change + changed = true + } + } + const d = Object.keys(prev).filter((key) => !(key in next) && prev[key] !== undefined) + if (d.length) return { p, d } + return changed ? { p } : null + } + const kept = (value: unknown) => + typeof value !== 'object' || value === null || Array.isArray(value) || isPlain(value) || ArrayBuffer.isView(value) + if (!kept(next) && !(next instanceof Map)) + throw new Error(`A view copy cannot carry a ${(next as object).constructor.name}`) + return { v: next } +} + +/** `prev` with `change` applied; parts the change leaves alone keep their identity. */ +export function applyChange(prev: T, change: Change | null): T { + if (!change) return prev + if ('v' in change) return change.v as T + if (Array.isArray(prev)) { + const next = prev.slice(0, change.n ?? prev.length) + next.length = change.n ?? prev.length + for (const key in change.p) next[Number(key)] = applyChange(prev[Number(key)], change.p[key]!) + return next as T + } + const next: Record = { ...(prev as Record) } + for (const key of change.d ?? []) delete next[key] + for (const key in change.p) next[key] = applyChange((prev as Record)[key], change.p[key]!) + return next as T +}