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
14 changes: 12 additions & 2 deletions packages/solver/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ is the entry point. `planSolve()` does the shared setup:
reserved before the layout exists and converges long before its cap, so what
it hands back becomes another short walk rather than idle time. Each stage
is a file under `search/` (`seed`, `anneal`, `composition`, `repair`,
`rightSize`, `pooledCoolers`, over the shared `placement` and `stability`
`rightSize`, `pooledCoolers`, `emptyTiles`, over the shared `placement` and `stability`
primitives); `placementSearch.ts` keeps `solveIsland`, the budget split,
the deterministic replay and `internals`, and stays the one module anything
outside imports the search from. The reasoning for each stage is in
Expand Down Expand Up @@ -662,7 +662,17 @@ at 2%, so nothing in the walk prefers the tier a tile actually needs, and the
roster's top cooler lands where a twentieth of it would do — real money the
player spends on capacity that never runs. Each swap is re-simulated and kept
only if power holds and every producer stays online, so it can change which
building sits on a tile and nothing else. Tied layouts go through it too.
building sits on a tile and nothing else — except a building doing nothing at
all, which it takes away rather than shrinking: every tier covers a load of
zero, so such a cooler used to become the cheapest one and stand there idle.
Tied layouts go through it too.

**`gatherEmptyTiles` runs last, under every rule**, and is the same kind of
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.

**`distribution.ts` is a port of Unity's `FlowNetwork.cs`.** Two shapes in it are
load-bearing and look like details:
Expand Down
66 changes: 66 additions & 0 deletions packages/solver/src/data/buildingPrices.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { findBuilding } from "./buildings";
import { TIME_LAB } from "./timeLab";

/**
Expand Down Expand Up @@ -85,3 +86,68 @@ export function sellRefund(
): number {
return copies > 0 ? buildPrice(base, copies, rules) * rules.refund : 0;
}

/** The price rules of a player with none of the price research. */
const BASE_RULES: PriceRules = {
scaler: COST_SCALER[0],
discount: 1,
refund: REFUND[0],
};

/**
* What building `layout` from an empty board costs, every copy at the price
* the next one would be.
*
* This is what ranks layouts that tie on power, so it only has to order them
* right, and the research that lowers prices mostly cannot change the order:
* both reductions scale every price alike. The scaler can, a little, and the
* copies standing on other islands too, so this is the board's own cost under
* the base scaler — a ranking, not a quote.
*/
export function layoutCost(
layout: readonly { buildingId: string }[],
rules: PriceRules = BASE_RULES,
): number {
const copies = new Map<string, number>();
for (const p of layout)
copies.set(p.buildingId, (copies.get(p.buildingId) ?? 0) + 1);
let cost = 0;
for (const [id, n] of copies) {
const base = findBuilding(id)?.price ?? 0;
for (let k = 0; k < n; k++) cost += buildPrice(base, k, rules);
}
return cost;
}

/**
* Relative slack for "the same cost": two layouts holding the same buildings
* sum them in a different order and can disagree in the last bits.
*/
const COST_TIE_RELATIVE_TOLERANCE = 1e-9;

