Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions packages/solver/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,9 @@ CoolingPerSec` — it is what a cooler is worth and what the game shows for it,
landmasses with no producer count as nearest of all. A move onto an empty
tile is exact. A swap with a producer is re-simulated and kept only if power,
every producer and the upgrade plan all hold, so the pass cannot cost a watt.
It is capped at 150ms for the primary and 150ms shared across the
alternates; on the shipped maps one layout takes 15-110ms. Map 1 goes from
five cooler clusters to one.
**It is not timed against the run**, and neither is anything else past the
deadline — see "The cleanup past the deadline is untimed" below. Map 1 goes
from five cooler clusters to one.

**Before the sweep, hubs leave the smaller landmasses**
(`evacuateMinorLandmasses`). One tile at a time cannot move a hub: a
Expand All @@ -221,8 +221,7 @@ CoolingPerSec` — it is what a cooler is worth and what the game shows for it,
tiles, and each displaced cooler crosses to the tile its producer left, so
composition and pool are unchanged. A swap descent over the main landmass
then restores power. The move is kept only on the same three tests as a swap,
and the emptied landmass then fills with coolers like any scrap. It has its
own 1s cap on top of the sweep's (`EVACUATE_BUDGET_MS`), sized for a phone; a
and the emptied landmass then fills with coolers like any scrap. A
15-producer hub takes about 170ms on a desktop. On the eight maps with
obstacles cleared it brings seven to a single producing landmass at the same
power. Shadowspire keeps two, because its 29-producer second landmass does
Expand Down Expand Up @@ -672,7 +671,38 @@ pass: it moves the holes a layout leaves inside the land out to the shore and
into corners, a nearer-the-edge building stepping into each, re-simulated and
kept only if power holds, no producer goes offline, nothing new goes idle and
the plan holds. Under a pool it leaves coolers where `gatherPooledCoolers` put
them. Its budget (`EMPTY_GATHER_BUDGET_MS`) is added to a run.
them.

**The cleanup past the deadline is untimed.** Pruning, right-sizing, the
pooled coolers' evacuation and sweep, and `gatherEmptyTiles` all run to
completion on the primary and on every alternate. Each pass terminates on its
own — every accepted move strictly lowers a summed distance or depth, except in
the evacuation's swap descent, where every accepted swap strictly raises power
over a finite set of layouts. That descent is the one pass with no cheap bound
(a pass is O(pairs) simulations and it runs to a local optimum when the floor is
never reached), so it is what to measure first if a phone's cleanup outlasts
`FINALIZING_GRACE_MS`. Their
`deadlineMs` parameters default to `Infinity`, kept only for a caller that
wants a bound. They used to be capped, and the cap is what went wrong: shared
across a shortlist, the first alternate's evacuation spent it, so every later
variant the player stepped through came back with its coolers wherever the walk
had left them. Uncapped, it adds 0.1s on most maps and 3-4s on a desktop on the
largest under a pool (0.1-0.9s per layout, eleven layouts).

So the wait is reported rather than hidden: `SearchHooks.onFinalizing(done,
total)` fires as the cleanup starts and after each layout (the last at
`total/total`), the worker posts it as `ISLAND_FINALIZING`, the coordinator sums
it over the tasks that have reached their cleanup — a finished one counted whole
until none is left, so the count never goes backwards — and the readout's clock
reads "finalizing 3/11" once its countdown is out. Each report also re-arms the
app's watchdog (`FINALIZING_GRACE_MS`), which would otherwise stop a slow phone
mid-shortlist and lose the layouts not yet tidied.

STOP lands between layouts and never cuts the primary's cleanup short. Only a
STOP that arrives **during** the cleanup cuts the shortlist; one already in hand
when the search ended asked for what it had found, alternates included, so the
shortlist is finished — cutting there returned every stopped run with no
variants at all.

**`distribution.ts` is a port of Unity's `FlowNetwork.cs`.** Two shapes in it are
load-bearing and look like details:
Expand Down
19 changes: 19 additions & 0 deletions packages/solver/src/solver/pacer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,23 @@ export class Pacer {

if (!this.stopped && this.hooks?.shouldStop?.()) this.stopped = true;
}

