Try to fix AI playerss getting bankrupt all the time

Fix z-fighting
This commit is contained in:
tyuXX 2026-11-15 16:09:08 +03:00
parent 2e3cea5a30
commit 5878827d6c
14 changed files with 511 additions and 105 deletions

127
analyze_zfight.mjs Normal file
View file

@ -0,0 +1,127 @@
// minimal DOM stubs for headless run
globalThis.document = {
createElement: () => ({
width: 0, height: 0,
getContext: () => ({
createRadialGradient: () => ({ addColorStop: () => {} }),
fillRect: () => {},
}),
}),
};
globalThis.window = globalThis;
globalThis.self = globalThis;
globalThis.ProgressEvent = class ProgressEvent { constructor(type, init){ this.type=type; Object.assign(this, init);} };
const RealRequest = globalThis.Request;
globalThis.Request = class extends RealRequest {
constructor(url, ...a) {
if (typeof url === "string" && url.startsWith("/")) url = "http://localhost" + url;
super(url, ...a);
}
};
import fs from "node:fs";
import path from "node:path";
globalThis.fetch = async (url) => {
let u = typeof url === "string" ? url : url.url;
let p = u.split("?")[0];
try { p = decodeURIComponent(new URL(p).pathname); } catch {}
if (p.startsWith("/models/")) p = "models/" + p.slice(8);
else if (p.startsWith("/vendor/")) p = "public/vendor/" + p.slice(8);
else if (p.startsWith("/data/")) p = "data/" + p.slice(6);
else return new Response("not found", { status: 404 });
try {
const buf = fs.readFileSync(path.resolve(p));
return new Response(buf, { status: 200 });
} catch { return new Response("nf", { status: 404 }); }
};
import * as THREE from "three";
import { buildRocket } from "./dist/shared/physics/buildRocket.js";
import { createStarterDesign } from "./dist/shared/physics/starters.js";
import { buildRocketMesh } from "./dist/client/three/rocketMesh/assembly.js";
const parts = JSON.parse(fs.readFileSync("data/parts.json", "utf8"));
const materials = JSON.parse(fs.readFileSync("data/materials.json", "utf8"));
const payloadId = process.env.PAYLOAD || "payload-cubesat-1u";
const design = createStarterDesign(null, "sandbox");
design.payloadPartId = payloadId;
design.stages.push({
engineId: "eng-merlin-vac", engineCount: 1, nozzleRatio: 1.4, gimbalDeg: 3,
tankId: "tank-med-kero", diameter: 3.7, length: 14, fillRatio: 0.9,
structureId: "struct-frame-std", materialId: "al-7075",
wallThicknessFactor: 1.0, hasFins: false, hasHeatshield: false,
});
design.stages[0].interstageId = "interstage-std";
const asm = buildRocket(design, parts, materials, {});
console.log("height", asm.height.toFixed(2), "stages", asm.stages.length, "payload", payloadId);
const handle = await buildRocketMesh(asm, { realModels: true, fairingCutaway: false });
handle.group.updateMatrixWorld(true);
const faces = [];
let meshId = 0;
const meshNames = new Map();
handle.group.traverse((obj) => {
if (!obj.isMesh) return;
const id = meshId++;
const chain = [];
let n = obj;
while (n && chain.length < 5) { chain.push(n.name || n.type); n = n.parent; }
meshNames.set(id, chain.reverse().join("<"));
const geo = obj.geometry;
const pos = geo.attributes.position;
if (!pos) return;
const index = geo.index;
const triCount = index ? index.count / 3 : pos.count / 3;
const p = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
for (let t = 0; t < triCount; t++) {
const i0 = index ? index.getX(t * 3) : t * 3;
const i1 = index ? index.getX(t * 3 + 1) : t * 3 + 1;
const i2 = index ? index.getX(t * 3 + 2) : t * 3 + 2;
p[0].fromBufferAttribute(pos, i0).applyMatrix4(obj.matrixWorld);
p[1].fromBufferAttribute(pos, i1).applyMatrix4(obj.matrixWorld);
p[2].fromBufferAttribute(pos, i2).applyMatrix4(obj.matrixWorld);
const e1 = p[1].clone().sub(p[0]);
const e2 = p[2].clone().sub(p[0]);
const nrm = e1.cross(e2);
const area = nrm.length();
if (area < 1e-8) continue;
nrm.normalize();
if (Math.abs(nrm.y) < 0.999) continue;
const y = (p[0].y + p[1].y + p[2].y) / 3;
const cx = (p[0].x + p[1].x + p[2].x) / 3;
const cz = (p[0].z + p[1].z + p[2].z) / 3;
const rr = Math.max(
Math.hypot(p[0].x - cx, p[0].z - cz),
Math.hypot(p[1].x - cx, p[1].z - cz),
Math.hypot(p[2].x - cx, p[2].z - cz),
);
faces.push({ y, cx, cz, r: rr, ny: Math.sign(nrm.y), id, area });
}
});
console.log("meshes:", meshId, "horizontal faces:", faces.length);
faces.sort((a, b) => a.y - b.y);
const EPS = 0.03;
const groups = [];
for (const f of faces) {
const g = groups[groups.length - 1];
if (g && Math.abs(f.y - g.y) < EPS) g.items.push(f);
else groups.push({ y: f.y, items: [f] });
}
const seen = new Set();
for (const g of groups) {
const items = g.items;
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
const a = items[i], b = items[j];
if (a.id === b.id) continue;
const d = Math.hypot(a.cx - b.cx, a.cz - b.cz);
if (d < a.r + b.r - 0.05) {
const key = `${g.y.toFixed(2)}|${Math.min(a.id,b.id)}|${Math.max(a.id,b.id)}`;
if (seen.has(key)) continue;
seen.add(key);
console.log(`ZF y=${g.y.toFixed(3)}\n A m${a.id} ${meshNames.get(a.id)} ny=${a.ny} r=${a.r.toFixed(2)} @(${a.cx.toFixed(1)},${a.cz.toFixed(1)})\n B m${b.id} ${meshNames.get(b.id)} ny=${b.ny} r=${b.r.toFixed(2)} @(${b.cx.toFixed(1)},${b.cz.toFixed(1)})`);
}
}
}
}

