From 384712045c3ec2e9c6c3ba9c18ea499381bea74f Mon Sep 17 00:00:00 2001 From: NeoLorenzo Date: Wed, 28 Oct 2026 17:18:32 +0000 Subject: [PATCH] perf(life15): lighter wake-ups and an in-place worker step [LIFE15-Lighter-070] --- CHANGELOG.md | 12 +++++ LAB_NOTES.md | 12 +++++ docs/ARCHITECTURE.md | 4 +- docs/LIFE15_SPEC.md | 28 ++++++++++-- docs/VALIDATION.md | 2 +- src/valley/clock.ts | 40 +++++++++++++---- src/valley/engine.test.ts | 11 ++++- src/valley/engine.ts | 78 +++++++++++++++++++++++--------- src/valley/perception.ts | 80 ++++++++++++++++++++------------- src/valley/wake.ts | 14 ++++-- src/valleyView/engineWorker.ts | 5 ++- src/valleyView/viewCopy.test.ts | 20 ++++++--- src/valleyView/viewCopy.ts | 41 +++++++++++++---- 13 files changed, 258 insertions(+), 89 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38c6681..911ce24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ 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-Lighter-070] - (2026-10-28) + +- An exchange no longer copies group members who are dead or out of talking distance, and copies back only the views that changed. +- Looking around scans nearby chunks directly, without candidate lists; only walkers have their position worked out from their route. +- The chunks a route crosses are found with one reused buffer instead of temporary lists. +- The wake-up queue cancels lazily: cancelled entries are marked and dropped at the front, or all at once when they outnumber the rest. +- New `advanceValley` runs the engine on a state in place; the worker uses it, and `stepValley` stays pure. The view copy snapshots the followed person's memory itself. +- The daily summary counts known places without copying them. +- Days 50 to 59 at 1 month/s run about 27% faster. Every fingerprint stays the same. +- New tests: advancing in place equals stepping copies, and view copies of an in-place run equal those of a pure run. +- The Life 15 specification is revised for update 070, with the hut-building week's cost left as a question for later. + ## [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). diff --git a/LAB_NOTES.md b/LAB_NOTES.md index bafd574..c0dd7ee 100644 --- a/LAB_NOTES.md +++ b/LAB_NOTES.md @@ -6,6 +6,18 @@ 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-Lighter-070] - (2026-10-28) + +The owner asked why 1 month/s (30 simulated days a second) is out of reach and approved any speed-up that leaves the simulation unchanged. The camp wake-up cascade was kept on purpose: who wakes whom will matter for relationships. + +**Where the time went, measured in Node on the canonical forty, seed 20260813, 12-hour steps on main.** Days 1–10: 100–200 ms a simulated day. Days 11–17, the hut-building week: 0.5–3.3 s. Days 20–90: 170–650 ms, typically about 250 ms. Days 50–60 averaged 228 ms: 1,008 wake-ups a day ending in "keep resting" at 37 µs each (37 ms; looking around 11, choosing a task 7.5, the exchange check 6, the body 6, meetings 3.7), and 403 walk decisions at 345 µs each (139 ms; route planning 68, arrival wake-ups 20, choosing water 18, leisure walks 14). About 274 MB was allocated a day, and garbage collection took about 46 ms. + +**What was built.** Six speed-ups that change no result: the exchange check skips absent members, looking around and route crossings stop building temporary lists, the queue cancels lazily, the worker advances its state in place with `advanceValley`, and the daily summary counts places without copying. Every fingerprint passed unchanged. + +**After.** Pure 12-hour steps take about 170–180 ms a day past day 50, with garbage collection about 29 ms. Run as the worker runs (50 ms slices, 720-minute strides, a view copy and its changes each step), days 50–59 took 200, 172 and 177 ms a day in three runs against main's 275, 240 and 236: about 27% faster, roughly 4.2 to 5.7 days a second of engine time. Not checked in the browser this time: the preview pane was hidden, so the browser figures of update 069 stand. + +**Findings.** Keeping still is no longer the main cost. Walk decisions are now about 60% of a day, and the hut-building week is still about ten times slower than later days. 1 month/s would need each day near 33 ms, about five times faster again, so the next work is on route planning and water choice, then the hut week. + ## [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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bb68546..afabd76 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -83,7 +83,7 @@ The 3D world draws each firm and Government across its plot: `buildingScale` str ## Life 15: habitual routes, bodies, clock and ground mesh -`src/valley/` is the independent Life core described by [LIFE15_SPEC.md](LIFE15_SPEC.md). It imports only the pure RNG helpers from the frozen MVP9 core. Quantities are integers: centimetres, kilocalories, kilograms, millilitres and minutes. `stepValley(state, toMinute)` is pure and deterministic: it clones the state, runs every queued wake-up up to `toMinute` and sets the clock there. +`src/valley/` is the independent Life core described by [LIFE15_SPEC.md](LIFE15_SPEC.md). It imports only the pure RNG helpers from the frozen MVP9 core. Quantities are integers: centimetres, kilocalories, kilograms, millilitres and minutes. `stepValley(state, toMinute)` is pure and deterministic: it clones the state, runs every queued wake-up up to `toMinute` and sets the clock there. `advanceValley(state, toMinute)` runs the same loop on the state itself, for a caller that owns it: only the worker does. - **Bodies and personality.** `nature.ts` draws bounded integer normals and applies integer Cholesky factors to body and Big Five correlations. `layout.ts` owns isolated body and traits streams; founder positions, skills and craft draws are unchanged. Each person stores immutable body measurements, trait scores, derived thresholds, load and rates. `personConfig` supplies a cached personal view to shared body, route and task helpers; run settings stay separate. Founder means and spreads by sex are recorded once, in thousandths. State copies copy the small body/trait records independently. - **Clock and queue.** `clock.ts` holds the wake-up queue, ordered by minute, then world before people, then person id. `calendar.ts` turns a minute into a day, a season and a year of `daysPerYear` days. `world.ts` owns hourly and midnight work: regrowth, fish growth, fires and daily summaries. `wake.ts` handles a person's wake-up: it settles the task that ended, perceives, chooses the next task by priority and queues the next wake-up. @@ -98,7 +98,7 @@ 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 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 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. The worker owns its state, so it advances it in place with `advanceValley`. `viewCopy.ts` makes the view copy, with its own snapshot of the followed person's memory: 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. diff --git a/docs/LIFE15_SPEC.md b/docs/LIFE15_SPEC.md index cb1aebe..16cd228 100644 --- a/docs/LIFE15_SPEC.md +++ b/docs/LIFE15_SPEC.md @@ -1,6 +1,6 @@ -# [LIFE15-Worker-069] +# [LIFE15-Lighter-070] -**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. +**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. Update 070 makes wake-ups cheaper without changing any result. 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,21 @@ 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 070: lighter wake-ups + +**The problem.** After update 069, 1 month/s reaches about 4 simulated days a second, against 30 wanted. On the canonical forty past day 50 a simulated day costs about 230 ms of engine time: a thousand wake-ups that end in "keep resting" take 37 ms, four hundred walk decisions 140 ms, and the rest is the step's own copies and about 45 ms of garbage collection over 270 MB of short-lived objects a day. + +**The change.** Six speed-ups. None changes a result: every fingerprint stays the same. + +- **The exchange check.** A wake-up offers exchanges within the person's group. Group members who are dead or beyond talking distance can take no part, so they are no longer copied into the exchange's working views, and views nobody changed are not copied back. +- **Looking around.** The people, fires and stock checks at each wake-up scan the nearby chunks directly, without building lists of candidates first; only walkers have their position worked out from their route, as everyone else stands where they are recorded. +- **Route chunk crossings.** The chunks a walk crosses, which decide who is woken by someone arriving, are found with one reused buffer in place of temporary lists for every route. +- **The wake-up queue cancels lazily.** Every wake-up cancels the person's pending wake-ups, which rebuilt the whole queue. Cancelled entries are now marked and dropped when they reach the front, or all at once when they outnumber the rest. Live entries leave in exactly the same order. +- **The worker advances its state in place.** `stepValley` stays pure: it copies the state, then runs it on. The worker owns its state and keeps only the view copies it sends, so it calls `advanceValley`, the same loop without the copy. Nothing else may call `advanceValley` on a state someone else holds. The view copy now takes its own snapshot of the followed person's memory, since the engine's is changed in place. +- **The daily summary counts known places without copying them.** + +**Measured.** In Node, on the canonical forty, seed 20260813, as the worker runs at 1 month/s (12-hour strides, a view copy and its changes each step), days 50 to 59 take 175–200 ms a simulated day against 235–275 ms before, about 27% faster: roughly 5.7 days a second of engine time against 4.2. Garbage collection falls from about 46 to 29 ms a day. Walk decisions (planning routes, choosing water, leisure walks) are now about 60% of a day and are the next thing to make cheaper. + ## 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. @@ -171,7 +186,7 @@ The run starts at minute 0, midnight of day 0 of year 0. A day is 1,440 minutes; ### Wake-ups -The state holds a queue of wake-ups `(minute, phase, id)`. Phases, in order within a minute: `world` (daily regrowth, spoilage, invariants at midnight; fires at each hour), then `person`, ordered by id. `stepValley(state, toMinute)` pops and runs wake-ups until the queue's head is past `toMinute`, and is pure: it returns a new state and the events of the interval. +The state holds a queue of wake-ups `(minute, phase, id)`. Phases, in order within a minute: `world` (daily regrowth, spoilage, invariants at midnight; fires at each hour), then `person`, ordered by id. `stepValley(state, toMinute)` pops and runs wake-ups until the queue's head is past `toMinute`, and is pure: it returns a new state and the events of the interval. `advanceValley(state, toMinute)` runs the same loop on the state itself, for a caller that owns it, as the worker does (update 070). Cancelling a person's wake-ups marks them; a marked entry is dropped when it reaches the front. A person's wake-up is scheduled by: @@ -455,6 +470,8 @@ Update 068 changes `routes.ts` only for behaviour: a person's pieces, worked out 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. +Update 070 changes no result: `wake.ts` skips absent group members in an exchange; `perception.ts` scans nearby chunks without temporary lists and finds route crossings with a reused buffer; `clock.ts` cancels lazily; `engine.ts` adds `advanceValley` and counts known places without copying; the worker advances its state in place, and `viewCopy.ts` snapshots the followed person's memory. + ## 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. @@ -493,6 +510,8 @@ Life 14 fixtures, kept: **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. +**Update 070.** Every fingerprint stays the same. A few fast unit tests: advancing a state in place equals stepping copies of it, minute by minute and across days; and the view-copy tests run on a state advanced in place, checking each copy equals the one made from a pure copy of the run. Measured once and recorded in the lab notes: days 50 to 59 at 1 month/s in Node, before and after. + 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 @@ -501,7 +520,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? -- 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. +- After update 070, which still reaches about 6 days a second at 1 month/s, which way to a month a second: cheaper route planning and water choice, which change no result, or people thinking less often (surveying and replanning less), or a simpler model of daily movement at map speeds? The last two change what people do. +- The hut-building week (days 11 to 17 on the canonical run) takes 0.5 to 3.3 s a simulated day against about 0.25 s later, from its many cutting and log-carrying walks. What would make it affordable at a month a second? - 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? diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 545d205..cf72550 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 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. +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. It runs on a state advanced in place, as the worker does, and checks each copy equals the one made from a pure run. `engine.test.ts` checks that advancing a state in place equals stepping copies of it. The worker leaves the engine unchanged, so update 069 keeps every fingerprint, and the speed-ups of update 070 keep them too. 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/valley/clock.ts b/src/valley/clock.ts index a04cda6..dd32507 100644 --- a/src/valley/clock.ts +++ b/src/valley/clock.ts @@ -22,10 +22,15 @@ const compare = (a: WakeEntry, b: WakeEntry) => (a.routeId ?? -1) - (b.routeId ?? -1) || (a.walkStartMinute ?? -1) - (b.walkStartMinute ?? -1) +/** + * Cancelling marks entries instead of rebuilding the heap, which every wake-up did; a marked entry is dropped when it + * reaches the front, or when marked entries outnumber the rest. Live entries leave in the same order either way. + */ export class WakeQueue { private heap: WakeEntry[] = [] + private cancelled = new Set() get size() { - return this.heap.length + return this.heap.length - this.cancelled.size } schedule(entry: WakeEntry): void { if (!Number.isSafeInteger(entry.minute) || entry.minute < 0 || !Number.isSafeInteger(entry.id) || entry.id < 0) @@ -42,10 +47,16 @@ export class WakeQueue { this.heap[index] = value } peek(): WakeEntry | null { + while (this.heap.length && this.cancelled.has(this.heap[0]!)) { + this.cancelled.delete(this.heap[0]!) + this.removeFirst() + } return this.heap[0] ?? null } pop(): WakeEntry | null { - if (!this.heap.length) return null + return this.peek() ? this.removeFirst() : null + } + private removeFirst(): WakeEntry { const first = this.heap[0]! const last = this.heap.pop()! if (this.heap.length) { @@ -62,21 +73,32 @@ export class WakeQueue { return first } cancelPerson(id: number, kind?: WakeKind): void { - const kept = this.heap.filter( - (entry) => entry.phase !== 1 || entry.id !== id || (kind !== undefined && entry.kind !== kind), - ) - this.heap = [] - for (const entry of kept) this.schedule(entry) + for (const entry of this.heap) + if (entry.phase === 1 && entry.id === id && (kind === undefined || entry.kind === kind)) this.cancelled.add(entry) + if (this.cancelled.size > this.heap.length / 2) { + const kept = this.live() + this.heap = [] + this.cancelled.clear() + for (const entry of kept) this.schedule(entry) + } + } + private live() { + return this.cancelled.size ? this.heap.filter((entry) => !this.cancelled.has(entry)) : this.heap } entriesOf(id: number): WakeEntry[] { - return this.heap + return this.live() .filter((entry) => entry.phase === 1 && entry.id === id) .map((entry) => ({ ...entry })) .sort(compare) } clone(): WakeQueue { + // The copy keeps the heap's layout and marks, so a copy runs on exactly as its original would. const queue = new WakeQueue() - queue.heap = this.heap.map((entry) => ({ ...entry })) + queue.heap = this.heap.map((entry) => { + const copy = { ...entry } + if (this.cancelled.has(entry)) queue.cancelled.add(copy) + return copy + }) return queue } } diff --git a/src/valley/engine.test.ts b/src/valley/engine.test.ts index 7877579..872d0b4 100644 --- a/src/valley/engine.test.ts +++ b/src/valley/engine.test.ts @@ -1,6 +1,6 @@ import { addTestLake } from './ruleFixtures' import { describe, expect, it } from 'vitest' -import { createValley, stepValley, cloneValley } from './engine' +import { advanceValley, createValley, stepValley, cloneValley } from './engine' import { FLAT_LAND } from './config' import { WakeQueue } from './clock' @@ -67,6 +67,15 @@ describe('wake-up engine', () => { expect(batch).toEqual(single) expect(state).toEqual(before) }) + it('advancing a state in place equals stepping copies of it', () => { + const owned = createValley(FLAT_LAND) + let stepped = cloneValley(owned) + for (const minute of [1, 60, 61, 600, 1_440, 2_000, 2_880]) { + expect(advanceValley(owned, minute)).toBe(owned) + stepped = stepValley(stepped, minute) + expect(owned).toEqual(stepped) + } + }) }) describe('food, water and wood tasks', () => { diff --git a/src/valley/engine.ts b/src/valley/engine.ts index 23f00f5..1a66747 100644 --- a/src/valley/engine.ts +++ b/src/valley/engine.ts @@ -35,6 +35,12 @@ const foodStocks = (state: Pick) => ({ }) const zeros = (n: number) => Array.from({ length: n }, () => 0) +/** How many places a person has seen. */ +function placesKnown(person: Forager) { + let count = 0 + for (const minute of person.knownPlaces) if (minute >= 0) count += 1 + return count +} /** Groups standing, and living foragers without a group. */ function groupCounts(state: Pick) { @@ -106,9 +112,9 @@ function emptyDay( foundings: 0, joinings: 0, dissolutions: 0, - placesSeenById: foragers.map((p) => [...p.knownPlaces].filter((m) => m >= 0).length), + placesSeenById: foragers.map(placesKnown), loadedWalkSecondsById: zeros(foragers.length), - sitesKnownById: foragers.map((p) => [...p.knownPlaces].filter((m) => m >= 0).length), + sitesKnownById: foragers.map(placesKnown), sitesCheckedById: zeros(foragers.length), fireGivenById: zeros(foragers.length), campfireBurnedWood: 0, @@ -332,24 +338,43 @@ export function createValley(overrides: Partial = {}): ValleyState // Traits, rates and thirst thresholds are set at birth and never change, so copies share them; sharing `rates` also // keeps `personConfig`'s cache warm across steps. -const cloneForager = (forager: Forager): Forager => { +/** A person's memory of the valley: what a view copy holds afresh only for the person followed. */ +export type Memory = Pick< + Forager, + | 'knowledge' + | 'ways' + | 'knownBanks' + | 'knownPlaces' + | 'placeCheckedMinute' + | 'placeStock' + | 'placeWood' + | 'placeLogs' + | 'fishMemory' + | 'metPosition' +> +/** A copy of a person's memory. Knowledge and banks are shared until either holder learns more; ways never change. */ +export const copyMemory = (forager: Forager): Memory => ({ + knowledge: shareKnowledge(forager.knowledge), + ways: forager.ways, + knownBanks: shareBankMemory(forager.knownBanks), + knownPlaces: forager.knownPlaces.slice(), + placeCheckedMinute: forager.placeCheckedMinute.slice(), + placeStock: forager.placeStock.slice(), + placeWood: forager.placeWood.slice(), + placeLogs: forager.placeLogs.slice(), + fishMemory: new Map(forager.fishMemory), + metPosition: new Map(forager.metPosition), +}) +const cloneForager = (forager: Forager, memory: Memory = copyMemory(forager)): Forager => { return { ...forager, task: forager.task ? { ...forager.task, rateChanges: forager.task.rateChanges?.map((change) => ({ ...change })) } : null, - knownPlaces: forager.knownPlaces.slice(), - placeCheckedMinute: forager.placeCheckedMinute.slice(), seenMinute: forager.seenMinute.slice(), - placeStock: forager.placeStock.slice(), - placeWood: forager.placeWood.slice(), - placeLogs: forager.placeLogs.slice(), metMinute: forager.metMinute.slice(), - metPosition: new Map(forager.metPosition), arrivalFrom: forager.arrivalFrom.slice(), - knowledge: shareKnowledge(forager.knowledge), - knownBanks: shareBankMemory(forager.knownBanks), - fishMemory: new Map(forager.fishMemory), + ...memory, deathCauses: [...forager.deathCauses], carried: [...forager.carried], practiceLog: { @@ -402,8 +427,11 @@ const cloneDay = (day: DaySummary): DaySummary => ({ hutLogsById: [...day.hutLogsById], }) -/** A copy that shares nothing mutable with `state`. The layout and finished days never change, so they are shared. */ -export function cloneValley(state: ValleyState): ValleyState { +/** + * A copy that shares nothing mutable with `state`. The layout and finished days never change, so they are shared. + * `memoryOf` gives each person's memory in the copy; by default a copy of it. + */ +export function cloneValley(state: ValleyState, memoryOf: (forager: Forager) => Memory = copyMemory): ValleyState { return { ...state, queue: state.queue.clone(), @@ -419,7 +447,7 @@ export function cloneValley(state: ValleyState): ValleyState { felledMinute: state.felledMinute.slice(), logRegrowth: new Map([...state.logRegrowth].map(([id, minutes]) => [id, [...minutes]])), stoneStock: state.stoneStock.slice(), - foragers: state.foragers.map(cloneForager), + foragers: state.foragers.map((forager) => cloneForager(forager, memoryOf(forager))), groups: state.groups.map((group) => ({ ...group })), huts: [...state.huts], totals: { ...state.totals }, @@ -453,7 +481,7 @@ function finishDay(state: ValleyState, minute: number) { day.forageRates = state.foragers.map((p) => p.forageRate) day.woodRates = state.foragers.map((p) => p.woodRate) day.craftById = state.foragers.map((p) => p.craft) - day.sitesKnownById = state.foragers.map((p) => [...p.knownPlaces].filter((m) => m >= 0).length) + day.sitesKnownById = state.foragers.map(placesKnown) day.placesSeenById = [...day.sitesKnownById] state.days.push(day) state.today = emptyDay(dayOf(minute), state) @@ -467,16 +495,26 @@ function finishDay(state: ValleyState, minute: number) { export function stepValley(previous: ValleyState, toMinute = previous.minute + 1, stop?: () => boolean): ValleyState { if (!Number.isSafeInteger(toMinute) || toMinute < previous.minute) throw new Error('Target minute must be a safe integer at or after the current minute') - const state = cloneValley(previous) + return advanceValley(cloneValley(previous), toMinute, stop) +} +/** + * Runs `state` itself on to `toMinute`, exactly as `stepValley` runs a copy of it, and returns it. Only for a caller + * that owns the state and never reads it again as it was, such as the engine's worker: the copy each step makes, and + * the copies of memory it shares, then cost nothing. + */ +export function advanceValley(state: ValleyState, toMinute = state.minute + 1, stop?: () => boolean): ValleyState { + if (!Number.isSafeInteger(toMinute) || toMinute < state.minute) + throw new Error('Target minute must be a safe integer at or after the current minute') + const start = state.minute state.lastInterval = [] - if (toMinute === previous.minute) return state + if (toMinute === start) return state while (state.queue.peek() && state.queue.peek()!.minute <= toMinute) { - if (stop && state.queue.peek()!.minute > state.minute && state.minute > previous.minute && stop()) { + if (stop && state.queue.peek()!.minute > state.minute && state.minute > start && stop()) { toMinute = state.minute break } const entry = state.queue.pop()! - if (entry.minute < previous.minute) throw new Error('A wake-up cannot be in the past') + if (entry.minute < start) throw new Error('A wake-up cannot be in the past') state.minute = entry.minute if (entry.phase === 0) { if (entry.minute % MINUTES_PER_DAY === 0) finishDay(state, entry.minute) diff --git a/src/valley/perception.ts b/src/valley/perception.ts index e403a4e..2de5eb8 100644 --- a/src/valley/perception.ts +++ b/src/valley/perception.ts @@ -71,7 +71,11 @@ export function peopleInChunk(state: ValleyState, chunk: number): number[] { /** Records each living person's chunk at `minute`; wake-ups do this often, so the chunk lists are not rebuilt. */ export function locatePeople(state: ValleyState, minute: number): void { for (const person of state.foragers) - state.personChunk[person.id] = person.alive ? chunkOf(state.layout.nav, positionAt(state, person, minute)) : -1 + state.personChunk[person.id] = !person.alive + ? -1 + : person.task?.kind === 'walk' + ? chunkOf(state.layout.nav, positionAt(state, person, minute)) + : chunkOf(state.layout.nav, person) } /** Locates people and rebuilds the chunk lists, which the state keeps between steps. */ export function reindexPeople(state: ValleyState, minute: number): void { @@ -127,7 +131,7 @@ export function observeAt(state: ValleyState, person: Forager, minute: number): stones: state.stoneStock[placeId]!, } } - const viewKey = `${origin.x},${origin.y}:${radius}` + const viewKey = surveying ? `${origin.x},${origin.y}:${radius}` : '' if (surveying && !viewsSeen.get(person.knowledge)?.has(viewKey)) for ( let cy = Math.max(0, Math.floor((origin.y - radius) / nav.chunkCm)); @@ -183,16 +187,16 @@ export function observeAt(state: ValleyState, person: Forager, minute: number): } // The index records each person's last wake-up; route entry notifications keep moving entries local. const talk = config.sightRadiusCm - const [x0, x1] = [Math.floor((origin.x - talk) / nav.chunkCm), Math.floor((origin.x + talk) / nav.chunkCm)] - const [y0, y1] = [Math.floor((origin.y - talk) / nav.chunkCm), Math.floor((origin.y + talk) / nav.chunkCm)] - const candidates: number[] = [] + const x0 = Math.floor((origin.x - talk) / nav.chunkCm), + x1 = Math.floor((origin.x + talk) / nav.chunkCm), + y0 = Math.floor((origin.y - talk) / nav.chunkCm), + y1 = Math.floor((origin.y + talk) / nav.chunkCm) for (let id = 0; id < state.personChunk.length; id += 1) { const chunk = state.personChunk[id]! if (chunk < 0) continue - const [x, y] = [chunk % nav.chunkCells, Math.floor(chunk / nav.chunkCells)] - if (x >= x0 && x <= x1 && y >= y0 && y <= y1) candidates.push(id) - } - for (const id of candidates) { + const x = chunk % nav.chunkCells, + y = Math.floor(chunk / nav.chunkCells) + if (x < x0 || x > x1 || y < y0 || y > y1) continue const other = state.foragers[id]! if (id === person.id || !other.alive) continue const point = positionAt(state, other, minute) @@ -214,40 +218,52 @@ export function observeAt(state: ValleyState, person: Forager, minute: number): person.knownFlags.push(group.id) return observation } +/** Where along a segment it crosses chunk lines, reused between segments: walks have many short segments. */ +let cutBuffer = new Float64Array(64) export function chunksOfRoute(nav: NavMap, route: Route): { chunk: number; minute: number }[] { const result: { chunk: number; minute: number }[] = [], - seen = new Set() + seen = new Set(), + size = nav.chunkCm let units = 0 - const add = (chunk: number, at: number) => { + const add = (x: number, y: number, at: number) => { + const chunk = Math.floor(y / size) * nav.chunkCells + Math.floor(x / size) if (!seen.has(chunk)) { seen.add(chunk) result.push({ chunk, minute: Math.floor(at / TIME_UNITS_PER_MINUTE) }) } } + const crossings = (a: number, b: number, count: number) => { + if (a === b) return count + for (let line = (Math.floor(Math.min(a, b) / size) + 1) * size; line < Math.max(a, b); line += size) { + if (count === cutBuffer.length) { + const grown = new Float64Array(2 * count) + grown.set(cutBuffer) + cutBuffer = grown + } + cutBuffer[count++] = (line - a) / (b - a) + } + return count + } for (const segment of route.segments) { - const cuts = [0, 1], - dx = segment.x1 - segment.x0, + const dx = segment.x1 - segment.x0, dy = segment.y1 - segment.y0 - for (const [a, b] of [ - [segment.x0, segment.x1], - [segment.y0, segment.y1], - ]) { - if (a === b) continue - for ( - let line = (Math.floor(Math.min(a!, b!) / nav.chunkCm) + 1) * nav.chunkCm; - line < Math.max(a!, b!); - line += nav.chunkCm - ) - cuts.push((line - a!) / (b! - a!)) + cutBuffer[0] = 0 + cutBuffer[1] = 1 + const count = crossings(segment.y0, segment.y1, crossings(segment.x0, segment.x1, 2)) + // Insertion sort: a segment crosses few chunk lines. + for (let i = 1; i < count; i += 1) { + const value = cutBuffer[i]! + let j = i - 1 + for (; j >= 0 && cutBuffer[j]! > value; j -= 1) cutBuffer[j + 1] = cutBuffer[j]! + cutBuffer[j + 1] = value } - cuts.sort((a, b) => a - b) - add(chunkOf(nav, { x: segment.x0, y: segment.y0 }), units) - for (let i = 1; i < cuts.length; i += 1) { - const t = (cuts[i - 1]! + cuts[i]!) / 2 - add(chunkOf(nav, { x: segment.x0 + t * dx, y: segment.y0 + t * dy }), units + cuts[i - 1]! * segment.timeUnits) + add(segment.x0, segment.y0, units) + for (let i = 1; i < count; i += 1) { + const t = (cutBuffer[i - 1]! + cutBuffer[i]!) / 2 + add(segment.x0 + t * dx, segment.y0 + t * dy, units + cutBuffer[i - 1]! * segment.timeUnits) } units += segment.timeUnits - add(chunkOf(nav, { x: segment.x1, y: segment.y1 }), units) + add(segment.x1, segment.y1, units) } return result } @@ -267,8 +283,8 @@ export function scheduleArrivals(state: ValleyState, walkerId: number, route: Ro routeId: walker.task?.routeId ?? -1, walkStartMinute: startMinute, }) - for (const id of peopleInChunk(state, entry.chunk)) { - if (id === walkerId) continue + for (let id = 0; id < state.personChunk.length; id += 1) { + if (state.personChunk[id] !== entry.chunk || id === walkerId) continue const person = state.foragers[id]! if (!person.alive || (person.task?.kind === 'sleep' && person.waterDeficitMl < fatal)) continue state.queue.schedule({ diff --git a/src/valley/wake.ts b/src/valley/wake.ts index 71d97a4..1ae4512 100644 --- a/src/valley/wake.ts +++ b/src/valley/wake.ts @@ -9,6 +9,7 @@ import { nearestFrontier, chunkOf, estimateMinutes } from './routes' import { observeAt, locatePeople, scheduleArrivals, peopleInChunk } from './perception' import { rememberWalk, type WalkFound } from './ways' import { carriedKcal, spoil, addLots, eatCarried } from './food' +import { distanceSq } from './geometry' import { takeFrom } from './places' import { nextShortOfWood, swap } from './trade' import { meet, dissolveIfAlone } from './social' @@ -262,13 +263,19 @@ function creditTask(state: ValleyState, person: Forager, minute: number, events: return produced } /** The waking person offers and asks for wood and axes among the people it may trade with. */ +/** A group member out of the trader's reach: dead to every exchange rule, and in no group. */ +const ABSENT = { id: -1, alive: false, groupId: null } as unknown as Forager function exchange(state: ValleyState, id: number, minute: number, events: ValleyEvent[]) { - // Acceptance reads the counterparty's body at this minute without ending its task or paying it twice. Only members - // of the trader's group may trade with it, so everyone else is passed as they are, never read past their group. - const groupId = state.foragers[id]!.groupId + // Acceptance reads the counterparty's body at this minute without ending its task or paying it twice. Only living + // members of the trader's group within talking distance may trade with it or hear its terms, so everyone else is + // passed as they are, or, for members out of reach, as an absent member that no rule reads past. + const groupId = state.foragers[id]!.groupId, + at = positionAt(state, state.foragers[id]!, minute) const views = state.foragers.map((other) => { if (other.groupId !== groupId) return other const point = positionAt(state, other, minute) + if (other.id !== id && (!other.alive || distanceSq(point.x, point.y, at.x, at.y) > state.config.talkRadiusCm ** 2)) + return ABSENT const energy = other.task ? Math.max(0, energyAt(other.task, minute, state.routes).kcal) : other.energyKcal const water = other.task ? waterAt(other.task, minute, state.routes).ml : other.waterDeficitMl return { @@ -301,6 +308,7 @@ function exchange(state: ValleyState, id: number, minute: number, events: Valley if (event.kind === 'sale') address(state, event.sellerId === id ? event.buyerId : event.sellerId, minute) } for (const view of views) { + if (view === ABSENT || view === state.foragers[view.id]) continue const owner = state.foragers[view.id]! owner.carried = view.carried owner.wood = view.wood diff --git a/src/valleyView/engineWorker.ts b/src/valleyView/engineWorker.ts index 66f76ce..b4afc9d 100644 --- a/src/valleyView/engineWorker.ts +++ b/src/valleyView/engineWorker.ts @@ -1,5 +1,5 @@ /// -import { createValley, stepValley } from '../valley/engine' +import { advanceValley, createValley } from '../valley/engine' import type { ValleyConfig, ValleyState } from '../valley/types' import { changeOf, wireOf, type Wire } from './viewCopy' import type { EngineMessage, PageMessage } from './engineLink' @@ -34,7 +34,8 @@ function run() { try { while (state.minute < goal) { const before = state.minute - state = stepValley(state, Math.min(goal, before + stride), () => performance.now() - started >= SLICE_MS) + // The worker owns its state and keeps only the copies it sends, so it runs the state on in place. + state = advanceValley(state, Math.min(goal, before + stride), () => performance.now() - started >= SLICE_MS) send() if (performance.now() - started >= SLICE_MS) break } diff --git a/src/valleyView/viewCopy.test.ts b/src/valleyView/viewCopy.test.ts index ce3bf60..f4303a4 100644 --- a/src/valleyView/viewCopy.test.ts +++ b/src/valleyView/viewCopy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { FLAT_LAND } from '../valley/config' -import { cloneValley, stepValley } from '../valley/engine' +import { advanceValley, cloneValley, stepValley } from '../valley/engine' import { createSurveyedValley } from '../valley/ruleFixtures' import { applyChange, changeOf, stateOf, wireOf, type Wire } from './viewCopy' @@ -9,18 +9,22 @@ const across = (wire: Wire): Wire => ({ ...structuredClone({ ...wire, layout: nu describe('view copies', () => { it('rebuilds each state’s view copy on the page from the changes alone', () => { - let state = createSurveyedValley(FLAT_LAND) + // As in the worker, the state runs on in place, so a copy that shared its objects would lose changes. + const state = createSurveyedValley(FLAT_LAND), + pure = { state: cloneValley(state) } 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) + advanceValley(state, state.minute + stride) + pure.state = stepValley(pure.state, pure.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({ ...wire, layout: null }).toEqual({ ...wireOf(pure.state, followed, sent), layout: null }) } expect(state.minute).toBeGreaterThan(2_700) expect(page.layout).toBe(sent.layout) @@ -37,10 +41,12 @@ describe('view copies', () => { 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]) + // Memory is a current copy for the person followed, and the last copy's for everyone else. + for (const key of ['knowledge', 'knownPlaces', 'placeStock', 'knownBanks'] as const) + if (p.id === 2) { + expect(wire.foragers[p.id]![key]).toEqual(p[key]) + expect(wire.foragers[p.id]![key]).not.toBe(p[key]) + } else expect(wire.foragers[p.id]![key]).toBe(last.foragers[p.id]![key]) } const moved = (p: (typeof state.foragers)[number]) => (['knowledge', 'ways', 'knownPlaces', 'placeStock'] as const).some( diff --git a/src/valleyView/viewCopy.ts b/src/valleyView/viewCopy.ts index 1bb1415..5bc3e15 100644 --- a/src/valleyView/viewCopy.ts +++ b/src/valleyView/viewCopy.ts @@ -1,4 +1,5 @@ import { WakeQueue, type WakeEntry } from '../valley/clock' +import { cloneValley, type Memory } from '../valley/engine' import type { Route } from '../valley/routes' import type { Forager, ValleyEvent, ValleyState } from '../valley/types' @@ -31,13 +32,37 @@ const MEMORY = [ 'placeLogs', 'fishMemory', 'metPosition', -] as const satisfies readonly (keyof Forager)[] +] as const satisfies readonly (keyof Memory)[] -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 +/** + * What a copy holds of a person's memory: the last copy's, or, for the person followed and in the first copy, a copy + * that shares nothing with the engine's state, which the worker runs on in place. Banks are only ever added, so a + * bank memory of the same size is the same and is kept. + */ +function viewMemory(person: Forager, followedId: number, last: Forager | undefined): Memory { + if (person.id !== followedId && last) { + const kept = {} as Record<(typeof MEMORY)[number], unknown> + for (const key of MEMORY) kept[key] = last[key] + return kept as Memory + } + const k = person.knowledge + return { + knowledge: { + triangles: k.triangles.slice(), + revision: k.revision, + fullyKnown: k.fullyKnown?.slice(), + banksKnown: k.banksKnown?.slice(), + }, + ways: person.ways, + knownBanks: last && last.knownBanks.size === person.knownBanks.size ? last.knownBanks : new Map(person.knownBanks), + knownPlaces: person.knownPlaces.slice(), + placeCheckedMinute: person.placeCheckedMinute.slice(), + placeStock: person.placeStock.slice(), + placeWood: person.placeWood.slice(), + placeLogs: person.placeLogs.slice(), + fishMemory: new Map(person.fishMemory), + metPosition: new Map(person.metPosition), + } } const VIEW_EVENTS = new Set(['exchange', 'walk']) @@ -53,6 +78,7 @@ function viewDay(events: ValleyEvent[], finished: boolean) { /** 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 copy = cloneValley(state, (person) => viewMemory(person, followedId, previous?.foragers[person.id])) const routes: Route[] = [] for (const person of state.foragers) { const id = person.task?.routeId ?? -1 @@ -60,12 +86,11 @@ export function wireOf(state: ValleyState, followedId: number, previous: Wire | } const last = state.eventDays.length - 1 return { - ...state, + ...copy, 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])), } }