From c961222b510e3fc96c339a00e48e8f9c4b0ef11e Mon Sep 17 00:00:00 2001 From: NeoLorenzo Date: Tue, 27 Oct 2026 22:30:14 +0000 Subject: [PATCH 1/2] feat(life15): plan coarse routes through pieces of known ground [LIFE15-Planning-068] --- CHANGELOG.md | 9 +++ LAB_NOTES.md | 14 ++++ docs/ARCHITECTURE.md | 2 +- docs/LIFE15_SPEC.md | 73 ++++++++++++----- docs/VALIDATION.md | 2 +- src/valley/fingerprintRuns.ts | 76 ++++++++--------- src/valley/invariants.ts | 1 + src/valley/perception.ts | 5 +- src/valley/routes.ts | 148 +++++++++++++++++++++++++--------- src/valley/ways.test.ts | 58 +++++++++++-- 10 files changed, 285 insertions(+), 103 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35aae1a..d4f1296 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ 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-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. +- The full search stays only as a guard; a walk that needed it is recorded as `full`, and the checker rejects it. +- Pieces are worked out from knowledge when needed, cached per knowledge, and carried forward at each survey by dropping only the chunks where triangles were learnt. +- Every trajectory changes: new fingerprints are recorded for every configuration except the flat land, which is unchanged. +- New unit fixtures: a coarse plan round a wall of unknown ground, a chunk split into two pieces, a plan between two pieces of one chunk, and the checker rejecting a `full` walk. +- The Life 15 specification is revised for update 068. + ## [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. diff --git a/LAB_NOTES.md b/LAB_NOTES.md index 885d641..bd93230 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-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. + +**The cause, counted on the canonical forty, seed 20260813, in whole-day steps.** From day 12, most route-search work was the search over everything a person knew, run when a band search failed. On day 13 there were 980 new plans, and 328 band searches failed, 268 of them walks to a frontier; the full searches expanded 11.3 million triangles against 2.5 million in bands. On day 30, 18 failures still made three-quarters of the search work (0.43 against 0.14 million). The band failed because two chunks counted as linked whenever the person knew ground on both sides of any edge between them, though that ground could be separate patches inside a chunk, as it often is at the edge of what someone knows and around water. + +**After.** No walk on the canonical run needs the full search; every fingerprint run is checked with the guard rejected. Over the first 30 days, 6,123 coarse plans are no longer than the shortest path over the walker's known ground at the median, 9.0% longer at the 95th percentile and 20.8% at most. Whole-day times, before → after: day 12 2.0 → 1.9 s, day 13 4.6 → 2.5 s, day 16 1.7 → 1.2 s, day 30 347 → 249 ms. Days 11 to 17 now take 0.4–2.5 s, and days 20 to 45 about 180–420 ms. In off-screen Chrome on a production build at 1 month/s, from day 46: 15.9 frames and 3.2 days a second, against 15.6 frames and 2.4 days a second at update 067. The new run reached day 46 in 18 s from the start. + +**Short of the spec's expectation.** The spec expected the slow days at about 1–1.5 s. Day 12 barely improved: it had few failures (86) but about 8,500 wake-ups and 1,600 cutting and carrying walks for huts, and about 800 band searches a day still cost a millisecond each. A profile of days 12–13 after the change: route search 32% (of which A\* 25%), observation 25%, garbage collection 10%, choosing tasks 9%. + +**Speed work tried and dropped.** The spec allowed speed-ups that leave the trajectory unchanged, kept only if they measurably help. Skipping chunks wholly beyond sight in a survey, and reusing the A\* heap between searches, each left the fingerprints unchanged and changed day times by no more than run-to-run noise, so both were removed. What remains costly is the amount of work people do (band searches, surveys), not waste in doing it, so further gains need rules that change behaviour, or the engine moved off the main thread. + +**Not checked.** In the built-in browser, which was hidden and so throttled, the run played with a clean console, but a walk round a lake was not picked out by eye; the unit fixtures cover it. + ## [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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5901a27..cf9d776 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -89,7 +89,7 @@ The 3D world draws each firm and Government across its plot: `buildingScale` str - **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. - **Places.** `places.ts` and `layout.ts` place berry and hazel thickets, wood stands and stone outcrops as aggregate stocks, indexed by place id, with their own regrowth (`logRegrowth` keeps each felled tree's schedule). The terrain, water, shore geometry and fish of Life 11 (`terrain.ts`, `water.ts`, `banks.ts`, `fish.ts`) are kept unchanged. - **Ground mesh.** `mesh.ts` builds, once per layout, a constrained Delaunay triangulation (Delaunator and Constrainautor, pinned) over the whole valley: the hydrology's shorelines simplified to within `shoreToleranceCm`, relief vertices from a quadtree of squares from `meshMaxEdgeCm` down to one terrain cell, and refinement until every dry 5 m point is within `meshHeightToleranceCm` of the terrain. Each triangle has an area type (ground, lake or river), neighbours, a chunk and a region; the largest walkable region is the main land, where founders start. The mesh is cached per terrain and checked once by `meshViolations`. -- **Knowledge and routes.** `perception.ts` records what a person sees at a wake-up: mesh triangles, places with their stock, bank points and other people. Triangle knowledge is a bitset shared between a state and its copy until its holder learns something. `routes.ts` runs A\* over known ground triangles, pulls the path straight through the corridor with the funnel algorithm, and cuts it at triangle edges into segments with their slope and walking time. Bank points sit on the ground side of each shore edge. A new route is planned coarse to fine: an A* over the mesh's chunks, linked only across ground the person knows on both sides (`ChunkLinks`, precomputed per mesh), gives a band of chunks, and the triangle search stays inside it, falling back to the whole known ground when the band holds no path. The still landscape is surveyed again only after moving `resurveyCm` (100 m) from the last survey point; stock at the person's place, people and fires are seen at every wake-up. +- **Knowledge and routes.** `perception.ts` records what a person sees at a wake-up: mesh triangles, places with their stock, bank points and other people. Triangle knowledge is a bitset shared between a state and its copy until its holder learns something. `routes.ts` runs A\* over known ground triangles, pulls the path straight through the corridor with the funnel algorithm, and cuts it at triangle edges into segments with their slope and walking time. Bank points sit on the ground side of each shore edge. A new route is planned coarse to fine: an A* over the person's pieces, the joined-up patches of known ground within each chunk, linked across chunk borders only where the person knows ground on both sides (`ChunkLinks`, precomputed per mesh), gives a band of chunks, and the triangle search stays inside it. A chain of pieces is joined-up known ground, so the band always holds a path; the search over the whole known ground remains only as a guard, recorded as a `full` walk, which the checker rejects. Pieces are derived from knowledge, cached per knowledge and carried forward at each survey by dropping only the chunks where triangles were learnt. The still landscape is surveyed again only after moving `resurveyCm` (100 m) from the last survey point; stock at the person's place, people and fires are seen at every wake-up. - **Ways.** `ways.ts` keeps each person's remembered ways: immutable corridors of triangles between two ends (the hearth, a place, a known bank point), at most `waysRemembered` (64), the least recently used forgotten first. A walk to such an end takes a way that holds the walker's triangle, whole or joined part-way, in either direction; the route is pulled straight along the way's corridor at the walker's current load. A way is planned again once a day has passed and the person has seen new ground since, or at once if it crosses ground no longer known. Walk events record whether the walk used a way, joined one or planned a new one. An idle person with nothing to explore takes one leisure walk a day along the way from home used longest ago (`leisureMinute`), goes home when away, and otherwise rests. - **Tasks and lazy bodies.** `tasks.ts` builds a `TaskRecord` (kind, start and end minute, place, route, reason, starting body and load). `body.ts` gives energy and water at any minute of a task in closed form (`energyAt`, `waterAt`), and `positionAt` gives the position along its route. Nobody is advanced minute by minute. Food, wood, fire, huts, axes, trade and practice (`food.ts`, `work.ts`, `fire.ts`, `huts.ts`, `axes.ts`, `trade.ts`, `practice.ts`, `social.ts`) apply their rules when a task settles or two people meet. - **Checker.** `invariants.ts` checks each interval against the preceding immutable state. `replay.ts` keeps separate stock, fish, body, tool, hut and water ledgers, replays recorded transfers and regrowth, and compares them with the returned state. Geography is checked once. diff --git a/docs/LIFE15_SPEC.md b/docs/LIFE15_SPEC.md index dc6845c..d825b2e 100644 --- a/docs/LIFE15_SPEC.md +++ b/docs/LIFE15_SPEC.md @@ -1,6 +1,6 @@ -# [LIFE15-Habits-066] +# [LIFE15-Planning-068] -**Draft for the owner's approval, 2026-10-27.** This specification replaces the Life 14 specification 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. It is implemented as one pull request. +**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. 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. @@ -9,7 +9,7 @@ Time is one clock in minutes. Nobody is stepped: a person is woken when their ta ## What Life 15 makes possible - **People walk the ways they know.** Until now every walk was planned from nothing, as the best path over all the ground the person had ever seen, as if they studied a perfect map before every step. Real people learn a few routes between the places they use, take them again, and join a familiar route when they find themselves on it (Siegel and White 1975; Golledge 1999). Each person now remembers **ways**: the line of ground they walked from a starting point to a place, a bank or home. A walk to the same place, or back from it, takes the remembered way, or the rest of a way they are standing on. -- **People plan coarsely, then in detail.** When no way is known, a person first picks a chain of 200 m squares of known land that leads there, then the exact path within that band, as someone thinks "over the ridge, round the lake" before choosing their footing. If the band holds no path, they plan over everything they know, as before. +- **People plan coarsely, then in detail.** When no way is known, a person first picks a chain of pieces of known land, each within a 200 m square, that leads there, then the exact path within that band, as someone thinks "over the ridge, round the lake" before choosing their footing. Because each piece is ground the person knows to be joined up, the chain always holds a path (update 068). - **People notice shortcuts slowly.** A remembered way is reconsidered at most once a day, and only if the person has seen new ground since they planned it. Until then they keep to it, even if a better path has just come into view. - **People look again only when they have moved.** The still landscape in sight (ground, banks, thickets, stands, outcrops) is surveyed again only once the person has moved 100 m from where they last surveyed it. People, fires, flags and huts, and the stock where the person stands are noticed at every wake-up, as before. - **Why now.** In the canonical run, the engine is about 400 times slower per simulated hour on day 12 than on day 2: in four midday hours of day 12 people searched 1,675 routes, every one planned anew, none repeating an earlier search (update 065). Planning every walk from scratch is both unrealistic and the largest single cost of a late day. Fixing it now, before relationships add more walking, keeps later steps runnable. @@ -17,20 +17,45 @@ 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 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: + +| Day | Time | New plans | Band searches that failed | Triangles searched in bands | Triangles searched in full searches | +| --- | --- | --- | --- | --- | --- | +| 5 | 124 ms | 56 | 0 | 14,567 | 0 | +| 12 | 2.0 s | 733 | 86 | 0.77 million | 1.48 million | +| 13 | 4.6 s | 980 | 328 | 2.46 million | 11.26 million | +| 16 | 1.7 s | 307 | 128 | 0.75 million | 5.16 million | +| 30 | 347 ms | 110 | 18 | 0.14 million | 0.43 million | + +On every day from 12, most of the route-search work is the full search, run after a band search finds no path. On day 13, 268 of the 328 failures were walks to a frontier, exploring. The band fails because the coarse plan links two 200 m squares whenever the person knows ground on both sides of any edge between them, without asking whether that ground is joined up inside the square. Near the edge of what a person knows, and around lakes and streams, a square often holds two or more separate patches of known ground: the chain passes through the square on paper, but no path does. The person then searches everything they know, about 34,000 triangles on average on day 13. + +**The change.** The coarse plan moves from squares to **pieces**: the patches of joined-up known ground within each square. Two pieces are linked when known ground in one shares an edge with known ground in the other. A chain of linked pieces is a path on known ground by construction, so the fine search in the band around it always succeeds, and the full search is no longer needed. People still plan "over the ridge, round the lake" first; they now plan only through land they know they can cross, which is closer to how people reason about routes they know (Golledge 1999) and to hierarchical path planning over connected regions (Botea et al. 2004). + +**What was expected, and what was measured.** The full searches, 11.3 million triangles on day 13 and 0.43 million on day 30, go; the walks they served are planned in a band instead. The slow days were expected to fall to roughly 1–1.5 s; measured, days 11 to 17 take 0.4–2.5 s (day 13: 4.6 → 2.5 s), and ordinary days gained about a quarter (day 30: 347 → 249 ms). Day 12 barely changed, because its cost was hut-building walks and the band searches themselves, not failures. This update does not by itself reach 30 ms a day. + +**Who notices.** Walks that used to be planned over everything known are now planned in a band, and may be slightly longer than the shortest known path, as coarse plans already are. Every run's trajectory changes except on the open flat land, where no chunk is ever split; nothing else about people changes. + +### Speed work + +After the behaviour change and its new fingerprints, each further speed-up must leave every fingerprint unchanged and be kept only if it measurably helps. They are chosen from the profiles at days 13 and 30, not in advance. None of them changes what people do. Measured: after the change, days 12–13 spend 32% of the time in route search, 25% in observation, 10% in garbage collection and 9% choosing tasks. Skipping chunks beyond sight in a survey and reusing the A\* heap left the fingerprints unchanged but did not measurably help, so neither was kept. The remaining cost is the work people do, not waste in doing it. + ## Checked against | Measure | Evidence and comparison | Status | | --- | --- | --- | | Route choice | People rarely take the shortest path. Most commuters keep to habitual routes longer than the shortest one (Zhu and Levinson 2015); pedestrians choose by familiarity and simple rules such as "head roughly the right way" more than by distance (Golledge 1995; Hölscher et al. 2011). | Magnitudes, measured once on the canonical seed: how much longer walks on a remembered way are than the shortest path over the walker's known ground at that minute, as a median and the largest. A median within about 10% is expected; a large excess is examined in the lab notes, not tuned away. | | Reuse | Habit: most trips go between a few familiar places along familiar routes (Golledge 1999). | Recorded once on the canonical seed: the share of walks by how they were found (a remembered way, a joined way, a coarse plan, a full plan), day by day. Most walks to places are expected to use a way after the first days. | -| Coarse planning | Planning by regions before footing gives routes close to the shortest when regions are small against the trip (hierarchical path planning, Botea et al. 2004). | Recorded once: the share of new plans that needed the full search, and how much longer coarse plans are than full ones on the same walks. | Mesolithic Europe, from skeletons: men about 165 cm and women about 154 cm, each with a spread of about 6 cm (Formicola and Giannecchini 1999; Ruff 2018). The forty founders' means lie within 3 cm of these, and the sexes do not overlap much more than real ones. | Magnitudes; checked once on the canonical seed, and by a unit test over 10,000 draws. | +| Coarse planning | Planning by regions before footing gives routes close to the shortest when regions are small against the trip (hierarchical path planning, Botea et al. 2004). | Recorded once on the canonical seed: how much longer coarse plans are than the shortest path over the walker's known ground at that minute, as a median and the largest. From update 068 no plan needs the full search. | +| Adult height | Mesolithic Europe, from skeletons: men about 165 cm and women about 154 cm, each with a spread of about 6 cm (Formicola and Giannecchini 1999; Ruff 2018). The forty founders' means lie within 3 cm of these, and the sexes do not overlap much more than real ones. | Magnitudes; checked once on the canonical seed, and by a unit test over 10,000 draws. | | Adult body mass | Mesolithic Europe, estimated from skeletons: men about 62 kg, women about 52 kg (Ruff 2018). | As above. | | Strength | Grip strength, the standard field measure, among forager-horticulturalists (Tsimane, Hadza, Agta): men about 38 kg, women about 24 kg, with women's strength about 60% of men's (Gurven et al. 2006; Apicella 2014). | As above. | | Body correlations | Within each sex, height with weight about 0.55, height with grip about 0.35, weight with grip about 0.40. | A unit test over 10,000 draws, each within 0.05. | | Trait correlations | The meta-analysis of the five traits across 212 samples (van der Linden et al. 2010): openness with extraversion 0.43, conscientiousness with agreeableness 0.43, conscientiousness with neuroticism −0.43, extraversion with neuroticism −0.36, agreeableness with neuroticism −0.36, conscientiousness with extraversion 0.29, agreeableness with extraversion 0.26, openness with agreeableness 0.21, openness with conscientiousness 0.20, openness with neuroticism −0.17. | A unit test over 10,000 draws, each within 0.05. | | What the traits do | Extraverts seek contact more (Asendorpf and Wilpers 1998); agreeable people offer fairer splits in bargaining games (Ben-Ner et al. 2004); conscientious people plan and store; neurotic people avoid risk; open people seek novelty. | Direction only: each trait's rule has a unit fixture showing the direction. The strengths of the effects are judgement, not calibration, and are listed as questions for later. | | Carrying | Forager women carry loads of 15 to 25 kg for hours, men more; women's load capacity is closer to men's than their grip is (Hadza and !Kung loads; Lee 1979; Marlowe 2010). | Magnitudes. | -| Speed | A year of forty people in about a second, as since Life 12. | Not expected to be met by this step alone. Life 14's canonical ninety-day year took 852.90 s with an 8 GB Node heap (update 064). Measured once and recorded: the canonical year's time and memory, and a profile of day 12, where route search should no longer be the largest cost. | +| Speed | A year of forty people in about a second, as since Life 12; in the browser, a month a second, which needs about 30 ms a simulated day. | Not met by this step. After update 068, in whole-day steps, days 11 to 17 take 0.4–2.5 s and days 20 to 45 about 180–420 ms; in off-screen Chrome at 1 month/s, 3.2 days a second. Measured once and recorded: each of the canonical first 45 days' time, the canonical year's time and memory, and profiles of days 13 and 30 against update 067's. | ## Design decisions @@ -47,8 +72,10 @@ This step changes how people find and keep their way, and how often they look ar | A remembered way is reconsidered when it is about to be used, if `wayRecheckMinutes` (one day) has passed since it was planned and the person's knowledge has grown since. Otherwise it is used as it is, even if a shorter path is now known. | Rules 2 and 10: local, not optimal, decisions, and learning through experience. People notice a shortcut eventually, not the instant it comes into sight. Once a day bounds re-planning per way. | | A way whose triangles are not all still walkable and known to the person is dropped and planned afresh. | Nothing can block a way in this step, because the ground does not change and knowledge only grows; the rule is for floods, fences and palisades later, and costs one pass over the corridor. | | An idle person who has nothing new to explore no longer tours the places they know. Once a day they walk out along a remembered way from home, the one used longest ago, and otherwise go home and rest. | Foragers spend much of the day resting and in company at camp (Hawkes et al. 1997; Marlowe 2010), and learn the state of patches while out foraging, not by inspecting every one daily. In Life 14 an idle person walked to every known place unchecked for a day, about 210 short walks a day each from day 13, which also made late days slow. A walk along a known way needs no planning, and refreshes the memory of the place at its far end. | -| A new plan is coarse first: an A\* over chunks the person knows to be linked, then the fine A\* restricted to triangles whose chunks are on the chunk path or next to it. If the band holds no path, the fine A\* runs over all known triangles, as before. | People plan by regions before footing (Golledge 1999). The band keeps a fine search to a few chunks instead of the whole known valley. The fallback keeps every reachable target reachable. | -| Two chunks are linked for a person when a known walkable triangle in one shares an edge with a known walkable triangle in the other. A triangle belongs to the chunk holding its centroid. The coarse cost is the distance between chunk centres, ties by chunk number. | It uses only what the person knows (rule 1). The edges crossing between chunks are listed once per mesh, so a link is a check of a short list. | +| A new plan is coarse first: an A\* over the person's pieces of known ground, then the fine A\* restricted to triangles whose chunks are on the chain of pieces or next to it. (Update 068; before, the coarse A\* ran over whole chunks, and when the band held no path the fine A\* ran over all known triangles.) | People plan by regions before footing (Golledge 1999). The band keeps a fine search to a few chunks instead of the whole known valley. A chain of joined-up pieces always holds a path, so every target on the person's known ground is reached without searching all of it. | +| A person's piece is a largest set of their known walkable triangles in one chunk joined to each other by shared edges within that chunk; it is numbered by its lowest triangle id. Two pieces in different chunks are linked when a known walkable triangle in one shares an edge with one in the other. A triangle belongs to the chunk holding its centroid. The coarse cost is the distance between chunk centres, ties by piece number. | It uses only what the person knows (rule 1), and only ground they know to be joined, so the coarse plan never promises a crossing that is not there. Linking whole chunks failed whenever a chunk held two separate patches of known ground, which on day 13 sent a third of all new plans to a search of everything known. | +| Pieces are worked out from the person's knowledge when needed and not stored in the state; only the chunks holding newly learnt triangles are worked out again. | They follow from knowledge alone, so keeping them would add state that could disagree with it. Most chunks change rarely once known. | +| The full search over all known ground stays only as a guard: if the band ever held no path, the walk is planned in full and recorded as `full`, and the checker rejects it. | By construction it never runs. A guard that a checked run rejects finds a mistake in the pieces without stopping an unchecked run in the browser. | | The still landscape is surveyed again only once the person stands `resurveyCm` (100 m) or more from where they last surveyed it. People, people-made places and the stock where the person stands are looked at every wake-up. | Ground, water, thickets and stands do not move; looking again over the same kilometre from the same spot learns almost nothing. 100 m is a tenth of the sight radius: what is missed at the edge of sight is learnt on the next move. | | The route cache by exact end points, knowledge revision and load is removed. | Ways replace it. It was almost never reused, because a start a centimetre away or one newly seen triangle made a new key. | | Travel estimates for choosing targets stay straight-line lower bounds. | A person judges how far a place is before walking; the way is what they then walk. | @@ -245,15 +272,15 @@ When a walk to a target starts, in this order: - if it has a triangle that is no longer walkable or known to the person, it is forgotten and the search goes on to step 2; - if `wayRecheckMinutes` have passed since it was planned and the person's knowledge revision has changed since, it is planned afresh by step 2, and the new way replaces it; - otherwise the walk takes the part of the corridor from the walker's triangle to the target's end, reversed if the target is the way's start. It is a **way** walk if the walker stands at the way's other end, and a **joined** walk otherwise. -2. **A coarse plan.** If start and target lie in different chunks, an A\* over chunks finds a chain from the start's chunk to the target's, moving only between chunks linked for the person, costed by the distance between chunk centres, ties by chunk number. The band is the chain's chunks and every chunk next to one of them, side or corner. The fine A\* then runs over the person's known walkable triangles in the band. If both succeed, it is a **coarse** walk. If start and target share a chunk, the band is that chunk and its neighbours. -3. **A full plan.** If the chunk chain or the band's search fails, the fine A\* runs over all the person's known walkable triangles, as in Life 14. It is a **full** walk. +2. **A coarse plan.** If start and target lie in different pieces of the person's known ground, an A\* over pieces finds a chain from the start's piece to the target's, moving only between linked pieces, costed by the distance between their chunk centres, with the distance from a piece's chunk centre to the target's as the estimate, ties by piece number. If they lie in the same piece, the chain is that piece. The band is the chain's chunks and every chunk next to one of them, side or corner. The fine A\* then runs over the person's known walkable triangles in the band. It is a **coarse** walk. +3. **The guard.** A chain exists whenever start and target are on one piece of known ground, and the band then always holds a path. If the band's search failed all the same, the fine A\* would run over all the person's known walkable triangles and the walk be recorded as **full**; a checked run rejects it. 4. If the target is unknown or unreachable, the person walks to the nearest known frontier, or rests with `no known route`, as before. **Leisure.** A person idle at their hearth (priority 9, no frontier in range), who has not set out on a leisure walk this calendar day, takes the remembered way with an end at their hearth that was used longest ago (ties by lowest number) whose far end can be reached and left for home before dusk, less their dusk margin, by the straight-line estimate. They walk it to its far end, `out for a walk`, and the walk's start records the minute in `leisureMinute`. Idle away from their hearth, they walk home, `going home to rest`. Idle at home otherwise, they rest. A person with no such way rests. The fine A\* is Life 14's: costed by the distance between the midpoints of the edges crossed, ties by triangle id. Before a fine search, the person's known pieces of ground are compared as before; targets on another piece go straight to step 4. A coarse, full or rechecked plan to a place, bank point or hearth is remembered as a way between the walk's start and the target, replacing any way with the same two end points; when the person holds `waysRemembered` ways, the one used longest ago is forgotten first, ties by lowest number. Using a way sets its last-used minute. Walks to a frontier are never remembered. -Two chunks are linked for a person when one of the mesh's chunk-crossing edges, listed once per layout, joins two triangles the person knows and may walk on. A triangle's chunk is the chunk holding its centroid. +A person's pieces are found within each chunk: known walkable triangles of the chunk sharing an edge belong to one piece, numbered by its lowest triangle id. Two pieces are linked when one of the mesh's chunk-crossing edges, listed once per layout, joins a triangle of one to a triangle of the other. A triangle's chunk is the chunk holding its centroid. Pieces and links are worked out from the person's knowledge, never stored, and only for chunks where the person has learnt triangles since they were last worked out; they cannot change any result. Speed is the person's flat loaded speed, above; moderate slopes divide it by `moderateSlowdownPerMille/1,000` uphill; steep slopes halve it uphill and divide by `steepDownSlowdownPerMille/1,000` downhill; ground multiplies time by Life 11's terrain percentages. Walking costs the person's walking rate on the flat, one and a half times that on moderate uphill and twice on steep. A walk's duration is summed in integer 1/60,000-minute units and rounded up at its end; remainders carry. The path, its pieces and their times are computed afresh for every walk from its corridor, the walker's position and their load. @@ -360,7 +387,7 @@ The checker replays the events of each `stepValley` interval against the state i - **The mesh, once per layout:** as Life 13: winding, areas, neighbours, shores, shore heights, shoreline and heights within tolerance, places and banks on walkable ground. - **Bodies and traits:** every person's sex is 0 or 1; height, weight and grip lie within three spreads of their sex's mean; trait scores lie within −3,000…3,000; and the stored load capacity, rate table, thirst thresholds, company radius, exchange rule inputs, stock target, satiation level, dusk margin, exploring range and expected share equal those recomputed from the scores and the configuration. None changes during a run. - Every wake-up's body charge equals the person's own rates for the task over its minutes, with bounded remainders; energy and water at a wake-up equal the lazy functions evaluated there. -- **Ways:** every person holds at most `waysRemembered` ways, no two with the same end points; every way's corridor is a chain of triangles each sharing an edge with the next, every one walkable and known to the person, its first and last holding its end points; numbers are below the person's next way number; last-used minutes are not in the future. Every walk recorded as a way or joined walk stays within the triangles of the way it names. The checker does not recompute the coarse band or the recheck rule; unit fixtures cover both. +- **Ways:** every person holds at most `waysRemembered` ways, no two with the same end points; every way's corridor is a chain of triangles each sharing an edge with the next, every one walkable and known to the person, its first and last holding its end points; numbers are below the person's next way number; last-used minutes are not in the future. Every walk recorded as a way or joined walk stays within the triangles of the way it names. No walk is recorded as `full` (update 068). The checker does not recompute the pieces, the coarse band or the recheck rule; unit fixtures cover them. - **Leisure:** nobody sets out on two leisure walks in one calendar day, and `leisureMinute` is the start of the last one. - **Survey:** each observation is replayed against the rule: it is a survey exactly when the person had no survey point or stood at least `resurveyCm` from it, and the survey point changes only at a survey, to where they stood. - No person's trip wood exceeds their load capacity. @@ -371,7 +398,7 @@ The checker replays the events of each `stepValley` interval against the state i - Every decision reads memory only. - Hunger and thirst hysteresis with the person's own levels, death minute and cause, and group dissolution below two living members follow the stated order. -Events are as Life 14; a walk's start records how it was found (`plan`: `way`, `joined`, `coarse` or `full`; a walk to a frontier is coarse or full), whether a way was dropped and planned again (`rechecked`), and the way it used (`wayId`, −1 for a new plan). An observation records whether it was a survey. Daily summaries and world metrics are as Life 14. +Events are as Life 14; a walk's start records how it was found (`plan`: `way`, `joined`, `coarse`, or `full` only from the guard; a walk to a frontier is coarse), whether a way was dropped and planned again (`rechecked`), and the way it used (`wayId`, −1 for a new plan). An observation records whether it was a survey. Daily summaries and world metrics are as Life 14. ## Observer @@ -400,6 +427,8 @@ Unchanged from Life 14: Bodies and traits (`nature.ts`), the terrain, hydrology and mesh (`terrain.ts`, `water.ts`, `mesh.ts`) are unchanged. The MVP9 core is unchanged. +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. + ## 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. @@ -411,11 +440,13 @@ New unit fixtures: 3. Recheck: on a fixture where new ground opens a shorter path, the way is kept within a day of planning, replaced after a day, and kept after a day when nothing new was seen. 4. Forgetting: with `waysRemembered` ways held, a new way forgets the one used longest ago; a new way between the same end points replaces the old one. 5. Load: the same way walked loaded and unloaded has the same corridor and different times. -6. Coarse planning: on an open fixture the corridor lies in the band of the chunk chain; on a fixture where a strip of unknown ground walls off the band, the full search finds the way round and the plan is full. -7. Chunk links: two chunks are linked only when the person knows walkable triangles on both sides of a crossing edge. -8. Survey: a person who has moved less than 100 m learns no new triangles; after moving 100 m they learn what came into sight. -9. The checker rejects a way through an unknown triangle, a corridor with a gap, one way too many, and a survey recorded against the rule. -10. Leisure: an idle person at home with nothing to explore walks out along the way from home used longest ago, once a calendar day; away from home they walk home to rest; with no time to return before dusk they rest. +6. Coarse planning: on an open fixture the corridor lies in the band of the chain; on a fixture where a strip of unknown ground walls off the straight way, the chain goes round it and the plan is coarse, not full. +7. Pieces and links: a chunk whose known ground is split by unknown or unwalkable ground holds two pieces; two pieces are linked only when the person knows walkable triangles on both sides of a crossing edge; a chain never passes from one piece of a chunk to another inside it. +8. Same chunk, two pieces: a walk between two pieces of one chunk, joined only through a neighbouring chunk, is coarse and goes round. +9. The checker rejects a walk recorded as `full`. +10. Survey: a person who has moved less than 100 m learns no new triangles; after moving 100 m they learn what came into sight. +11. The checker rejects a way through an unknown triangle, a corridor with a gap, one way too many, and a survey recorded against the rule. +12. Leisure: an idle person at home with nothing to explore walks out along the way from home used longest ago, once a calendar day; away from home they walk home to rest; with no time to return before dusk they rest. Life 14 fixtures, kept: @@ -432,14 +463,18 @@ Life 14 fixtures, kept: 11. The checker rejects a weight outside three spreads, a stored load capacity that disagrees with grip, a trip load above capacity, a body charge at the reference rate instead of the person's, an exchange off the agreeableness price, and the earlier corruptions. 12. The existing queue, lazy-body, places, mesh, routes, food, fire, hut, axe, trade, group and playback tests, with route fixtures updated where a reused way or a coarse plan now gives a different path. -Final validation is `npm run agent:check`. Measured once 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. +**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. + +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 - Should people join a way from nearby, not only from on it, and how near? - 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 squares of land? +- 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. +- 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)? - Does sight need to stop at ridges once surveys are rarer? diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 4634578..321de8f 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -130,6 +130,6 @@ The browser check looks at the settings screen rejecting 7 and 366 days, Start s Life 14 adds bounded-normal moments, integer factorisation and positive-definiteness checks, 10,000 draws per sex for body magnitudes and correlations, and 10,000 trait sets for all ten correlations. Small fixtures verify carrying, loaded speed, energy and thirst, each trait's direction, and checker rejection of damaged bodies, derived quantities, task charges and exchange prices. Rule fixtures explicitly supply a reference-weight/reference-grip body and neutral traits when old numeric assertions need them. `life13-founders.json` freezes starts and born skills on all three fingerprint seeds; those streams must remain unchanged. -`sites.test.ts` checks that an idle person at home with nothing to explore walks out along the way used longest ago, once a day, goes home to rest afterwards, and stays in when there is no time to return before dusk. `ways.test.ts` checks walking a way again and back the other way, joining one part-way and planning afresh from off it, the recheck after a day with new ground, forgetting the least recently used way and replacing one between the same ends, the same corridor at a slower pace under load, a coarse plan staying in its band, the fallback to a full plan behind a wall, chunks linked only across known ground, the 100 m survey rule, and the checker rejecting a way through unknown ground, a way with a gap, too many ways and a survey against the rule. +`sites.test.ts` checks that an idle person at home with nothing to explore walks out along the way used longest ago, once a day, goes home to rest afterwards, and stays in when there is no time to return before dusk. `ways.test.ts` checks walking a way again and back the other way, joining one part-way and planning afresh from off it, the recheck after a day with new ground, forgetting the least recently used way and replacing one between the same ends, the same corridor at a slower pace under load, a coarse plan staying in its band, a coarse plan going round a wall of unknown ground, a chunk split into two pieces where its known ground is not joined, a plan between two pieces of one chunk going through the next chunk, chunks linked only across known ground, the 100 m survey rule, and the checker rejecting a way through unknown ground, a way with a gap, too many ways, a survey against the rule and a walk that needed the full search. Browser acceptance covers the followed person's remembered ways drawn as lines, the task line naming the kind of walk, the "Ways" row, and the console. Earlier steps' acceptance covered a woman's and a man's person panels, five trait bars, figures scaled by height and weight, minute stepping and an exchange line with its price and gain share. Results and the single canonical year measurement are recorded in update 064's lab notes. diff --git a/src/valley/fingerprintRuns.ts b/src/valley/fingerprintRuns.ts index a606a82..7861dc8 100644 --- a/src/valley/fingerprintRuns.ts +++ b/src/valley/fingerprintRuns.ts @@ -39,110 +39,110 @@ const RECORDED = [ { config: 'canonical', seed: 20260813, - days: 'ba06bf58:66472', - totals: 'd224a9e8:464', + days: '6dd66e65:66501', + totals: 'f7cf7980:464', }, { config: 'canonical', seed: 1, - days: 'a4716341:66323', - totals: '4a7749ce:464', + days: '2ac589f6:66317', + totals: '13558877:464', }, { config: 'canonical', seed: 2, - days: '596e9d14:66288', - totals: '48191fa1:462', + days: 'a47a374b:66221', + totals: '55a6f741:463', }, { config: 'together', seed: 20260813, - days: 'ea71fe3e:66306', - totals: '325c9d26:463', + days: '6b1d2742:66291', + totals: '5b2a7159:463', }, { config: 'together', seed: 1, - days: '68cbaf19:66147', - totals: '767e9c5f:464', + days: 'cd30b991:66129', + totals: 'f36c46d1:464', }, { config: 'together', seed: 2, - days: '3e669b9d:66159', - totals: '475f385e:464', + days: '1e2a7ee5:66146', + totals: '6ddf9c6a:464', }, { config: 'noPractice', seed: 20260813, - days: '54e0fe72:66508', - totals: '3127dfd:464', + days: '7a366264:66580', + totals: 'da4c7848:464', }, { config: 'noPractice', seed: 1, - days: 'eab2ebaa:66294', - totals: 'e71379e5:464', + days: '995b0000:66296', + totals: 'd4f2e53a:464', }, { config: 'noPractice', seed: 2, - days: '103a4189:66239', - totals: 'd7b155ca:462', + days: '52cd85f9:66238', + totals: '534d359f:462', }, { config: 'talent', seed: 20260813, - days: '7fd46fbd:66549', - totals: '5318db71:464', + days: 'b874662e:66551', + totals: 'fd049345:464', }, { config: 'talent', seed: 1, - days: '42e51fc7:66390', - totals: '404b2f07:464', + days: 'b93234b4:66380', + totals: '400eb230:464', }, { config: 'talent', seed: 2, - days: '2fe9f587:66272', - totals: '181e967d:463', + days: '16f626b:66282', + totals: 'acfb38c5:463', }, { config: 'twelve', seed: 20260813, - days: 'cd844009:78552', - totals: '151c9ee4:468', + days: '90490841:78530', + totals: '2b986826:468', }, { config: 'twelve', seed: 1, - days: '16dd5839:78457', - totals: '3e37d3bd:472', + days: '294277b3:78475', + totals: '68bfeec3:472', }, { config: 'twelve', seed: 2, - days: '265be79b:78210', - totals: '26d287f6:470', + days: 'be666fe7:78187', + totals: 'a3ea33b:470', }, { config: 'alike', seed: 20260813, - days: '84e3c4af:66526', - totals: 'b4917c8a:464', + days: '6eead3:66600', + totals: 'deec9194:463', }, { config: 'alike', seed: 1, - days: 'f9a95463:66369', - totals: 'a7164861:464', + days: '9f26e36b:66432', + totals: '797f9a88:464', }, { config: 'alike', seed: 2, - days: '8aef2320:66372', - totals: '4f44c0d2:463', + days: '83304d9b:66370', + totals: '87404deb:463', }, { config: 'flat', @@ -165,8 +165,8 @@ const RECORDED = [ { config: 'forty', seed: 20260813, - days: 'dc285484:162403', - totals: '3f77d959:477', + days: '9645b9b3:162512', + totals: '628f4e06:477', }, ] as const diff --git a/src/valley/invariants.ts b/src/valley/invariants.ts index 25db23c..a4d1c71 100644 --- a/src/valley/invariants.ts +++ b/src/valley/invariants.ts @@ -172,6 +172,7 @@ export class ValleyChecker { errors.push(`person ${p.id}: two leisure walks in a day`) leisure = e.minute } + if (e.kind === 'walk' && e.plan === 'full') errors.push(`person ${p.id}: a walk needed the full search`) if (e.kind === 'walk' && (e.plan === 'way' || e.plan === 'joined')) { const way = known.get(e.wayId) if (way) { diff --git a/src/valley/perception.ts b/src/valley/perception.ts index 6a6cd66..e403a4e 100644 --- a/src/valley/perception.ts +++ b/src/valley/perception.ts @@ -1,6 +1,7 @@ import { placesWithin, placeAt } from './places' import { carryComponents, + carryPieces, chunkOf, knows, learnTriangle, @@ -171,8 +172,10 @@ export function observeAt(state: ValleyState, person: Forager, minute: number): if (complete) (ownKnowledge(person).fullyKnown ??= new Uint8Array(nav.chunkCells ** 2))[chunk] = 1 } if (observation.triangles.length) person.knowledge.revision += 1 - if (person.knowledge !== before || observation.triangles.length) + if (person.knowledge !== before || observation.triangles.length) { carryComponents(nav, before, person.knowledge, observation.triangles) + carryPieces(nav, before, person.knowledge, observation.triangles) + } if (surveying) { let views = viewsSeen.get(person.knowledge) if (!views) viewsSeen.set(person.knowledge, (views = new Set())) diff --git a/src/valley/routes.ts b/src/valley/routes.ts index b889d0c..bde2d9f 100644 --- a/src/valley/routes.ts +++ b/src/valley/routes.ts @@ -578,55 +578,128 @@ export function cutPath( } return pieces } -/** Whether a person knows walkable ground crossing between chunk `c` and its `k`-th listed neighbour. */ -function linkKnown(links: ChunkLinks, knowledge: Knowledge, k: number) { - for (let j = links.pairStart[k]!; j < links.pairStart[k + 1]!; j++) - if (knows(knowledge, links.pairs[2 * j]!) && knows(knowledge, links.pairs[2 * j + 1]!)) return true - return false +/** + * A person's pieces of known ground within chunks: for each chunk worked out, the piece of each of its triangles, + * numbered by the lowest triangle id in it, or -1 where the triangle is unknown or not walkable. Chunks are worked out + * when needed, and carried forward as triangles are learnt by dropping only the chunks those lie in. + */ +interface Pieces { + revision: number + chunks: Map +} +const pieceCache = new WeakMap() +const slotCache = new WeakMap() +/** Each triangle's position in its chunk's list. */ +function slotsOf(mesh: GroundMesh) { + let slots = slotCache.get(mesh) + if (!slots) { + slots = new Int32Array(mesh.triangles) + for (let c = 0; c < mesh.chunkCells ** 2; c++) + for (let k = mesh.chunkStart[c]!; k < mesh.chunkStart[c + 1]!; k++) + slots[mesh.chunkTriangles[k]!] = k - mesh.chunkStart[c]! + slotCache.set(mesh, slots) + } + return slots +} +function piecesOf(knowledge: Knowledge) { + let saved = pieceCache.get(knowledge) + if (saved?.revision !== knowledge.revision) { + saved = { revision: knowledge.revision, chunks: new Map() } + pieceCache.set(knowledge, saved) + } + return saved +} +/** The pieces of one chunk: known walkable triangles of the chunk sharing an edge are one piece. */ +function chunkPieces(mesh: GroundMesh, knowledge: Knowledge, pieces: Pieces, c: number) { + const saved = pieces.chunks.get(c) + if (saved) return saved + const start = mesh.chunkStart[c]!, + labels = new Int32Array(mesh.chunkStart[c + 1]! - start).fill(-1), + slots = slotsOf(mesh), + todo: number[] = [] + const open = (t: number) => mesh.area[t] === GROUND_AREA && knows(knowledge, t) === 1 + // Triangles are listed in id order, so each piece's first triangle is its lowest. + for (let i = 0; i < labels.length; i++) { + const root = mesh.chunkTriangles[start + i]! + if (labels[i]! >= 0 || !open(root)) continue + labels[i] = root + todo.length = 0 + todo.push(root) + while (todo.length) { + const t = todo.pop()! + for (let e = 0; e < 3; e++) { + const next = mesh.tn[3 * t + e]! + if (next < 0 || mesh.chunk[next] !== c || labels[slots[next]!]! >= 0 || !open(next)) continue + labels[slots[next]!] = root + todo.push(next) + } + } + } + pieces.chunks.set(c, labels) + return labels +} +/** The piece of known walkable ground in its chunk that a triangle belongs to, or -1. */ +export function pieceOf(nav: NavMap, knowledge: Knowledge, t: number) { + const mesh = nav.mesh + return chunkPieces(mesh, knowledge, piecesOf(knowledge), mesh.chunk[t]!)[slotsOf(mesh)[t]!]! +} +/** Carries a person's pieces forward to `after`, which knows `added` besides: only the chunks of `added` are dropped. */ +export function carryPieces(nav: NavMap, before: Knowledge, after: Knowledge, added: readonly number[]) { + const saved = pieceCache.get(before) + if (!saved || saved.revision + (added.length ? 1 : 0) !== after.revision) return + const chunks = before === after ? saved.chunks : new Map(saved.chunks) + for (const t of added) chunks.delete(nav.mesh.chunk[t]!) + pieceCache.set(after, { revision: after.revision, chunks }) } /** - * The coarse plan: A* over chunks linked for the person, costed between chunk centres, ties by chunk number. Returns - * the band of the chain's chunks and every chunk touching one of them, side or corner, or null if no chain is known. + * The coarse plan: A* over the person's linked pieces, costed between their chunks' centres, ties by piece number. + * Returns the band of the chain's chunks and every chunk touching one of them, side or corner, or null if no chain is + * known. A chain of pieces is joined-up known ground, so the band always holds a path. */ export function coarseBand(nav: NavMap, knowledge: Knowledge, first: number, last: number): Uint8Array | null { const { mesh, links } = nav, cells = mesh.chunkCells, - from = mesh.chunk[first]!, - to = mesh.chunk[last]! - const centre = (c: number) => [(c % cells) + 0.5, Math.floor(c / cells) + 0.5] as const - const gap = (a: number, b: number) => { - const [ax, ay] = centre(a), - [bx, by] = centre(b) - return Math.sqrt((ax - bx) ** 2 + (ay - by) ** 2) - } - const chain: number[] = [from] + pieces = piecesOf(knowledge), + slots = slotsOf(mesh) + const piece = (t: number) => chunkPieces(mesh, knowledge, pieces, mesh.chunk[t]!)[slots[t]!]! + const from = piece(first), + to = piece(last) + if (from < 0 || to < 0) return null + const gap = (a: number, b: number) => + Math.sqrt(((a % cells) - (b % cells)) ** 2 + (Math.floor(a / cells) - Math.floor(b / cells)) ** 2) + const chain: number[] = [mesh.chunk[from]!] if (from !== to) { - const costs = new Float64Array(cells * cells).fill(Infinity), - parents = new Int32Array(cells * cells).fill(-1), - closed = new Uint8Array(cells * cells), + const goal = mesh.chunk[to]!, + costs = new Map([[from, 0]]), + parents = new Map([[from, -1]]), + closed = new Set(), heap = new CellHeap() - costs[from] = 0 - heap.push(from, gap(from, to)) + heap.push(from, gap(mesh.chunk[from]!, goal)) while (heap.length) { - const c = heap.popId() - if (closed[c]) continue - closed[c] = 1 - if (c === to) break + const p = heap.popId() + if (closed.has(p)) continue + closed.add(p) + if (p === to) break + const c = mesh.chunk[p]! for (let k = links.start[c]!; k < links.start[c + 1]!; k++) { - const next = links.chunk[k]! - if (closed[next]) continue - const cost = costs[c]! + gap(c, next) - if (cost < costs[next]! || (cost === costs[next] && c < parents[next]!)) { - if (!linkKnown(links, knowledge, k)) continue - costs[next] = cost - parents[next] = c - heap.push(next, cost + gap(next, to)) + const n = links.chunk[k]!, + cost = costs.get(p)! + gap(c, n) + for (let j = links.pairStart[k]!; j < links.pairStart[k + 1]!; j++) { + if (piece(links.pairs[2 * j]!) !== p) continue + const q = piece(links.pairs[2 * j + 1]!) + if (q < 0 || closed.has(q)) continue + const old = costs.get(q) + if (old === undefined || cost < old || (cost === old && p < parents.get(q)!)) { + costs.set(q, cost) + parents.set(q, p) + heap.push(q, cost + gap(n, goal)) + } } } } - if (!closed[to]) return null + if (!closed.has(to)) return null chain.length = 0 - for (let c = to; c >= 0; c = parents[c]!) chain.push(c) + for (let p = to; p >= 0; p = parents.get(p)!) chain.push(mesh.chunk[p]!) } const band = new Uint8Array(cells * cells) for (const c of chain) { @@ -640,8 +713,9 @@ export function coarseBand(nav: NavMap, knowledge: Knowledge, first: number, las } export type PlanKind = 'coarse' | 'full' /** - * A new corridor over known ground: within the band of a coarse chunk plan first, over all known ground if the band - * holds none. Null when the two points are on separate pieces of known ground. + * A new corridor over known ground, within the band of a coarse plan over pieces. The band always holds a path; the + * search over all known ground is only a guard, recorded as `full`, that the checker rejects. Null when the two points + * are on separate pieces of known ground. */ export function planCorridor( nav: NavMap, diff --git a/src/valley/ways.test.ts b/src/valley/ways.test.ts index f7d47ca..4bdddf1 100644 --- a/src/valley/ways.test.ts +++ b/src/valley/ways.test.ts @@ -1,7 +1,15 @@ import { describe, expect, it } from 'vitest' import { createSurveyedValley } from './ruleFixtures' import { FLAT_LAND } from './config' -import { coarseBand, corridorRoute, planCorridor, routeTriangle, trianglePoint, type Knowledge } from './routes' +import { + coarseBand, + corridorRoute, + pieceOf, + planCorridor, + routeTriangle, + trianglePoint, + type Knowledge, +} from './routes' import { findWalk, rememberWalk } from './ways' import { observeAt } from './perception' import { stepValley } from './engine' @@ -60,7 +68,7 @@ describe('remembered ways', () => { expect(joined.corridor).toEqual(corridor.slice(corridor.indexOf(middle))) const off = [0, 1, 2].map((e) => mesh.tn[3 * middle + e]!).find((t) => t >= 0 && !corridor.includes(t))! place(person, trianglePoint(mesh, off)) - expect(['coarse', 'full']).toContain(walk(thicket).plan) + expect(walk(thicket).plan).toBe('coarse') }) it('keeps a way until a day has passed and new ground was seen', () => { const { state, person, go, walk } = fixture() @@ -108,7 +116,7 @@ describe('remembered ways', () => { }) describe('coarse planning', () => { - it('keeps a coarse plan inside the band of its chunk chain', () => { + it('keeps a coarse plan inside the band of its chain', () => { const { state, person } = fixture() const nav = state.layout.nav, k = person.knowledge @@ -119,7 +127,7 @@ describe('coarse planning', () => { expect(plan.plan).toBe('coarse') for (const t of plan.corridor) expect(band[nav.mesh.chunk[t]!]).toBe(1) }) - it('falls back to a full plan when the band holds no path', () => { + it('goes round a wall of unknown ground in a coarse plan, inside its band', () => { const { state, person } = fixture() // A wall inside the first column of chunks, open only far outside the band of the straight chain. forget(state, person.knowledge, (x, y) => x > 9_000 && x < 11_000 && y < 70_000) @@ -127,8 +135,39 @@ describe('coarse planning', () => { k = person.knowledge const from = { x: 1_000, y: 10_000 }, to = { x: 30_000, y: 10_000 } - const plan = planCorridor(nav, k, routeTriangle(nav, k, from), routeTriangle(nav, k, to), from, to)! - expect(plan.plan).toBe('full') + const first = routeTriangle(nav, k, from), + last = routeTriangle(nav, k, to) + const band = coarseBand(nav, k, first, last)! + const plan = planCorridor(nav, k, first, last, from, to)! + expect(plan.plan).toBe('coarse') + for (const t of plan.corridor) expect(band[nav.mesh.chunk[t]!]).toBe(1) + expect(plan.corridor.some((t) => nav.mesh.cy[t]! > 70_000)).toBe(true) + }) + it('splits a chunk into pieces where its known ground is not joined', () => { + const { state, person } = fixture() + forget(state, person.knowledge, (x, y) => x > 9_000 && x < 11_000 && y < 70_000) + const nav = state.layout.nav, + k = person.knowledge + const left = routeTriangle(nav, k, { x: 1_000, y: 10_000 }), + right = routeTriangle(nav, k, { x: 15_000, y: 10_000 }), + below = routeTriangle(nav, k, { x: 1_000, y: 2_000 }) + expect(nav.mesh.chunk[left]).toBe(nav.mesh.chunk[right]) + expect(pieceOf(nav, k, left)).not.toBe(pieceOf(nav, k, right)) + expect(pieceOf(nav, k, left)).toBe(pieceOf(nav, k, below)) + }) + it('plans between two pieces of one chunk through the next chunk', () => { + const { state, person } = fixture() + forget(state, person.knowledge, (x, y) => x > 9_000 && x < 11_000 && y < 21_000) + const nav = state.layout.nav, + k = person.knowledge + const from = { x: 1_000, y: 5_000 }, + to = { x: 15_000, y: 5_000 } + const first = routeTriangle(nav, k, from), + last = routeTriangle(nav, k, to) + expect(nav.mesh.chunk[first]).toBe(nav.mesh.chunk[last]) + const plan = planCorridor(nav, k, first, last, from, to)! + expect(plan.plan).toBe('coarse') + expect(plan.corridor.some((t) => nav.mesh.chunk[t] !== nav.mesh.chunk[first])).toBe(true) }) it('links chunks only across ground known on both sides', () => { const { state, person } = fixture() @@ -193,4 +232,11 @@ describe('the checker on ways', () => { }) expect(survey.some((e) => e.includes('survey taken against the rule'))).toBe(true) }) + it('rejects a walk that needed the full search', () => { + const errors = run((s) => { + const e = s.lastInterval.find((r) => r.kind === 'walk')! + if (e.kind === 'walk') e.plan = 'full' + }) + expect(errors.some((e) => e.includes('needed the full search'))).toBe(true) + }) }) From 6757690c26c6cb12a32490c81d9430a7c9e29581 Mon Sep 17 00:00:00 2001 From: NeoLorenzo Date: Tue, 27 Oct 2026 23:10:29 +0000 Subject: [PATCH 2/2] test(life14): give the founder stream test its own time limit --- src/valley/nature.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/valley/nature.test.ts b/src/valley/nature.test.ts index e84d965..4b0b4b2 100644 --- a/src/valley/nature.test.ts +++ b/src/valley/nature.test.ts @@ -337,5 +337,5 @@ describe('Life 14 bodies and personality', () => { } expect(TRAITS).toHaveLength(5) expect(FLAT_LAND.founders).toBe(8) - }) + }, 180_000) })