/**
* Reports that the cleanup past the deadline has finished `done` of `total`
* layouts, and yields. Unconditionally rather than when `due()`: a layout's
* cleanup can take most of a second, and both the report and a STOP should
* land between layouts rather than whenever the interval happens to say so.
*/
async finalizing(done: number, total: number): Promise<void> {
this.hooksFinalizing(done, total);
await this.pump(performance.now());
}

/**
* The same report without the yield — for the last one, after which the
* solve returns at once and there is nothing left for a STOP to cut.
*/
hooksFinalizing(done: number, total: number): void {
this.hooks?.onFinalizing?.(done, total);
}
}
79 changes: 38 additions & 41 deletions packages/solver/src/solver/placementSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,15 @@ import {
targetCanBeat,
targetCompositions,
} from "./search/composition";
import { EMPTY_GATHER_BUDGET_MS, gatherEmptyTiles } from "./search/emptyTiles";
import { gatherEmptyTiles } from "./search/emptyTiles";
import {
emptyPlacement,
isDirectProducer,
isReactor,
put,
toPlacedBuildings,
} from "./search/placement";
import {
EVACUATE_BUDGET_MS,
GATHER_BUDGET_MS,
gatherPooledCoolers,
} from "./search/pooledCoolers";
import { gatherPooledCoolers } from "./search/pooledCoolers";
import {
greedyPolish,
polishCandidates,
Expand Down Expand Up @@ -185,37 +181,38 @@ export interface IslandSolution extends IslandLayout {
* the last place the layouts change shape.
*/
async function finalizeAlternates(
collector: AlternateCollector,
layouts: Placement[],
primaryRows: PlacedBuilding[],
primaryPower: number,
effectiveBuildings: EffectiveBuilding[],
ctx: IslandContext,
pacer: Pacer,
stoppedBeforeCleanup: boolean,
): Promise<IslandLayout[]> {
const kept: PlacedBuilding[][] = [primaryRows];
const out: IslandLayout[] = [];
// One gathering budget for the whole shortlist rather than one each, so a
// long shortlist cannot add a second to the run. An alternate the deadline
// cuts short is still valid, only less gathered.
const gatherDeadlineMs =
performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS;
// And one for the holes, counted in time actually spent: the coolers' pass
// is a no-op under every rule but a pool, and its unused budget is not this
// one's to take.
let emptyLeftMs = EMPTY_GATHER_BUDGET_MS;

for (const layout of collector.layouts()) {
// This runs after the search's deadline, and each alternate is a few
// hundred simulations — up to a second under a cooling pool — so come up
// for air between them: a STOP that arrives here ends the shortlist where
// it stands rather than waiting for ten more layouts to be finished.
const now = performance.now();
if (pacer.due(now)) {
await pacer.pump(now);
if (pacer.stopRequested) break;
const total = 1 + layouts.length;
let cut = false;

// Every alternate is finished as fully as the primary, with no time cap:
// the variants are what the player steps through, and a shared budget left
// all but the first with their coolers where the walk dropped them. The
// primary was layout 1 of `1 + layouts.length`; each pass here is the next.
for (let i = 0; i < layouts.length; i++) {
// Each alternate is a few hundred simulations — most of a second under a
// cooling pool — so come up for air between them: the progress report
// goes out, and a STOP pressed during the cleanup ends the shortlist where
// it stands rather than waiting for ten more layouts to be finished. A
// STOP that arrived during the search does not: it asked for the layouts
// found so far, and the shortlist is part of them — cutting here returned
// a stopped run with no variants at all.
await pacer.finalizing(1 + i, total);
if (pacer.stopRequested && !stoppedBeforeCleanup) {
cut = true;
break;
}

const pruned = pruneDeadWeight(layout, ctx);
const pruned = pruneDeadWeight(layouts[i], ctx);
const downsized = downgradeOversized(
pruned.rows,
pruned.power,
Expand All @@ -227,17 +224,13 @@ async function finalizeAlternates(
downsized.power,
effectiveBuildings,
ctx,
gatherDeadlineMs,
);
const emptyStartedMs = performance.now();
const tidied = gatherEmptyTiles(
sized.rows,
sized.power,
effectiveBuildings,
ctx,
emptyStartedMs + emptyLeftMs,
);
emptyLeftMs -= performance.now() - emptyStartedMs;
if (!powerTies(tidied.power, primaryPower)) continue;

const rows = toPlacedBuildings(tidied.rows);
Expand All @@ -246,6 +239,8 @@ async function finalizeAlternates(
out.push({ placements: rows, powerOutput: tidied.power });
}

// The last layout is done too: say so, so a caller's count reaches its end.
if (!cut) pacer.hooksFinalizing(total, total);
return out;
}

Expand Down Expand Up @@ -722,13 +717,16 @@ export async function solveIsland(
if (annealMs < minRoundMs) break;
}

// Everything from here runs past the deadline and none of it yields on its
// own, so yield once before it: the walk's last pump may be most of a yield
// interval ago, and the cleanup below is a second of work under a pool.
{
const now = performance.now();
if (pacer.due(now)) await pacer.pump(now);
}
// Everything from here runs past the deadline, untimed — a finished layout
// is worth finishing — and none of it yields on its own, so say so and yield
// before it: the caller's countdown has run out, and this is what explains
// the wait. The STOP that may arrive here does not cut the primary short;
// pruning is what makes it an answer.
const shortlist = collector.layouts();
// A STOP already in hand asked for what the search found, alternates
// included; only one that lands during the cleanup cuts the shortlist.
const stoppedBeforeCleanup = pacer.stopRequested;
await pacer.finalizing(0, 1 + shortlist.length);

// Post-search cleanup pass...
const pruned = pruneDeadWeight(placement, ctx);
Expand All @@ -748,24 +746,23 @@ export async function solveIsland(
downsized.power,
effectiveBuildings,
ctx,
performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS,
);
// Then push the holes the layout leaves out to the shore and the corners.
const tidied = gatherEmptyTiles(
sized.rows,
sized.power,
effectiveBuildings,
ctx,
performance.now() + EMPTY_GATHER_BUDGET_MS,
);
const placements = toPlacedBuildings(tidied.rows);
const alternates = await finalizeAlternates(
collector,
shortlist,
placements,
tidied.power,
effectiveBuildings,
ctx,
pacer,
stoppedBeforeCleanup,
);
// Every one of these ties on power, so the cheapest to build goes first and
// is the one the island shows. Stable, so equal costs keep the walk's order.
Expand Down
16 changes: 4 additions & 12 deletions packages/solver/src/solver/search/emptyTiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,6 @@ import { anyOfflineProducer, layoutHolds } from "./stability";
* and into its corners.
*/

/**
* How long `gatherEmptyTiles` may spend, per solve on the primary layout and
* once more shared across its alternates. It runs after the search's deadline,
* so this is time added to a run; out of time, the holes stay where the sweep
* left them. On a desktop the largest shipped island under Singularity takes
* 105-145ms and the rest 0-60ms, so this leaves a phone room to finish.
*/
export const EMPTY_GATHER_BUDGET_MS = 300;

/** A tile's 8-neighbourhood is complete when every neighbour is buildable. */
const FULL_NEIGHBOURHOOD = 8;

Expand Down Expand Up @@ -93,15 +84,16 @@ function idleCount(placement: Placement, rows: SimPlacedBuilding[]): number {
*
* Under a cooling pool coolers are not moved, since `gatherPooledCoolers` has
* just put them where they are. Every accepted move strictly lowers the holes'
* summed `interiority`, so the sweep terminates; the deadline only bounds how
* far it gets.
* summed `interiority`, so the sweep terminates on its own. It runs after the
* search's deadline and is not timed against it — a finished layout is worth
* finishing, so `deadlineMs` is only for a caller that wants to bound it.
*/
export function gatherEmptyTiles(
rows: SimPlacedBuilding[],
power: number,
effectiveBuildings: EffectiveBuilding[],
ctx: IslandContext,
deadlineMs: number,
deadlineMs = Infinity,
): { rows: SimPlacedBuilding[]; power: number } {
if (rows.length === 0 || rows.length >= ctx.n) return { rows, power };

Expand Down
40 changes: 12 additions & 28 deletions packages/solver/src/solver/search/pooledCoolers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,6 @@ import { anyOfflineProducer, layoutHolds } from "./stability";
* after moving hubs off the smaller landmasses so those can hold them.
*/

/**
* How long `gatherPooledCoolers` may spend, per solve on the primary layout and
* once more shared across its alternates. It runs after the search's deadline,
* so this is time added to a run. Moving a cooler onto an empty tile costs
* nothing. The cap is for the cooler-to-producer swaps, which mostly fail and
* cost a simulation each. On the shipped maps one layout finishes in 15-110ms.
*/
export const GATHER_BUDGET_MS = 150;

/**
* How long `evacuateMinorLandmasses` may spend, on top of `GATHER_BUDGET_MS`
* and taken first. Spent only on a board with producers on more than one
* landmass, and the pass stops as soon as a hub is placed — moving a
* 15-producer hub costs about 170ms on a desktop. The cap is sized for a phone,
* several times slower, where a tight one would make the pass silently do
* nothing; a second is small beside a 10-30s attempt. Out of time, the layout
* stays as it was.
*/
export const EVACUATE_BUDGET_MS = 1000;

/** Chebyshev radius of the patch `gatherPooledCoolers` anchors on. */
const GATHER_ANCHOR_RADIUS = 2;

Expand Down Expand Up @@ -279,18 +259,24 @@ function relocateHub(
* landmass with no producer is a scrap nothing else can use, and counts as
* nearer than any tile on a working landmass, so empty scraps fill first. Every
* accepted move strictly lowers the coolers' summed distance, so the sweep
* terminates; the deadline only bounds how far it gets.
* terminates on its own.
*
* **Neither pass is timed against the run.** Both run after the search's
* deadline, and a cap there left the layouts unfinished: shared across a
* shortlist, the first alternate's evacuation spent it and every later variant
* came back with its coolers where the walk left them. Run to completion it is
* 0.1-0.9s per layout on the largest shipped maps (a 15-producer evacuation
* about 170ms of that), a few seconds over a shortlist of ten; the run reports
* that it is finalizing (`SearchHooks.onFinalizing`) so the wait is explained.
* The deadlines remain for a caller that wants to bound it.
*/
export function gatherPooledCoolers(
rows: SimPlacedBuilding[],
power: number,
effectiveBuildings: EffectiveBuilding[],
ctx: IslandContext,
deadlineMs: number,
evacuateDeadlineMs = Math.min(
deadlineMs,
performance.now() + EVACUATE_BUDGET_MS,
),
deadlineMs = Infinity,
evacuateDeadlineMs = deadlineMs,
): { rows: SimPlacedBuilding[]; power: number } {
if (ctx.anomaly.rule !== "shared_cooling" || rows.length === 0)
return { rows, power };
Expand All @@ -304,8 +290,6 @@ export function gatherPooledCoolers(
}

const { component, count } = landmasses(ctx);
// The callers' deadline covers both budgets; capping the evacuation at its
// own (the default) leaves the sweep at least `GATHER_BUDGET_MS`.
evacuateMinorLandmasses(
current,
ctx,
Expand Down
16 changes: 16 additions & 0 deletions packages/solver/src/solver/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,15 @@ export interface SearchHooks {
onProgress?: (placements: PlacedBuilding[], powerOutput: number) => void;
shouldStop?: () => boolean;
reportIntervalMs?: number;
/**
* The search's deadline has passed and the finished layouts are being
* tidied: `done` of `total` (the primary and its alternates) so far. Called
* once with `done` 0 as the cleanup starts, then after each layout, the
* last at `total` unless a STOP during the cleanup cut it short. The
* cleanup is not timed against the run, so this is how a caller explains the
* wait past its countdown.
*/
onFinalizing?: (done: number, total: number) => void;
}

/**
Expand Down Expand Up @@ -541,6 +550,13 @@ export type IslandWorkerResponse =
placements: PlacedBuilding[];
powerOutput: number;
}
| {
/** Past the deadline, tidying the finished layouts — `SearchHooks.onFinalizing`. */
id: string;
type: "ISLAND_FINALIZING";
done: number;
total: number;
}
| {
id: string;
type: "ISLAND_DONE";
Expand Down
4 changes: 3 additions & 1 deletion src/lib/components/canvas/PixiCanvas.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,9 @@
/*
* Lines from the inspected building — hovered on a mouse, pinned on touch,
* which `inspectedTile` already decides — to every building it sends heat or
* cooling to or takes it from, and on through theirs with `chainLinks`. Only
* cooling to or takes it from (no cooling under a shared pool, where no
* cooler serves anyone in particular — see `placementFlows`), and on through
* theirs with `chainLinks`. Only
* a building standing on the tile has flows: hovering grass draws nothing.
*/
$effect(() => {
Expand Down
Loading
Loading