View file

@ -19,11 +19,15 @@ export interface LeaderboardRow {
difficultyLabel?: string; difficultyLabel?: string;
aiSkill?: number | null; aiSkill?: number | null;
bankrupt: boolean; bankrupt: boolean;
bankruptcyReason?: string | null;
sponsorId: string | null; sponsorId: string | null;
treasury: number; treasury: number;
reputation: number; reputation: number;
missionsCompleted: number; missionsCompleted: number;
missionsFailed: number; missionsFailed: number;
careerMissionsCompleted?: number;
careerMissionsFailed?: number;
contractsAbandoned?: number;
earnedTotal: number; earnedTotal: number;
score: number; score: number;
} }

View file

@ -127,7 +127,7 @@ export function renderMarketPanel(
h( h(
"span", "span",
{}, {},
`${row.missionsCompleted} OK / ${row.missionsFailed} FAIL`, `${row.missionsCompleted} OK / ${row.missionsFailed} FAIL${row.contractsAbandoned ? ` / ${row.contractsAbandoned} VOID` : ""}`,
), ),
), ),
live live

View file

@ -133,7 +133,10 @@ function handleLiveEvent(ev: {
void refreshWorld(); void refreshWorld();
if (isMine) void refreshMe(); if (isMine) void refreshMe();
} else if (ev.type === "agency.bankrupt") { } else if (ev.type === "agency.bankrupt") {
const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy.`; const reason = d.reason
? ` (${String(d.reason).replace(/_/g, " ")})`
: "";
const msg = `INSOLVENCY ALERT: ${d.agency} declared bankruptcy${reason}.`;
pushNotification( pushNotification(
msg, msg,
isMine ? "err" : "warn", isMine ? "err" : "warn",
@ -179,6 +182,17 @@ function handleLiveEvent(ev: {
"world", "world",
); );
void refreshWorld(); void refreshWorld();
} else if (ev.type === "contract.abandoned") {
const reason = String(d.reason ?? "unknown").replace(/_/g, " ");
const penalty = ((Number(d.penalty) || 0) / 1e6).toFixed(1);
const msg = `${d.agency} abandoned contract ${d.missionId ?? d.offerId ?? "contract"} (${reason}) — $${penalty}M penalty.`;
if (isMine) {
toast(msg, "warn", false);
void refreshMe();
} else {
pushNotification(msg, "warn", "world", false);
}
void refreshWorld();
} else if (ev.type === "agency.updated" && isMine) { } else if (ev.type === "agency.updated" && isMine) {
if (state.agency && d.rocketDesign) { if (state.agency && d.rocketDesign) {
state.agency.rocketDesign = d.rocketDesign; state.agency.rocketDesign = d.rocketDesign;

View file

@ -9,6 +9,7 @@ import {
buildEngineClusterStandard, buildEngineClusterStandard,
buildPayloadNode, buildPayloadNode,
buildStageConnector, buildStageConnector,
cappedColumnGroup,
fitPayloadInsideFairing, fitPayloadInsideFairing,
} from "./geometry.js"; } from "./geometry.js";
import { import {
@ -190,7 +191,7 @@ export async function buildRocketMesh(
const cR = Math.max(0.6, topDia * 0.48); const cR = Math.max(0.6, topDia * 0.48);
const compGroup = new THREE.Group(); const compGroup = new THREE.Group();
const housing = new THREE.Mesh( const housing = new THREE.Mesh(
new THREE.CylinderGeometry(cR * 1.03, cR * 1.03, 0.36, 28), new THREE.CylinderGeometry(cR * 1.03, cR * 1.03, 0.36, 28, 1, true),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x1e293b, color: 0x1e293b,
metalness: 0.75, metalness: 0.75,
@ -248,15 +249,18 @@ export async function buildRocketMesh(
} }
payloadGroup = builtPayload; payloadGroup = builtPayload;
} else if (!isPro || topProPayload) { } else if (!isPro || topProPayload) {
const generic = new THREE.Mesh( const generic = cappedColumnGroup(
new THREE.CylinderGeometry(1.0, 1.2, 3.0, 16), 1.0,
1.2,
3.0,
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x60a5fa, color: 0x60a5fa,
metalness: 0.6, metalness: 0.6,
roughness: 0.35, roughness: 0.35,
}), }),
{ radialSegs: 16 },
); );
generic.position.y = assembly.payloadY + 1.5; generic.position.y = assembly.payloadY;
const genericGroup = new THREE.Group(); const genericGroup = new THREE.Group();
genericGroup.add(generic); genericGroup.add(generic);
if (topProPayload) { if (topProPayload) {
@ -318,17 +322,20 @@ export async function buildRocketMesh(
let lasGroup: THREE.Group | null = null; let lasGroup: THREE.Group | null = null;
if (assembly.lasPart) { if (assembly.lasPart) {
lasGroup = new THREE.Group(); lasGroup = new THREE.Group();
const tower = new THREE.Mesh( const tower = cappedColumnGroup(
new THREE.CylinderGeometry(0.28, 0.75, assembly.lasPart.length, 16), 0.28,
0.75,
assembly.lasPart.length,
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0xe2e8f0, color: 0xe2e8f0,
metalness: 0.4, metalness: 0.4,
roughness: 0.5, roughness: 0.5,
}), }),
{ radialSegs: 16 },
); );
tower.position.y = assembly.lasY + assembly.lasPart.length / 2; tower.position.y = assembly.lasY;
const tip = new THREE.Mesh( const tip = new THREE.Mesh(
new THREE.ConeGeometry(0.28, 1.4, 16), new THREE.ConeGeometry(0.28, 1.4, 16, 1, true),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0xf87171, color: 0xf87171,
metalness: 0.3, metalness: 0.3,

View file

@ -165,6 +165,40 @@ export function buildOgiveFairingGeo(
const CONNECTOR_RADIUS_FRAC = 0.94; const CONNECTOR_RADIUS_FRAC = 0.94;
// Stacked parts butt end-to-end, so any two capped faces on the same plane
// z-fight. Body columns are therefore built as an open wall plus cap discs
// recessed CAP_INSET from each end; trim rings keep exact bounds and stay
// clear of the recessed caps.
const CAP_INSET = 0.035;
export function cappedColumnGroup(
rt: number,
rb: number,
h: number,
mat: THREE.Material,
opts: { radialSegs?: number; heightSegs?: number; caps?: boolean } = {},
): THREE.Group {
const g = new THREE.Group();
const segs = opts.radialSegs ?? 32;
const wall = new THREE.Mesh(
new THREE.CylinderGeometry(rt, rb, h, segs, opts.heightSegs ?? 1, true),
mat,
);
wall.position.y = h / 2;
g.add(wall);
if (opts.caps !== false) {
const inset = Math.min(CAP_INSET, h * 0.2);
const top = new THREE.Mesh(new THREE.CircleGeometry(rt, segs), mat);
top.rotation.x = -Math.PI / 2;
top.position.y = h - inset;
const bot = new THREE.Mesh(new THREE.CircleGeometry(rb, segs), mat);
bot.rotation.x = Math.PI / 2;
bot.position.y = inset;
g.add(top, bot);
}
return g;
}
export function buildStageConnector( export function buildStageConnector(
botR: number, botR: number,
topR: number, topR: number,
@ -174,13 +208,13 @@ export function buildStageConnector(
const g = new THREE.Group(); const g = new THREE.Group();
const bR = Math.max(0.15, botR * CONNECTOR_RADIUS_FRAC); const bR = Math.max(0.15, botR * CONNECTOR_RADIUS_FRAC);
const tR = Math.max(0.15, topR * CONNECTOR_RADIUS_FRAC); const tR = Math.max(0.15, topR * CONNECTOR_RADIUS_FRAC);
const body = new THREE.Mesh( const body = cappedColumnGroup(tR, bR, len, mat, { radialSegs: 48 });
new THREE.CylinderGeometry(tR, bR, len, 48, 1, false), body.traverse((o) => {
mat, if ((o as THREE.Mesh).isMesh) {
); o.castShadow = true;
body.position.y = len / 2; o.receiveShadow = true;
body.castShadow = true; }
body.receiveShadow = true; });
g.add(body); g.add(body);
const flangeH = Math.min(0.22, len * 0.12); const flangeH = Math.min(0.22, len * 0.12);
const lerpR = (y: number) => bR + (tR - bR) * (y / len); const lerpR = (y: number) => bR + (tR - bR) * (y / len);
@ -227,16 +261,15 @@ export function buildEngineClusterStandard(
ringR *= k; ringR *= k;
singleR *= k; singleR *= k;
} }
const dome = new THREE.Mesh( const domeH = comp.length * 0.28;
new THREE.CylinderGeometry( const dome = cappedColumnGroup(
stageR * 0.88, stageR * 0.88,
stageR * 0.78, stageR * 0.78,
comp.length * 0.28, domeH,
28,
),
AVIONICS_RING_MAT, AVIONICS_RING_MAT,
{ radialSegs: 28 },
); );
dome.position.y = comp.yBottom + comp.length * 0.86; dome.position.y = comp.yBottom + comp.length * 0.86 - domeH / 2;
cluster.add(dome); cluster.add(dome);
const offsets: Array<[number, number]> = []; const offsets: Array<[number, number]> = [];
if (count === 1) { if (count === 1) {
@ -366,20 +399,18 @@ export async function buildPayloadNode(
} }
} }
const g = new THREE.Group(); const g = new THREE.Group();
const body = new THREE.Mesh( const body = cappedColumnGroup(
new THREE.CylinderGeometry( part.diameter * 0.42,
part.diameter * 0.42, part.diameter * 0.45,
part.diameter * 0.45, part.length * 0.85,
part.length * 0.85,
20,
),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x94a3b8, color: 0x94a3b8,
metalness: 0.7, metalness: 0.7,
roughness: 0.3, roughness: 0.3,
}), }),
{ radialSegs: 20 },
); );
body.position.y = yPos + part.length * 0.425; body.position.y = yPos;
g.add(body); g.add(body);
return g; return g;
} }

View file

@ -5,6 +5,7 @@ import {
buildOgiveFairingGeo, buildOgiveFairingGeo,
buildParabolicBellGeo, buildParabolicBellGeo,
buildStageConnector, buildStageConnector,
cappedColumnGroup,
} from "./geometry.js"; } from "./geometry.js";
import { import {
ACCENT_STRIPE_MAT, ACCENT_STRIPE_MAT,
@ -25,11 +26,14 @@ export function buildSinglePartCopy(
const g = new THREE.Group(); const g = new THREE.Group();
const r = comp.diameter / 2; const r = comp.diameter / 2;
if (comp.role === "engine") { if (comp.role === "engine") {
const skirt = new THREE.Mesh( const skirt = cappedColumnGroup(
new THREE.CylinderGeometry(r * 0.55, r * 0.38, comp.length * 0.22, 18), r * 0.55,
r * 0.38,
comp.length * 0.22,
AVIONICS_RING_MAT, AVIONICS_RING_MAT,
{ radialSegs: 18 },
); );
skirt.position.y = comp.length * 0.89; skirt.position.y = comp.length * 0.78;
g.add(skirt); g.add(skirt);
const bellH = comp.length * 0.8; const bellH = comp.length * 0.8;
const bell = new THREE.Mesh( const bell = new THREE.Mesh(
@ -53,28 +57,37 @@ export function buildSinglePartCopy(
const aftH = Math.max(0.28, comp.length * 0.06); const aftH = Math.max(0.28, comp.length * 0.06);
const noseH = Math.max(0.55, comp.length * 0.22); const noseH = Math.max(0.55, comp.length * 0.22);
const cylLen = Math.max(0.6, comp.length - aftH - noseH); const cylLen = Math.max(0.6, comp.length - aftH - noseH);
const aftCap = new THREE.Mesh( const aftCap = cappedColumnGroup(r, r * 0.62, aftH, barrelMat, {
new THREE.CylinderGeometry(r, r * 0.62, aftH, 32), radialSegs: 32,
barrelMat, });
); aftCap.traverse((o) => {
aftCap.position.y = aftH / 2; if ((o as THREE.Mesh).isMesh) {
aftCap.castShadow = true; o.castShadow = true;
aftCap.receiveShadow = true; o.receiveShadow = true;
}
});
g.add(aftCap); g.add(aftCap);
const tankMesh = new THREE.Mesh( const tankMesh = cappedColumnGroup(r, r, cylLen, barrelMat, {
new THREE.CylinderGeometry(r, r, cylLen, 36), radialSegs: 36,
barrelMat, });
); tankMesh.position.y = aftH;
tankMesh.position.y = aftH + cylLen / 2; tankMesh.traverse((o) => {
tankMesh.castShadow = true; if ((o as THREE.Mesh).isMesh) {
tankMesh.receiveShadow = true; o.castShadow = true;
o.receiveShadow = true;
}
});
g.add(tankMesh); g.add(tankMesh);
const nose = new THREE.Mesh( const nose = cappedColumnGroup(r * 0.14, r, noseH, barrelMat, {
new THREE.CylinderGeometry(r * 0.14, r, noseH, 36), radialSegs: 36,
barrelMat, });
); nose.position.y = aftH + cylLen;
nose.position.y = aftH + cylLen + noseH / 2; nose.traverse((o) => {
nose.castShadow = true; if ((o as THREE.Mesh).isMesh) {
o.castShadow = true;
o.receiveShadow = true;
}
});
g.add(nose); g.add(nose);
const noseTip = new THREE.Mesh( const noseTip = new THREE.Mesh(
new THREE.SphereGeometry(r * 0.14, 16, 10), new THREE.SphereGeometry(r * 0.14, 16, 10),
@ -91,13 +104,15 @@ export function buildSinglePartCopy(
g.add(band); g.add(band);
} }
} else { } else {
const tankMesh = new THREE.Mesh( const tankMesh = cappedColumnGroup(r, r, comp.length, tankMat, {
new THREE.CylinderGeometry(r, r, comp.length, 48), radialSegs: 48,
tankMat, });
); tankMesh.traverse((o) => {
tankMesh.position.y = comp.length / 2; if ((o as THREE.Mesh).isMesh) {
tankMesh.castShadow = true; o.castShadow = true;
tankMesh.receiveShadow = true; o.receiveShadow = true;
}
});
g.add(tankMesh); g.add(tankMesh);
for (const frac of [0.15, 0.5, 0.85]) { for (const frac of [0.15, 0.5, 0.85]) {
const ring = new THREE.Mesh( const ring = new THREE.Mesh(
@ -120,24 +135,28 @@ export function buildSinglePartCopy(
g.add(raceway); g.add(raceway);
} }
} else if (comp.role === "heatshield") { } else if (comp.role === "heatshield") {
const shield = new THREE.Mesh( const shield = cappedColumnGroup(
new THREE.CylinderGeometry(r * 1.03, r * 1.03, comp.length, 32), r * 1.03,
r * 1.03,
comp.length,
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x451a03, color: 0x451a03,
metalness: 0.3, metalness: 0.3,
roughness: 0.85, roughness: 0.85,
}), }),
{ radialSegs: 32 },
); );
shield.position.y = comp.length / 2;
g.add(shield); g.add(shield);
} else if (comp.role === "structure") { } else if (comp.role === "structure") {
const avionics = new THREE.Mesh( const avionics = cappedColumnGroup(r, r, comp.length, tankMat, {
new THREE.CylinderGeometry(r, r, comp.length, 48), radialSegs: 48,
tankMat, });
); avionics.traverse((o) => {
avionics.position.y = comp.length / 2; if ((o as THREE.Mesh).isMesh) {
avionics.castShadow = true; o.castShadow = true;
avionics.receiveShadow = true; o.receiveShadow = true;
}
});
g.add(avionics); g.add(avionics);
const botTrim = new THREE.Mesh( const botTrim = new THREE.Mesh(
new THREE.CylinderGeometry( new THREE.CylinderGeometry(
@ -172,20 +191,19 @@ export function buildSinglePartCopy(
const topR = nextStageDia > 0.2 ? nextStageDia / 2 : r; const topR = nextStageDia > 0.2 ? nextStageDia / 2 : r;
g.add(buildStageConnector(botR, topR, Math.max(0.6, comp.length), tankMat)); g.add(buildStageConnector(botR, topR, Math.max(0.6, comp.length), tankMat));
} else if (comp.role === "computer") { } else if (comp.role === "computer") {
const collar = new THREE.Mesh( const collarH = Math.max(0.45, comp.length);
new THREE.CylinderGeometry( const collar = cappedColumnGroup(
r * 1.02, r * 1.02,
r * 1.02, r * 1.02,
Math.max(0.45, comp.length), collarH,
24,
),
new THREE.MeshStandardMaterial({ new THREE.MeshStandardMaterial({
color: 0x0f172a, color: 0x0f172a,
metalness: 0.72, metalness: 0.72,
roughness: 0.28, roughness: 0.28,
}), }),
{ radialSegs: 24 },
); );
collar.position.y = Math.max(0.45, comp.length) / 2; g.add(collar);
const ledColor = const ledColor =
(comp.part.radHardeningLevel ?? 1) >= 3 (comp.part.radHardeningLevel ?? 1) >= 3
? 0x34d399 ? 0x34d399
@ -198,7 +216,7 @@ export function buildSinglePartCopy(
); );
busRing.rotation.x = Math.PI / 2; busRing.rotation.x = Math.PI / 2;
busRing.position.y = Math.max(0.45, comp.length) * 0.55; busRing.position.y = Math.max(0.45, comp.length) * 0.55;
g.add(collar, busRing); g.add(busRing);
} else if (comp.role === "fairing") { } else if (comp.role === "fairing") {
const shroud = new THREE.Mesh( const shroud = new THREE.Mesh(
buildOgiveFairingGeo(r, comp.length), buildOgiveFairingGeo(r, comp.length),

View file

@ -157,8 +157,11 @@ export function makeAiAgency(def: AiAgencyDef): AgencyState {
profile.startingFunds * (sponsor?.budgetMult ?? 1.0) + skill * 4_000_000, profile.startingFunds * (sponsor?.budgetMult ?? 1.0) + skill * 4_000_000,
), ),
reputation: Math.round((1 + skill * 5) * 10) / 10, reputation: Math.round((1 + skill * 5) * 10) / 10,
missionsCompleted: Math.floor(skill * 2), missionsCompleted: 0,
missionsFailed: Math.floor((1 - skill) * 2), missionsFailed: 0,
careerMissionsCompleted: Math.floor(skill * 2),
careerMissionsFailed: Math.floor((1 - skill) * 2),
contractsAbandoned: 0,
earnedTotal: 0, earnedTotal: 0,
rocketDesign: null, rocketDesign: null,
crewConfig: { crewSize: 0, lifeSupport: 1 }, crewConfig: { crewSize: 0, lifeSupport: 1 },
@ -166,6 +169,7 @@ export function makeAiAgency(def: AiAgencyDef): AgencyState {
contractHistory: [], contractHistory: [],
bankrupt: false, bankrupt: false,
bankruptAt: null, bankruptAt: null,
bankruptcyReason: null,
bailoutsTaken: 0, bailoutsTaken: 0,
unlockedTechs: defaultTechsForDifficulty(def.difficulty), unlockedTechs: defaultTechsForDifficulty(def.difficulty),
partHeritage: {}, partHeritage: {},
@ -232,6 +236,33 @@ export function seedAI(): void {
agency.partHeritage = {}; agency.partHeritage = {};
dirty = true; dirty = true;
} }
if (
agency.careerMissionsCompleted == null ||
agency.careerMissionsFailed == null
) {
const careerSkill = def ? def.skill : clamp01(agency.aiSkill ?? 0.65);
const seededCompleted = Math.floor(careerSkill * 2);
const seededFailed = Math.floor((1 - careerSkill) * 2);
agency.careerMissionsCompleted = seededCompleted;
agency.careerMissionsFailed = seededFailed;
agency.missionsCompleted = Math.max(
0,
(agency.missionsCompleted ?? 0) - seededCompleted,
);
agency.missionsFailed = Math.max(
0,
(agency.missionsFailed ?? 0) - seededFailed,
);
dirty = true;
}
if (agency.contractsAbandoned == null) {
agency.contractsAbandoned = 0;
dirty = true;
}
if (agency.bankruptcyReason === undefined) {
agency.bankruptcyReason = agency.bankrupt ? "legacy_insolvency" : null;
dirty = true;
}
if (agency.bailoutsTaken == null) { if (agency.bailoutsTaken == null) {
agency.bailoutsTaken = 0; agency.bailoutsTaken = 0;
dirty = true; dirty = true;

View file

@ -29,6 +29,9 @@ import type {
ActiveMission, ActiveMission,
AgencyState, AgencyState,
ContractOffer, ContractOffer,
RocketAssembly,
RocketDesign,
ValidationResult,
} from "../../shared/types.js"; } from "../../shared/types.js";
import { import {
clamp01, clamp01,
@ -43,14 +46,122 @@ import { synthesizeAiRocket } from "./synthesizer.js";
let lastStartupAt = 0; let lastStartupAt = 0;
function estimateAiMissionCost(
agency: AgencyState,
offer: ContractOffer,
): number {
const payload = Math.max(0, effectivePayloadMass(agency, offer) || 0);
const dv = Math.max(0, offer.requiredDv || 0);
const base = 16_000_000 + payload * 2_600 + dv * 1_800;
let mult = 1;
if (offer.tier >= 2) mult *= 1.12;
else if (offer.tier === 1) mult *= 1.05;
if (offer.advanced || offer.isConvoluted) mult *= 1.18;
if (offer.requiredDv > 12_500) mult *= 1.22;
if (offer.crewed) mult *= 1.12;
return Math.round(base * mult);
}
function expectedContractPayout(offer: ContractOffer): number {
return Math.round(offer.budget * 0.68);
}
function estimateAiMissionEconomics(
agency: AgencyState,
contract: ContractOffer,
design: RocketDesign,
asm: RocketAssembly,
validation: ValidationResult,
totalCost: number,
anomalyRiskPct: number,
): {
successCash: number;
failureCash: number;
expectedCash: number;
launchNet: number;
abandonCost: number;
successProbability: number;
} {
const profile = getDifficultyProfile(agency.difficulty);
const budget = contract.budget;
const reqDv = contract.requiredDv ?? 9_000;
const margin = Math.max(0, validation.dvMargin / Math.max(1, reqDv));
const bus = validation.assembly?.spacecraftBus;
const gradeBonusRate =
bus?.efficiencyGrade === "S"
? 0.05
: bus?.efficiencyGrade === "A"
? 0.025
: 0;
const effBonusRate =
Math.min(
0.1,
margin * 0.4 +
((validation.compliance.waivedCount ?? 0) === 0 ? 0.04 : 0),
) + gradeBonusRate;
const grossPayout = Math.round(budget * (0.65 + effBonusRate));
const scienceBonus = Math.round(
budget * ((bus?.scienceBonusPct ?? 0) / 100),
);
const canRecover =
(contract.isReusable ||
(agency.unlockedTechs ?? []).includes("methalox-reusable")) &&
validation.dvMargin >= 450 &&
(!!design.stages?.[0]?.hasFins || (design.stages?.length ?? 0) >= 2);
const stage0Cost =
asm.stages?.[0]?.stageCost ?? Math.round(totalCost * 0.55);
const reusabilityBonus = canRecover ? Math.round(stage0Cost * 0.28) : 0;
const successCash = grossPayout + scienceBonus + reusabilityBonus;
const exempt = profile.id === "explorer" || profile.id === "sandbox";
const insured = !!agency.launchInsured;
const insurancePayout = insured ? Math.round(totalCost * 0.7) : 0;
const breachPenalty =
exempt || insured ? 0 : Math.round(budget * profile.breachFineRate);
const padRepairExpected = exempt
? 0
: Math.round(
(6_000_000 + Math.min(8_000_000, Math.round(totalCost * 0.22))) *
0.45,
);
const crewInquiryExpected =
contract.crewed && !exempt ? 10_000_000 : 0;
const failureCash =
insurancePayout - breachPenalty - padRepairExpected - crewInquiryExpected;
const skill = clamp01(agency.aiSkill ?? 0.65);
const successProbability = Math.max(
0.55,
Math.min(0.97, 0.88 + skill * 0.08 - anomalyRiskPct / 140),
);
const expectedCash = Math.round(
successProbability * successCash +
(1 - successProbability) * failureCash,
);
const abandonCost =
Math.round(budget * 0.35) + Math.round(budget * profile.breachFineRate);
return {
successCash,
failureCash,
expectedCash,
launchNet: expectedCash - totalCost,
abandonCost,
successProbability,
};
}
function isContractFeasibleForAi( function isContractFeasibleForAi(
agency: AgencyState, agency: AgencyState,
offer: ContractOffer, offer: ContractOffer,
): boolean { ): boolean {
const skill = clamp01(agency.aiSkill ?? 0.65);
const advance = Math.round(offer.budget * 0.35); const advance = Math.round(offer.budget * 0.35);
const estCost = offer.budget * 0.62; const estCost = estimateAiMissionCost(agency, offer);
if (estCost > (agency.treasury + advance) * 0.72) return false; const expectedPayout = expectedContractPayout(offer);
if (agency.treasury + advance - estCost < 10_000_000) return false; const requiredMargin = 1.08 - skill * 0.06;
if (expectedPayout < estCost * requiredMargin) return false;
if (estCost > (agency.treasury + advance) * 0.9) return false;
if (agency.treasury + advance - estCost < INSOLVENCY_THRESHOLD) return false;
const prof = getDifficultyProfile(agency.difficulty); const prof = getDifficultyProfile(agency.difficulty);
if (!prof.allTechUnlocked && offer.requiredDv > 9800) { if (!prof.allTechUnlocked && offer.requiredDv > 9800) {
const unlocked = new Set(agency.unlockedTechs ?? []); const unlocked = new Set(agency.unlockedTechs ?? []);
@ -88,10 +199,14 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null {
const skill = clamp01(agency.aiSkill ?? 0.65); const skill = clamp01(agency.aiSkill ?? 0.65);
const cryoUnlocked = isPartUnlocked("eng-rl10", agency); const cryoUnlocked = isPartUnlocked("eng-rl10", agency);
const scored = offers.map((offer) => { const scored = offers.map((offer) => {
const feasible = isContractFeasibleForAi(agency, offer);
const postAdvanceCash = agency.treasury + Math.round(offer.budget * 0.35); const postAdvanceCash = agency.treasury + Math.round(offer.budget * 0.35);
const estCost = offer.budget * 0.62; const estCost = estimateAiMissionCost(agency, offer);
let score = offer.budget / 1e6; const estMargin = expectedContractPayout(offer) - estCost;
if (!isContractFeasibleForAi(agency, offer)) { let score =
offer.budget / 1e6 +
Math.max(-25, Math.min(25, estMargin / 1e6)) * 0.5;
if (!feasible) {
score -= 1000; score -= 1000;
} }
if (estCost > postAdvanceCash * 1.05 && offer.tier > 0) { if (estCost > postAdvanceCash * 1.05 && offer.tier > 0) {
@ -107,10 +222,10 @@ function chooseContractForAi(agency: AgencyState): ContractOffer | null {
score -= 40; score -= 40;
} }
score += (Math.random() - 0.5) * (1 - skill) * 140; score += (Math.random() - 0.5) * (1 - skill) * 140;
return { offer, score }; return { offer, score, feasible };
}); });
scored.sort((a, b) => b.score - a.score); scored.sort((a, b) => b.score - a.score);
return scored[0]?.offer ?? offers[0]; return scored.find((s) => s.feasible)?.offer ?? null;
} }
export function aiTick(): void { export function aiTick(): void {
@ -124,6 +239,7 @@ export function aiTick(): void {
if (!agency.isAI) continue; if (!agency.isAI) continue;
if (agency.terminatedReason) { if (agency.terminatedReason) {
agency.bankrupt = true; agency.bankrupt = true;
agency.bankruptcyReason = agency.terminatedReason;
putAgency(agency.name, agency); putAgency(agency.name, agency);
continue; continue;
} }
@ -167,6 +283,7 @@ export function aiTick(): void {
agency.treasury += grant; agency.treasury += grant;
agency.bankrupt = false; agency.bankrupt = false;
agency.bankruptAt = null; agency.bankruptAt = null;
agency.bankruptcyReason = null;
agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1; agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1;
agency.reputation = Math.max( agency.reputation = Math.max(
0, 0,
@ -188,9 +305,15 @@ export function aiTick(): void {
if (!agency.bankrupt) { if (!agency.bankrupt) {
agency.bankrupt = true; agency.bankrupt = true;
agency.bankruptAt = simTime; agency.bankruptAt = simTime;
agency.bankruptcyReason = "treasury_below_operating_threshold";
clearActiveContract(agency); clearActiveContract(agency);
putAgency(agency.name, agency); putAgency(agency.name, agency);
emit("agency.bankrupt", { agency: agency.name, isAI: true }); emit("agency.bankrupt", {
agency: agency.name,
isAI: true,
reason: agency.bankruptcyReason,
treasury: agency.treasury,
});
} }
continue; continue;
} }
@ -261,12 +384,14 @@ export function aiTick(): void {
if ((agency.aiContractReadyAtSimTime ?? 0) > simTime) { if ((agency.aiContractReadyAtSimTime ?? 0) > simTime) {
continue; continue;
} }
const abandonContract = () => { const abandonContract = (reason: string) => {
if (agency.activeContract) { if (agency.activeContract) {
const cur = agency.activeContract; const cur = agency.activeContract;
const advanceRefund = Math.round(cur.budget * 0.35); const advanceRefund = Math.round(cur.budget * 0.35);
const breachFine = Math.round(cur.budget * profile.breachFineRate); const breachFine = Math.round(cur.budget * profile.breachFineRate);
agency.treasury -= advanceRefund + breachFine; const penalty = advanceRefund + breachFine;
agency.treasury -= penalty;
agency.contractsAbandoned = (agency.contractsAbandoned ?? 0) + 1;
agency.reputation = Math.max( agency.reputation = Math.max(
0, 0,
Math.round((agency.reputation - 1.5) * 10) / 10, Math.round((agency.reputation - 1.5) * 10) / 10,
@ -278,6 +403,16 @@ export function aiTick(): void {
); );
clearActiveContract(agency); clearActiveContract(agency);
putAgency(agency.name, agency); putAgency(agency.name, agency);
emit("contract.abandoned", {
agency: agency.name,
missionId: cur.id,
offerId: cur.offerId,
contractName: cur.name,
reason,
penalty,
treasury: agency.treasury,
ai: true,
});
} }
}; };
maybeUnlockAiTech(agency, contract); maybeUnlockAiTech(agency, contract);
@ -289,7 +424,7 @@ export function aiTick(): void {
{ chargeDryRuns: true }, { chargeDryRuns: true },
); );
if (design.maturity !== "flight-ready") { if (design.maturity !== "flight-ready") {
abandonContract(); abandonContract("design_not_flight_ready");
continue; continue;
} }
const effectiveMission = { const effectiveMission = {
@ -313,11 +448,11 @@ export function aiTick(): void {
!validation.valid || !validation.valid ||
validation.compliance.mandatoryFailed.length > 0 validation.compliance.mandatoryFailed.length > 0
) { ) {
abandonContract(); abandonContract("validation_failed");
continue; continue;
} }
if (validation.totalMissionCost > agency.treasury) { if (validation.totalMissionCost > agency.treasury) {
abandonContract(); abandonContract("unaffordable");
continue; continue;
} }
const asm = const asm =
@ -356,10 +491,23 @@ export function aiTick(): void {
: 0; : 0;
const totalCost = validation.totalMissionCost + insurancePremium; const totalCost = validation.totalMissionCost + insurancePremium;
if (agency.treasury < totalCost) { if (agency.treasury < totalCost) {
putAgency(agency.name, agency); abandonContract("unaffordable");
continue; continue;
} }
const reliability = computeDesignReliability(design, asm, agency); const reliability = computeDesignReliability(design, asm, agency);
const economics = estimateAiMissionEconomics(
agency,
contract,
design,
asm,
validation,
totalCost,
reliability.anomalyRiskPct,
);
if (economics.launchNet < -economics.abandonCost) {
abandonContract("negative_expected_value");
continue;
}
const ascent = simulateAscent(design, PARTS, MATERIALS, { const ascent = simulateAscent(design, PARTS, MATERIALS, {
weather: world.weather, weather: world.weather,
activeHazards, activeHazards,
@ -435,6 +583,10 @@ export function getLeaderboard() {
return listAgencies() return listAgencies()
.map((a) => { .map((a) => {
const profile = getDifficultyProfile(a.difficulty); const profile = getDifficultyProfile(a.difficulty);
const recordCompleted =
(a.missionsCompleted ?? 0) + (a.careerMissionsCompleted ?? 0);
const recordFailed =
(a.missionsFailed ?? 0) + (a.careerMissionsFailed ?? 0);
return { return {
name: a.name, name: a.name,
isAI: !!a.isAI, isAI: !!a.isAI,
@ -444,17 +596,21 @@ export function getLeaderboard() {
difficultyLabel: profile.label, difficultyLabel: profile.label,
aiSkill: a.isAI ? clamp01(a.aiSkill ?? 0.65) : null, aiSkill: a.isAI ? clamp01(a.aiSkill ?? 0.65) : null,
bankrupt: !!a.bankrupt, bankrupt: !!a.bankrupt,
bankruptcyReason: a.bankruptcyReason ?? null,
sponsorId: a.sponsorId, sponsorId: a.sponsorId,
treasury: a.treasury, treasury: a.treasury,
reputation: Math.round(a.reputation * 10) / 10, reputation: Math.round(a.reputation * 10) / 10,
missionsCompleted: a.missionsCompleted, missionsCompleted: recordCompleted,
missionsFailed: a.missionsFailed, missionsFailed: recordFailed,
careerMissionsCompleted: a.careerMissionsCompleted ?? 0,
careerMissionsFailed: a.careerMissionsFailed ?? 0,
contractsAbandoned: a.contractsAbandoned ?? 0,
earnedTotal: a.earnedTotal, earnedTotal: a.earnedTotal,
score: Math.round( score: Math.round(
(a.bankrupt ? -1000 : 0) + (a.bankrupt ? -1000 : 0) +
a.reputation * 120 + a.reputation * 120 +
a.missionsCompleted * 300 - recordCompleted * 300 -
a.missionsFailed * 90 + recordFailed * 90 +
Math.log10(Math.max(1, a.treasury) + 1) * 55, Math.log10(Math.max(1, a.treasury) + 1) * 55,
), ),
}; };

View file

@ -102,7 +102,9 @@ export function agencyTier(agency: AgencyState | null | undefined): number {
if (!agency) return 0; if (!agency) return 0;
let score = 0; let score = 0;
score += Math.max(0, (agency.reputation ?? 0) - 1) * 0.35; score += Math.max(0, (agency.reputation ?? 0) - 1) * 0.35;
score += (agency.missionsCompleted ?? 0) * 0.95; score +=
((agency.missionsCompleted ?? 0) + (agency.careerMissionsCompleted ?? 0)) *
0.95;
score += DIFF_TIER_BONUS[normalizeDifficulty(agency.difficulty)] ?? 0; score += DIFF_TIER_BONUS[normalizeDifficulty(agency.difficulty)] ?? 0;
return Math.max(0, Math.min(3, Math.floor(score))); return Math.max(0, Math.min(3, Math.floor(score)));
} }

View file

@ -51,6 +51,7 @@ export function registerAgencyRoutes(router: Router): void {
agency.sponsorId = sponsorId ?? null; agency.sponsorId = sponsorId ?? null;
agency.bankrupt = false; agency.bankrupt = false;
agency.bankruptAt = null; agency.bankruptAt = null;
agency.bankruptcyReason = null;
agency.terminatedReason = null; agency.terminatedReason = null;
if (!agency.unlockedTechs?.length) { if (!agency.unlockedTechs?.length) {
agency.unlockedTechs = profile.allTechUnlocked agency.unlockedTechs = profile.allTechUnlocked
@ -140,6 +141,7 @@ export function registerAgencyRoutes(router: Router): void {
agency.treasury += grant; agency.treasury += grant;
agency.bankrupt = false; agency.bankrupt = false;
agency.bankruptAt = null; agency.bankruptAt = null;
agency.bankruptcyReason = null;
agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1; agency.bailoutsTaken = (agency.bailoutsTaken ?? 0) + 1;
agency.reputation = Math.max( agency.reputation = Math.max(
0, 0,
@ -165,6 +167,7 @@ export function registerAgencyRoutes(router: Router): void {
agency.reputation = 1; agency.reputation = 1;
agency.missionsCompleted = 0; agency.missionsCompleted = 0;
agency.missionsFailed = 0; agency.missionsFailed = 0;
agency.contractsAbandoned = 0;
agency.earnedTotal = 0; agency.earnedTotal = 0;
agency.rocketDesign = null; agency.rocketDesign = null;
agency.crewConfig = { crewSize: 0, lifeSupport: 1 }; agency.crewConfig = { crewSize: 0, lifeSupport: 1 };
@ -172,6 +175,7 @@ export function registerAgencyRoutes(router: Router): void {
agency.contractHistory = []; agency.contractHistory = [];
agency.bankrupt = false; agency.bankrupt = false;
agency.bankruptAt = null; agency.bankruptAt = null;
agency.bankruptcyReason = null;
agency.bailoutsTaken = 0; agency.bailoutsTaken = 0;
agency.unlockedTechs = profile.allTechUnlocked agency.unlockedTechs = profile.allTechUnlocked
? TECH_TREE.map((t) => t.id) ? TECH_TREE.map((t) => t.id)

View file

@ -177,6 +177,7 @@ export function settleMissionOutcome(
"Catastrophic Loss of Crew — Flight Director License Revoked"; "Catastrophic Loss of Crew — Flight Director License Revoked";
agency.bankrupt = true; agency.bankrupt = true;
agency.bankruptAt = simTime; agency.bankruptAt = simTime;
agency.bankruptcyReason = agency.terminatedReason;
} }
summary = summary =
profile.id === "sandbox" profile.id === "sandbox"
@ -215,7 +216,13 @@ export function settleMissionOutcome(
if (agency.treasury < 5_000_000 && !agency.bankrupt) { if (agency.treasury < 5_000_000 && !agency.bankrupt) {
agency.bankrupt = true; agency.bankrupt = true;
agency.bankruptAt = simTime; agency.bankruptAt = simTime;
emit("agency.bankrupt", { agency: agency.name, isAI: !!agency.isAI }); agency.bankruptcyReason = "mission_failure_insolvency";
emit("agency.bankrupt", {
agency: agency.name,
isAI: !!agency.isAI,
reason: agency.bankruptcyReason,
treasury: agency.treasury,
});
} }
emit("mission.failed", { emit("mission.failed", {
agency: agency.name, agency: agency.name,

View file

@ -77,6 +77,7 @@ function chargeFacilityOverhead(simTime: number): void {
if (agency.treasury < 0) { if (agency.treasury < 0) {
agency.bankrupt = true; agency.bankrupt = true;
agency.bankruptAt = simTime; agency.bankruptAt = simTime;
agency.bankruptcyReason = "facility_overhead_insolvency";
emit("agency.bankrupt", { emit("agency.bankrupt", {
agency: agency.name, agency: agency.name,
isAI: !!agency.isAI, isAI: !!agency.isAI,

View file

@ -60,6 +60,9 @@ export interface AgencyState {
reputation: number; reputation: number;
missionsCompleted: number; missionsCompleted: number;
missionsFailed: number; missionsFailed: number;
careerMissionsCompleted?: number;
careerMissionsFailed?: number;
contractsAbandoned?: number;
earnedTotal: number; earnedTotal: number;
rocketDesign: RocketDesign | null; rocketDesign: RocketDesign | null;
crewConfig: CrewConfig | null; crewConfig: CrewConfig | null;
@ -67,6 +70,7 @@ export interface AgencyState {
contractHistory: string[]; contractHistory: string[];
bankrupt: boolean; bankrupt: boolean;
bankruptAt?: number | null; bankruptAt?: number | null;
bankruptcyReason?: string | null;
bailoutsTaken?: number; bailoutsTaken?: number;
unlockedTechs?: string[]; unlockedTechs?: string[];
partHeritage?: Record<string, number>; partHeritage?: Record<string, number>;