/**
* Orders layouts that tie on power cheapest first: by `layoutCost`, then — the
* prices span thirty orders of magnitude, so a cooler more or less is lost in
* the cost of a reactor — by how many buildings stand, fewest first, so the
* layout leaving more of the land empty wins. Stable, so layouts neither
* figure separates keep the order they came in.
*
* Each layout is costed once, not once per comparison.
*/
export function cheapestFirst<T>(
items: readonly T[],
placementsOf: (item: T) => readonly { buildingId: string }[],
): T[] {
return items
.map((item) => {
const placements = placementsOf(item);
return { item, cost: layoutCost(placements), count: placements.length };
})
.sort((a, b) =>
Math.abs(a.cost - b.cost) >
COST_TIE_RELATIVE_TOLERANCE * Math.max(a.cost, b.cost)
? a.cost - b.cost
: a.count - b.count,
)
.map(({ item }) => item);
}
57 changes: 42 additions & 15 deletions packages/solver/src/solver/placementSearch.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { cheapestFirst } from "../data/buildingPrices";
import { AlternateCollector, isDistinctLayout, powerTies } from "./alternates";
import { EPS } from "./constants";
import { buildIslandContext, type IslandContext } from "./context";
Expand All @@ -20,6 +21,7 @@ import {
targetCanBeat,
targetCompositions,
} from "./search/composition";
import { EMPTY_GATHER_BUDGET_MS, gatherEmptyTiles } from "./search/emptyTiles";
import {
emptyPlacement,
isDirectProducer,
Expand Down Expand Up @@ -184,6 +186,10 @@ async function finalizeAlternates(
// 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
Expand All @@ -210,12 +216,21 @@ async function finalizeAlternates(
ctx,
gatherDeadlineMs,
);
if (!powerTies(sized.power, primaryPower)) continue;
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(sized.rows);
const rows = toPlacedBuildings(tidied.rows);
if (!isDistinctLayout(rows, kept)) continue;
kept.push(rows);
out.push({ placements: rows, powerOutput: sized.power });
out.push({ placements: rows, powerOutput: tidied.power });
}

return out;
Expand Down Expand Up @@ -686,19 +701,30 @@ export async function solveIsland(
ctx,
performance.now() + EVACUATE_BUDGET_MS + GATHER_BUDGET_MS,
);
const placements = toPlacedBuildings(sized.rows);
return {
// 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,
placements,
powerOutput: sized.power,
alternates: await finalizeAlternates(
collector,
placements,
sized.power,
effectiveBuildings,
ctx,
pacer,
),
};
tidied.power,
effectiveBuildings,
ctx,
pacer,
);
// 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.
const [best, ...rest] = cheapestFirst(
[{ placements, powerOutput: tidied.power }, ...alternates],
(l) => l.placements,
);
return { ...best, alternates: rest };
}

/**
Expand All @@ -721,6 +747,7 @@ export const internals = {
DOWNGRADE_ROLES,
constructMultiStartSeed,
downgradeTiers,
gatherEmptyTiles,
gatherPooledCoolers,
greedyPolish,
hillClimb,
Expand Down
178 changes: 178 additions & 0 deletions packages/solver/src/solver/search/emptyTiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import type { IslandContext } from "../context";
import { type SimPlacedBuilding, simulateIsland } from "../simulate";
import type { EffectiveBuilding, Placement } from "../types";
import { chebyshev, emptyPlacement, put } from "./placement";
import { covers } from "./rightSize";
import { anyOfflineProducer, planHolds } from "./stability";

/**
* Pushing the tiles a finished layout leaves empty out to the edge of the land
* 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;

/**
* How far inside the land each tile sits, as one sortable figure: lower is
* nearer an edge, and on the edge itself, nearer a corner.
*
* Depth is the 8-neighbour step count from the nearest tile with a
* non-buildable neighbour — water, an obstacle or the board's edge — and the
* buildable-neighbour count breaks ties within a ring, which is what puts a
* corner (three) ahead of a straight edge (five).
*/
function interiority(ctx: IslandContext): Int32Array {
const depth = new Int32Array(ctx.n).fill(-1);
const queue: number[] = [];
for (let t = 0; t < ctx.n; t++) {
if (ctx.neighbors[t].length < FULL_NEIGHBOURHOOD) {
depth[t] = 0;
queue.push(t);
}
}
for (let head = 0; head < queue.length; head++) {
const t = queue[head];
for (const u of ctx.neighbors[t]) {
if (depth[u] < 0) {
depth[u] = depth[t] + 1;
queue.push(u);
}
}
}
const score = new Int32Array(ctx.n);
for (let t = 0; t < ctx.n; t++)
score[t] = depth[t] * (FULL_NEIGHBOURHOOD + 1) + ctx.neighbors[t].length;
return score;
}

