diff --git a/CHANGELOG.md b/CHANGELOG.md index d08a363..35aae1a 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-Speed-067] - (2026-10-27) + +- Each frame runs the engine in one step that checks its 40 ms budget between wake-ups, in place of many 15-minute steps that each copied the whole valley. At 1 month/s a frame had made about 48 copies. +- Copies of the valley share each person's traits, rates and thirst thresholds, which never change after birth, so a person's working settings are no longer rebuilt after every step. +- Choosing wood skips places no nearer than the best so far before testing whether they can be reached, and a person's own piece of known ground is found once per choice rather than once per place. +- The ground under a whole-centimetre point is found once and remembered. +- The followed person's known-ground shading finds the triangle under each map cell once per valley, not at every redraw: about 75 ms a redraw before, under 2 ms after. +- The rings round the places the followed person knows are draped on the ground once, not again at every overlay redraw. +- At map speeds the panels refresh twice a second instead of ten times, and the history charts are drawn again only when a day ends, the followed person changes or a run starts. +- A day around day 30 of forty founders, run as the view runs it, takes about 300 ms instead of about 560 ms. Fingerprints are unchanged. +- In an off-screen production page at 1 month/s, past day 35: about 15.6 frames and 2.4 days a second, against 8.5 frames and 1.3 days before. + ## [LIFE15-Habits-066] - (2026-10-27) - Life 15, habitual routes. People remember the ways they walk between their hearth, places and bank points, up to 64 each, and take them again in either direction, or join one part-way. A way is planned again once a day has passed and they have seen new ground since, or at once if it crosses ground they no longer know; the way used longest ago is forgotten first. diff --git a/LAB_NOTES.md b/LAB_NOTES.md index 6eb48b4..885d641 100644 --- a/LAB_NOTES.md +++ b/LAB_NOTES.md @@ -6,6 +6,20 @@ 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-Speed-067] - (2026-10-27) + +The owner found the view still far too laggy and set 1 month/s running smoothly as the goal. A month a second is 30 simulated days a second, so with the view drawing too, the engine must run a day in about 30 ms. + +**Where the time went (canonical forty founders, seed 20260813).** Run in whole days, the engine took about 130–250 ms a day up to day 10, 0.5–4.9 s a day on days 11 to 17, and about 250–650 ms a day from day 20 to 45. The view runs it in short steps, which cost more again: at day 30, 558 ms a day in 15-minute steps against 409 ms in one step. Each step copies the valley (about 2.5 ms), and each copy also copied every person's rates, so `personConfig`'s cache, keyed by the rates object, missed after every step and rebuilt a full configuration. Early in a run that copying was a fifth of all time. Choosing wood tested reachability for every known place before comparing distances, and finding the ground under a place scanned the mesh each time, about 14% of the time at day 30. + +**Changes, none of which changes a run.** One step a frame that stops between wake-ups when the budget is spent; shared immutable traits, rates and thresholds; nearer-first pruning and one reachability set-up per choice; a cache of the triangles under each whole-centimetre point. The forty-founder fingerprint matches whole and in 15-minute steps. + +**Measured after,** in 12-hour steps (one frame at 1 month/s): days 3 to 9 take 110–180 ms, day 30 about 300 ms, days 20 to 45 about 190–410 ms. Days 11 to 17 barely improved (1.2–4.4 s). + +**What remains.** On the slow days the cost is route search. Counted on day 13: 980 coarse-band searches, of which 328 found no path inside their band and fell back to a full search; those full searches expanded on average about 34,000 triangles each, 11.3 million in the day. The band fails because known ground inside it is not connected, though the start and target are on one known piece. A* itself is already tight (typed heap, bit-set knowledge), so further gains here would change which routes people take and need a spec. At day 30, A* is about 30% of the time, choosing tasks about 30% and garbage collection about 15%. Reaching about 30 ms a day needs roughly another tenfold at steady state and a hundredfold on the slow days. + +**In the browser.** In the built-in browser at 1 month/s around day 50, the page ran about 1.3 days a second at about 7 frames a second, though the engine there ran a day in about 130 ms by itself (day 169: 128 ms for 1,689 wake-ups). Paused, it drew at about 26 frames a second. Shading the followed person's known ground looked up the triangle under every map cell at each redraw, about 75 ms, up to four times a second; it now takes under 2 ms. When the browser pane went off screen and the page was throttled, the rest was measured instead in Playwright's off-screen Chrome, which is not throttled, on a production build without minification, with a ten-second CPU profile at 1 month/s past day 35. Before the view changes: 8.5 frames and 1.3 days a second, and the main thread busy throughout. The engine had 28% of it, React re-rendering the panels ten times a second about 25% (most of it the history charts, which change only once a day), the 3D draw 26%, of which re-draping about 2,000 place rings on the ground each overlay redraw was 14%, and the browser's own work and garbage collection the rest. After draping each ring once, refreshing the panels twice a second at map speeds and redrawing the charts only when a day ends, the engine had 56% of the main thread, React 9% and the draw 15%. Giving the engine a larger share of each frame at map speeds did not pay: 40 ms gave 15.6 frames and 2.4 days a second, 60 ms 10.8 frames and 2.2 days, and 100 ms 7.5 frames and 2.6 days, so the budget stays at 40 ms. Off-screen Chrome may draw without the real graphics card, so the 3D draw's cost on the owner's machine was not measured. + ## [LIFE15-Habits-066] - (2026-10-27) Implemented the owner's approved Life 15 specification. Update 065 found the engine slowing sharply as people learnt the valley, led by route search and `observeAt`. The owner asked whether to rewrite in another language or copy other projects; the recommendation, which they approved, was to make walking more human instead: people reuse the ways they know (habits), plan by regions before footing (hierarchical path planning), and do not re-survey a landscape they have not left. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 89860c5..5901a27 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -98,6 +98,6 @@ 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 steps of at most 15 minutes, checking its 40 ms budget between steps and always running at least one. When the budget runs out first, the drawn minute stops at the last step finished, so the clock runs slower than asked rather than freezing the view. 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. 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 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 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/VALIDATION.md b/docs/VALIDATION.md index a5e93db..4634578 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 short engine steps until its budget is spent (at least one) and stops the clock at the last step finished, 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 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. 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/engine.ts b/src/valley/engine.ts index 7276abf..23f00f5 100644 --- a/src/valley/engine.ts +++ b/src/valley/engine.ts @@ -330,12 +330,11 @@ 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 => { return { ...forager, - traits: { ...forager.traits }, - rates: { ...forager.rates }, - thirstThresholds: { ...forager.thirstThresholds }, task: forager.task ? { ...forager.task, rateChanges: forager.task.rateChanges?.map((change) => ({ ...change })) } : null, @@ -461,13 +460,21 @@ function finishDay(state: ValleyState, minute: number) { state.eventDays.push([]) if (state.eventDays.length > EVENT_HISTORY_DAYS) state.eventDays.shift() } -export function stepValley(previous: ValleyState, toMinute = previous.minute + 1): ValleyState { +/** + * Runs the valley to `toMinute`. When `stop` is given, it is asked between wake-ups at different minutes once a minute + * has been run; if it answers true, the step ends at the last minute run, exactly as a step to that minute would. + */ +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) state.lastInterval = [] if (toMinute === previous.minute) return state while (state.queue.peek() && state.queue.peek()!.minute <= toMinute) { + if (stop && state.queue.peek()!.minute > state.minute && state.minute > previous.minute && 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') state.minute = entry.minute diff --git a/src/valley/forager.ts b/src/valley/forager.ts index 4c21857..d9ae378 100644 --- a/src/valley/forager.ts +++ b/src/valley/forager.ts @@ -154,18 +154,23 @@ function waterGoal(state: ValleyState, person: Forager, minute: number, severe: } return explore(state, person, 'seeking water', severe) } -function reachablePoint(state: ValleyState, person: Forager, point: Point) { - const nav = state.layout.nav, - first = routeTriangle(nav, person.knowledge, person), - last = routeTriangle(nav, person.knowledge, point) - if (first < 0 || last < 0) return false - const componentOf = knownComponents(nav, person.knowledge) - return componentOf(first) === componentOf(last) +/** Whether a point is on the same piece of known ground as the person; the person's own piece is found once. */ +function reachability(state: ValleyState, person: Forager) { + const nav = state.layout.nav + let first: number | undefined, componentOf: ((t: number) => number) | undefined + return (point: Point) => { + first ??= routeTriangle(nav, person.knowledge, person) + const last = routeTriangle(nav, person.knowledge, point) + if (first < 0 || last < 0) return false + componentOf ??= knownComponents(nav, person.knowledge) + return componentOf(first) === componentOf(last) + } } export function foodGoal(state: ValleyState, person: Forager, minute: number): TaskChoice | null { let best: TaskChoice | null = null, bestScore = -1, bestId = Infinity + const reachable = reachability(state, person) const consider = (id: number, kind: 'pick' | 'nuts' | 'fish', target: Point, rate: number, stock: number) => { if (rate <= person.rates.pickKcalPerHour || rate < bestScore) return const lowerTravel = estimateMinutes(state.config, person, target, walkSpeed(state.config, person) * 60, 0) @@ -174,7 +179,7 @@ export function foodGoal(state: ValleyState, person: Forager, minute: number): T const home = estimateMinutes(state.config, target, person.hearth, walkSpeed(state.config, person) * 60, 0) if (travel + home + 1 > state.config.duskHour * 60 - person.duskMarginMinutes - minuteOfDay(minute)) return const score = (3_600 * rate) / (travel * 60 + 3_600) - if ((score > bestScore || (score === bestScore && id < bestId)) && reachablePoint(state, person, target)) { + if ((score > bestScore || (score === bestScore && id < bestId)) && reachable(target)) { bestScore = score bestId = id best = workAt( @@ -238,6 +243,7 @@ function woodGoal(state: ValleyState, person: Forager, minute: number): TaskChoi let best = -1, bestMinutes = Infinity, bestStock = 0 + const reachable = reachability(state, person) for (let id = 0; id < state.layout.places.count; id += 1) { if (person.knownPlaces[id]! < 0) continue const kind = state.layout.places.kind[id] @@ -251,7 +257,8 @@ function woodGoal(state: ValleyState, person: Forager, minute: number): TaskChoi if (stock <= 0) continue const target = { x: state.layout.places.x[id]!, y: state.layout.places.y[id]! }, travel = estimate(state, person, target) - if (!reachablePoint(state, person, target)) continue + // Only a nearer place can win, so the costlier tests come after this one. + if (travel >= bestMinutes || !reachable(target)) continue if ( travel + estimateMinutes(state.config, target, person.hearth, walkSpeed(state.config, person) * 60, 0) + 1 > state.config.duskHour * 60 - person.duskMarginMinutes - minuteOfDay(minute) diff --git a/src/valley/routes.ts b/src/valley/routes.ts index 68bd2e8..b889d0c 100644 --- a/src/valley/routes.ts +++ b/src/valley/routes.ts @@ -133,7 +133,53 @@ export const onWalkableGround = (mesh: GroundMesh, p: Point) => walkableTriangle /** The known walkable triangle a person or place stands on, or -1. */ export function routeTriangle(nav: NavMap, knowledge: Knowledge, point: Point & { triangle?: number }): number { if (point.triangle !== undefined) return knows(knowledge, point.triangle) ? point.triangle : -1 - return walkableTriangle(nav.mesh, knowledge, point) + const { mesh } = nav + if (!Number.isInteger(point.x) || !Number.isInteger(point.y)) return walkableTriangle(mesh, knowledge, point) + // The same as `walkableTriangle`: the lowest known triangle holding the point, else the lowest known one near it. + const { inside, near } = groundAt(mesh, point) + for (const t of inside) if (knows(knowledge, t)) return t + for (const t of near) if (knows(knowledge, t)) return t + return -1 +} +const groundCache = new WeakMap>() +/** The walkable triangles holding a whole-centimetre point, and those within `NEAR_CM` of it, each in id order. */ +function groundAt(mesh: GroundMesh, p: Point) { + let cache = groundCache.get(mesh) + if (!cache) { + cache = new Map() + groundCache.set(mesh, cache) + } + const key = p.x * (mesh.sizeCm + 1) + p.y + let found = cache.get(key) + if (!found) { + found = { inside: [], near: [] } + const { bucketCm, buckets } = mesh + for ( + let by = Math.max(0, Math.floor((p.y - NEAR_CM) / bucketCm)); + by <= Math.min(buckets - 1, Math.floor((p.y + NEAR_CM) / bucketCm)); + by++ + ) + for ( + let bx = Math.max(0, Math.floor((p.x - NEAR_CM) / bucketCm)); + bx <= Math.min(buckets - 1, Math.floor((p.x + NEAR_CM) / bucketCm)); + bx++ + ) { + const bucket = by * buckets + bx + for (let k = mesh.bucketStart[bucket]!; k < mesh.bucketStart[bucket + 1]!; k++) { + const t = mesh.bucketTriangles[k]! + if (mesh.area[t] !== GROUND_AREA) continue + const d = triangleDistanceSq(mesh, t, p.x, p.y) + if (d === 0) found.inside.push(t) + else if (d <= NEAR_CM * NEAR_CM) found.near.push(t) + } + } + found.inside = [...new Set(found.inside)].sort((a, b) => a - b) + found.near = [...new Set(found.near)].sort((a, b) => a - b) + // People stop at many points; a bounded cache keeps a long run's memory flat. + if (cache.size >= 500_000) cache.clear() + cache.set(key, found) + } + return found } /** No water within `radiusCm` of the point, and the point inside the valley. */ export function circleWalkable(mesh: GroundMesh, p: Point, radiusCm: number) { diff --git a/src/valleyView/ValleyApp.tsx b/src/valleyView/ValleyApp.tsx index 6ec6ff5..32ab7df 100644 --- a/src/valleyView/ValleyApp.tsx +++ b/src/valleyView/ValleyApp.tsx @@ -1,11 +1,12 @@ import { TRAITS } from '../valley/nature' import { LandMap } from './LandMap' -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { SpecializationChart } from './SpecializationChart' import { TimeChart } from '../ui/charts' import { Icon } from '../ui/components' 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 { advanceDisplay, @@ -56,6 +57,8 @@ interface Snapshot { } const HUD_INTERVAL_MS = 100 +/** At map speeds no one walks on screen, and refreshing the panels had taken a quarter of the page's time. */ +const MAP_HUD_INTERVAL_MS = 500 const formatChange = (change: number) => change ? ` (${change > 0 ? '+' : '−'}${Math.abs(change).toLocaleString('en-US')})` : '' @@ -222,7 +225,7 @@ export default function ValleyApp({ drawn = true readyRef.current() } - if (now - lastHud >= HUD_INTERVAL_MS) { + if (now - lastHud >= (speed.map ? MAP_HUD_INTERVAL_MS : HUD_INTERVAL_MS)) { lastHud = now clearRef.current = measureClear(mount) if (now - rate.atMs >= 1_000) @@ -311,7 +314,6 @@ export default function ValleyApp({ const standing = state.groups.filter((made) => made.dissolvedMinute === null) const summary = foragerSummary(state, followed) const fire = fireSaving(config) - const days = daySeries(state, followed) const percent = (value: number) => `${(value / config.reserveMaxKcal) * 100}%` const foodLeft = daysOfFoodLeft(state, followed) const thirst = thirstLevel(state, followed) @@ -1015,88 +1017,7 @@ export default function ValleyApp({ - {days.length > 1 && ( - <> - String(Math.round(value))} - domain={[0, 'auto']} - series={[ - { key: 'highest', name: 'Wood costs, highest', color: TERMS_COLORS.forager }, - { key: 'lowest', name: 'Wood costs, lowest', color: TERMS_COLORS.gatherer }, - { key: 'followed', name: `Wood costs ${name}`, color: palette.accent, dashed: true }, - ]} - /> - String(Math.round(value))} - domain={[0, 'auto']} - series={[ - { key: 'swappedWood', name: 'Wood swapped each day, kg', color: palette.accent }, - { key: 'coldHours', name: 'Hours slept cold each day', color: palette.firmA, dashed: true }, - { key: 'alive', name: 'Alive', color: palette.household }, - ]} - /> - String(Math.round(value))} - domain={[0, 'auto']} - series={[ - { key: 'groups', name: 'Groups', color: palette.accent }, - { key: 'loners', name: 'Without a group', color: palette.firmA, dashed: true }, - ]} - /> - String(Math.round(value))} - domain={[0, 'auto']} - series={[ - { key: 'axesMade', name: 'Axes made each day', color: palette.accent }, - { key: 'axesSold', name: 'Axes sold each day', color: palette.positive }, - { key: 'hutsWhole', name: 'Huts whole', color: palette.firmA, dashed: true }, - ]} - /> - (value >= 1_000 ? `${Math.round(value / 1000)}k` : String(Math.round(value)))} - series={[ - { key: 'reserve', name: `${name}’s reserve at day’s end`, color: palette.accent }, - { key: 'stock', name: 'Berries per bush, kcal', color: palette.positive, dashed: true }, - ]} - /> - (value >= 1_000 ? `${Math.round(value / 1000)}k` : String(Math.round(value)))} - domain={[0, 'auto']} - series={[ - { key: 'nutsTaken', name: 'Nuts taken each day, kcal', color: palette.accent }, - { key: 'berriesTaken', name: 'Berries taken each day, kcal', color: palette.positive }, - { key: 'fishTaken', name: 'Fish taken each day, kcal', color: palette.household, dashed: true }, - ]} - /> - `${Math.round(value)}%`} - domain={[0, 100]} - series={[ - { key: 'hazelPercent', name: 'Nuts on the hazels, % of full', color: palette.accent }, - { - key: 'fishPercent', - name: 'Fish in inland water, % of full', - color: palette.household, - dashed: true, - }, - ]} - /> - - )} + @@ -1142,6 +1063,104 @@ export default function ValleyApp({ ) } +/** + * The run's history charts. They show finished days only, so they are drawn again only when a day ends, the followed + * forager changes or a new run starts, not at every refresh of the panels. + */ +const HistoryCharts = memo( + function HistoryCharts({ state, followed, name }: { state: ValleyState; followed: number; name: string }) { + const days = daySeries(state, followed) + if (days.length <= 1) return null + return ( + <> + String(Math.round(value))} + domain={[0, 'auto']} + series={[ + { key: 'highest', name: 'Wood costs, highest', color: TERMS_COLORS.forager }, + { key: 'lowest', name: 'Wood costs, lowest', color: TERMS_COLORS.gatherer }, + { key: 'followed', name: `Wood costs ${name}`, color: palette.accent, dashed: true }, + ]} + /> + String(Math.round(value))} + domain={[0, 'auto']} + series={[ + { key: 'swappedWood', name: 'Wood swapped each day, kg', color: palette.accent }, + { key: 'coldHours', name: 'Hours slept cold each day', color: palette.firmA, dashed: true }, + { key: 'alive', name: 'Alive', color: palette.household }, + ]} + /> + String(Math.round(value))} + domain={[0, 'auto']} + series={[ + { key: 'groups', name: 'Groups', color: palette.accent }, + { key: 'loners', name: 'Without a group', color: palette.firmA, dashed: true }, + ]} + /> + String(Math.round(value))} + domain={[0, 'auto']} + series={[ + { key: 'axesMade', name: 'Axes made each day', color: palette.accent }, + { key: 'axesSold', name: 'Axes sold each day', color: palette.positive }, + { key: 'hutsWhole', name: 'Huts whole', color: palette.firmA, dashed: true }, + ]} + /> + (value >= 1_000 ? `${Math.round(value / 1000)}k` : String(Math.round(value)))} + series={[ + { key: 'reserve', name: `${name}’s reserve at day’s end`, color: palette.accent }, + { key: 'stock', name: 'Berries per bush, kcal', color: palette.positive, dashed: true }, + ]} + /> + (value >= 1_000 ? `${Math.round(value / 1000)}k` : String(Math.round(value)))} + domain={[0, 'auto']} + series={[ + { key: 'nutsTaken', name: 'Nuts taken each day, kcal', color: palette.accent }, + { key: 'berriesTaken', name: 'Berries taken each day, kcal', color: palette.positive }, + { key: 'fishTaken', name: 'Fish taken each day, kcal', color: palette.household, dashed: true }, + ]} + /> + `${Math.round(value)}%`} + domain={[0, 100]} + series={[ + { key: 'hazelPercent', name: 'Nuts on the hazels, % of full', color: palette.accent }, + { + key: 'fishPercent', + name: 'Fish in inland water, % of full', + color: palette.household, + dashed: true, + }, + ]} + /> + + ) + }, + (before, after) => + before.followed === after.followed && + before.name === after.name && + before.state.layout === after.state.layout && + before.state.days.length === after.state.days.length, +) + /** Carried food by kind, as a phrase: "1,200 kcal of nuts and 300 of fish". */ function carriedPhrase(food: { berries: number; nuts: number; fish: number }) { const parts = (['nuts', 'berries', 'fish'] as const).filter((kind) => food[kind] > 0) diff --git a/src/valleyView/playback.test.ts b/src/valleyView/playback.test.ts index 035fab0..0912e01 100644 --- a/src/valleyView/playback.test.ts +++ b/src/valleyView/playback.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from 'vitest' import { FLAT_LAND } from '../valley/config' +import { stepValley } from '../valley/engine' import { createSurveyedValley } from '../valley/ruleFixtures' import { advanceDisplay, foragerPose, mapSpeedMinutesPerSecond, routePoints, - SIMULATION_SLICE_MINUTES, startDisplay, VALLEY_SPEEDS, type Display, @@ -57,22 +57,35 @@ describe('drawing people from task records', () => { expect(walked).toBeGreaterThan(0) }) - it('runs the engine in hour steps until the frame budget is spent, and at least one step a frame', () => { + 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 start0 = start().state.minute - // Each clock reading is 10 ms later: four steps fit within 40 ms, and the clock stops at the last one finished. - let display: Display = advanceDisplay(start(), 0.25, { minutesPerSecond: 1_440 }, 40, ticking(10)) - expect(display.minute).toBe(start0 + 4 * SIMULATION_SLICE_MINUTES) + 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) - display = advanceDisplay(display, 0.25, { minutesPerSecond: 1_440 }, 40, ticking(100)) - expect(display.minute).toBe(start0 + 5 * SIMULATION_SLICE_MINUTES) - // With time to spare, the frame reaches the minute wanted. + // 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(start0 + 5 * SIMULATION_SLICE_MINUTES + 144) + 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('stops drawing people from map speeds up', () => { diff --git a/src/valleyView/valleyScene.ts b/src/valleyView/valleyScene.ts index f5852eb..60bcd2d 100644 --- a/src/valleyView/valleyScene.ts +++ b/src/valleyView/valleyScene.ts @@ -1785,10 +1785,13 @@ export async function createValleyScene(mount: HTMLElement, callbacks: SceneCall for (const ring of siteRings(state, followedId)) { const loop = siteLoops[ring.site] if (!loop) continue - const spot = at(ring.x, ring.y) loop.visible = true loop.material = ring.fresh ? freshSiteMaterial : staleSiteMaterial + // A place and its radius never move, so its ring is draped on the ground once. + if (loop.userData.draped) continue + const spot = at(ring.x, ring.y) drapeLoop(loop, spot.x, spot.z, ring.radiusCm / 100 + 1.5, 0.06) + loop.userData.draped = true } } diff --git a/src/valleyView/valleyViewModel.ts b/src/valleyView/valleyViewModel.ts index c4fe6a4..334402f 100644 --- a/src/valleyView/valleyViewModel.ts +++ b/src/valleyView/valleyViewModel.ts @@ -73,17 +73,11 @@ export const MAX_FRAME_SECONDS = 0.25 */ export const SIMULATION_FRAME_BUDGET_MS = 40 -/** - * A frame runs the engine in steps of at most this many minutes, checking its budget between them, so no frame runs far - * past its budget. Early in a run a step takes about a millisecond; later, as people know more ground and plan longer - * routes, an hour can take hundreds, so steps are short. - */ -export const SIMULATION_SLICE_MINUTES = 15 - /** * Advances the displayed minute by the wall time elapsed at `speed`, running the engine up to the last whole minute at - * or before it. When the engine cannot keep up within `budgetMs`, it stops at the last step finished, and the clock - * advances less. + * 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. */ export function advanceDisplay( display: Display, @@ -96,9 +90,7 @@ export function advanceDisplay( const toMinute = Math.floor(target) if (toMinute <= display.state.minute) return { state: display.state, minute: target } const started = now() - let state = display.state - do state = stepValley(state, Math.min(toMinute, state.minute + SIMULATION_SLICE_MINUTES)) - while (state.minute < toMinute && now() - started < budgetMs) + const state = stepValley(display.state, toMinute, () => now() - started >= budgetMs) return { state, minute: state.minute < toMinute ? state.minute : target } } @@ -1066,16 +1058,33 @@ export const daySeries = (state: ValleyState, foragerId: number) => * mesh triangle it has never seen dark, and the rest clear, since known ground stays known. Values are 0–255. */ export function knowledgeShades(state: ValleyState, foragerId: number) { - const { terrain, nav } = state.layout const knowledge = state.foragers[foragerId]!.knowledge - const shades = new Uint8Array(terrain.cells * terrain.cells) - for (let row = 0; row < terrain.cells; row += 1) - for (let col = 0; col < terrain.cells; col += 1) { - const t = triangleAt(nav.mesh, (col + 0.5) * terrain.cellCm, (row + 0.5) * terrain.cellCm) - shades[row * terrain.cells + col] = t >= 0 && knows(knowledge, t) ? 0 : 150 - } + const cellTriangles = cellTrianglesOf(state.layout) + const shades = new Uint8Array(cellTriangles.length) + for (let cell = 0; cell < cellTriangles.length; cell += 1) { + const t = cellTriangles[cell]! + shades[cell] = t >= 0 && knows(knowledge, t) ? 0 : 150 + } return shades } +const cellTriangleCache = new WeakMap() +/** The triangle at the centre of each terrain cell, found once per layout: the search is the costly part of shading. */ +function cellTrianglesOf(layout: ValleyState['layout']) { + let cells = cellTriangleCache.get(layout) + if (!cells) { + const { terrain, nav } = layout + cells = new Int32Array(terrain.cells * terrain.cells) + for (let row = 0; row < terrain.cells; row += 1) + for (let col = 0; col < terrain.cells; col += 1) + cells[row * terrain.cells + col] = triangleAt( + nav.mesh, + (col + 0.5) * terrain.cellCm, + (row + 0.5) * terrain.cellCm, + ) + cellTriangleCache.set(layout, cells) + } + return cells +} /** The part of the view, in pixels from its top left, that the cards over it leave clear. */ export interface ClearView {