/** Buildings on the board doing nothing at all, as the readout would call them idle. */
function idleCount(placement: Placement, rows: SimPlacedBuilding[]): number {
let n = 0;
for (const r of rows) {
if (placement[r.idx] === null) continue;
if (
r.powerGenerated <= 0 &&
r.heatProduced <= 0 &&
r.heatConsumed <= 0 &&
r.coolingProvided <= 0
)
n++;
}
return n;
}

/**
* Moves the empty tiles a finished layout leaves inside the land out towards
* its shore and corners.
*
* The search places by power and nothing else, so wherever a building did not
* pay for its tile there is a hole, and the holes land wherever the walk
* stopped — often in the middle of the hubs, where the player has to build
* around them and wonders whether the solver forgot a tile. A hole on the
* shore or in a corner reads as what it is.
*
* Like `downgradeOversized`, this cannot find a better layout. A hole moves by
* a building nearer the edge stepping into it, which leaves the hole on the
* building's old tile. That changes what the building stands beside, so every
* move is re-simulated and kept only if power holds against the layout handed
* in, every producer stays online, nothing new goes idle and the upgrade plan
* still runs. Any building nearer the edge may be offered, nearest first: a
* radius of two left 7 of 24 interior holes standing across the eight shipped
* maps under Singularity (a player's 160s solves), and no radius left none,
* at no power.
*
* 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.
*/
export function gatherEmptyTiles(
rows: SimPlacedBuilding[],
power: number,
effectiveBuildings: EffectiveBuilding[],
ctx: IslandContext,
deadlineMs: number,
): { rows: SimPlacedBuilding[]; power: number } {
if (rows.length === 0 || rows.length >= ctx.n) return { rows, power };

const byId = new Map(effectiveBuildings.map((b) => [b.id, b]));
const current = emptyPlacement(ctx.n);
for (const row of rows) {
const building = byId.get(row.buildingId);
if (building === undefined) return { rows, power };
put(current, ctx, row.idx, building);
}

const score = interiority(ctx);
const pooled = ctx.anomaly.rule === "shared_cooling";
const floor = power;
const idleFloor = idleCount(current, rows);
let moved = false;

let changed = true;
while (changed && performance.now() < deadlineMs) {
changed = false;
// Deepest hole first: it has the furthest to go.
const holes: number[] = [];
for (let t = 0; t < ctx.n; t++)
if (current[t] === null && score[t] > 0) holes.push(t);
holes.sort((a, b) => score[b] - score[a] || a - b);

for (const hole of holes) {
if (performance.now() >= deadlineMs) break;
// Nearest the hole first, since a building that moves a step keeps most
// of its neighbours; then nearest the edge, then ascending index, so the
// result depends only on the board.
const sources: number[] = [];
for (let t = 0; t < ctx.n; t++) {
const b = current[t];
if (b === null || score[t] >= score[hole]) continue;
if (pooled && b.type === "cooler") continue;
sources.push(t);
}
sources.sort(
(a, b) =>
chebyshev(ctx, a, hole) - chebyshev(ctx, b, hole) ||
score[a] - score[b] ||
a - b,
);

for (const from of sources) {
const building = current[from]!;
put(current, ctx, hole, building);
current[from] = null;
const trial = simulateIsland(current, ctx);
if (
covers(trial.totalPower, floor) &&
!anyOfflineProducer(current, trial.placements) &&
idleCount(current, trial.placements) <= idleFloor &&
planHolds(current, ctx)
) {
changed = true;
moved = true;
break;
}
current[hole] = null;
put(current, ctx, from, building);
if (performance.now() >= deadlineMs) break;
}
}
}

if (!moved) return { rows, power };
const final = simulateIsland(current, ctx);
// Every kept move held the floor, so a shortfall here would be a bug rather
// than a trade. Give the input back.
if (!covers(final.totalPower, floor)) return { rows, power };
return { rows: final.placements, power: final.totalPower };
}
Loading
Loading