import type { Payload } from "payload"; import type { GameStructure, Resource, Structure } from "@/payload-types"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { emitGameEvent } from "@/utils/event-log/emit"; import { consumeStorage, relationshipId, storedAmount } from "./storage"; import { effectiveCapacityMass, installedModuleEffects } from "./modules"; import { auraBonusAt, type AuraSourceLike } from "./adjacency"; import type { MapPoint } from "@/lib/map/points"; type PayloadType = Awaited>; export interface ProductionLog { info?: (message: string) => void; error?: (message: string) => void; } export interface ProductionTickResult { processed: number; produced: number; stalled: number; } type ProductionLine = { resource: number | Resource; amountPerHour?: number | null }; type StorageEntry = NonNullable[number]; type VoidEntry = NonNullable[number]; /** Cap on accumulated production time so a long outage cannot dump a mountain at once. */ const MAX_DELTA_HOURS = 8; async function structureBlueprint( payload: PayloadType, structure: GameStructure, ): Promise { const reference = structure.type; if (typeof reference === "object" && reference !== null) return reference as Structure; if (typeof reference !== "number") return null; return payload.findByID({ collection: "structures", id: reference, depth: 1, overrideAccess: true, }); } function capacityKg(blueprint: Structure | null): number | null { const capacity = blueprint?.maxCapacityMass; return capacity != null && capacity > 0 ? capacity : null; } function storedMass( storedResources: StorageEntry[], voidStorage: VoidEntry[], resourceById: Map, ): number { const massOf = (entry: { resource: number | Resource; amount?: number | null }): number => { const id = relationshipId(entry.resource); return (resourceById.get(id ?? -1)?.massPerUnit ?? 0) * (entry.amount ?? 0); }; return ( storedResources.reduce((total, entry) => total + massOf(entry), 0) + voidStorage.reduce((total, entry) => total + massOf(entry), 0) ); } function mergeIntoVoid(voidStorage: VoidEntry[], resourceId: number, amount: number): VoidEntry[] { if (amount <= 0) return voidStorage; const existing = voidStorage.find((entry) => relationshipId(entry.resource) === resourceId); if (existing) { return voidStorage.map((entry) => entry === existing ? { ...entry, amount: (entry.amount ?? 0) + amount } : entry, ); } return [...voidStorage, { resource: resourceId, amount, gridX: 0, gridY: 0 }]; } async function hasActiveLabor(payload: PayloadType, structureId: number): Promise { const rows = await payload.find({ collection: "npc-staffing", where: { and: [ { structure: { equals: structureId } }, { status: { equals: "active" } }, { headcount: { greater_than: 0 } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); return rows.docs.length > 0; } /** * Runs every complete, unpaused structure's production recipe for the time * elapsed since its lastProductionAt: consumes inputs from storage, pushes * outputs into void storage, and stalls with a surfaced reason on missing * labor, missing inputs, or a full store. Stalled time produces nothing (the * clock always advances), and the first tick after completion only primes the * clock so no output exists before a full interval has passed. */ export async function processProductionTick( payload: PayloadType, log?: ProductionLog, now: Date = new Date(), siteIds?: number[], ): Promise { const result: ProductionTickResult = { processed: 0, produced: 0, stalled: 0 }; const nowIso = now.toISOString(); const sites = await payload.find({ collection: "game-structures", where: { and: [ { constructionStatus: { equals: "complete" } }, ...(siteIds && siteIds.length > 0 ? [{ id: { in: siteIds } }] : []), ], }, limit: 1000, depth: 2, overrideAccess: true, }); // Aura sources must be unscoped even when siteIds scopes the sweep: // neighbors outside the scope still project their auras inward. const auraSourceDocs = siteIds && siteIds.length > 0 ? ( await payload.find({ collection: "game-structures", where: { constructionStatus: { equals: "complete" } }, depth: 1, limit: 1000, overrideAccess: true, }) ).docs : sites.docs; const auraSources: AuraSourceLike[] = auraSourceDocs.map((doc) => { const structure = doc as unknown as GameStructure; return { id: structure.id, coordinates: (structure.coordinates ?? null) as MapPoint | null, constructionStatus: structure.constructionStatus ?? "complete", blueprint: typeof structure.type === "object" ? structure.type : null, }; }); for (const doc of sites.docs) { const structure = doc as unknown as GameStructure; try { if (structure.productionPaused) continue; const outputs = (structure.productionOutputs ?? []) as ProductionLine[]; if (outputs.length === 0) continue; const inputs = (structure.productionInputs ?? []) as ProductionLine[]; const last = structure.lastProductionAt ? new Date(structure.lastProductionAt).getTime() : NaN; if (!Number.isFinite(last)) { await payload.update({ collection: "game-structures", id: structure.id, data: { lastProductionAt: nowIso }, overrideAccess: true, }); continue; } const deltaHours = Math.max(0, Math.min(MAX_DELTA_HOURS, (now.getTime() - last) / 3_600_000)); if (deltaHours <= 0) continue; result.processed++; if (!(await hasActiveLabor(payload, structure.id))) { await stall(payload, structure, "no_labor", nowIso); result.stalled++; continue; } let storedResources: StorageEntry[] = [...(structure.storedResources ?? [])]; let voidStorage: VoidEntry[] = [...(structure.voidStorage ?? [])]; const shortages: string[] = []; for (const line of inputs) { const resourceId = relationshipId(line.resource); if (resourceId === null) continue; const needed = Math.max(0, (line.amountPerHour ?? 0) * deltaHours); if (needed <= 0) continue; const available = storedAmount(storedResources, resourceId) + storedAmount(voidStorage, resourceId); if (available < needed) { const name = typeof line.resource === "object" ? line.resource.name : `Resource #${line.resource}`; shortages.push(`${name} (need ${needed}, have ${available})`); } } if (shortages.length > 0) { await stall(payload, structure, "missing_inputs", nowIso, shortages.join(", ")); result.stalled++; continue; } const resourceIds = new Set(); for (const line of [...inputs, ...outputs]) { const id = relationshipId(line.resource); if (id !== null) resourceIds.add(id); } const resourceById = new Map(); for (const id of resourceIds) { const resource = await payload.findByID({ collection: "resources", id, depth: 0, overrideAccess: true, }); resourceById.set(id, resource as unknown as Resource); } let producedLines = outputs .map((line) => ({ resourceId: relationshipId(line.resource), amount: Math.max(0, (line.amountPerHour ?? 0) * deltaHours), })) .filter( (line): line is { resourceId: number; amount: number } => line.resourceId !== null && line.amount > 0, ); if (producedLines.length === 0) { await payload.update({ collection: "game-structures", id: structure.id, data: { lastProductionAt: nowIso, productionStallReason: null }, overrideAccess: true, }); continue; } const blueprint = await structureBlueprint(payload, structure); const moduleEffects = installedModuleEffects( blueprint ?? {}, ((structure.installedModules ?? []) as { name: string }[]).map((entry) => entry.name), ); const adjacency = auraBonusAt( { id: structure.id, coordinates: (structure.coordinates ?? null) as MapPoint | null }, auraSources, ); const outputBoost = 1 + moduleEffects.productionMultiplier + adjacency.productionMultiplier; if (outputBoost > 1) { producedLines = producedLines.map((line) => ({ ...line, amount: line.amount * outputBoost, })); } const capacity = effectiveCapacityMass( capacityKg(blueprint), moduleEffects.capacityMass + adjacency.capacityMass, ); if (capacity !== null) { const free = capacity - storedMass(storedResources, voidStorage, resourceById); if (free <= 0) { await stall(payload, structure, "storage_full", nowIso); result.stalled++; continue; } const incomingMass = producedLines.reduce( (total, line) => total + (resourceById.get(line.resourceId)?.massPerUnit ?? 0) * line.amount, 0, ); if (incomingMass > free) { const scale = free / incomingMass; producedLines = producedLines.map((line) => ({ ...line, amount: line.amount * scale })); } } for (const line of inputs) { const resourceId = relationshipId(line.resource); if (resourceId === null) continue; const needed = Math.max(0, (line.amountPerHour ?? 0) * deltaHours); if (needed <= 0) continue; const fromGrid = consumeStorage(storedResources, resourceId, needed); storedResources = fromGrid.entries; voidStorage = consumeStorage(voidStorage, resourceId, fromGrid.remaining).entries; } for (const line of producedLines) { voidStorage = mergeIntoVoid(voidStorage, line.resourceId, line.amount); } await payload.update({ collection: "game-structures", id: structure.id, data: { storedResources, voidStorage, lastProductionAt: nowIso, productionStallReason: null, }, overrideAccess: true, }); const summary = producedLines .map( (line) => `${Math.round(line.amount)} ${resourceById.get(line.resourceId)?.name ?? ""}`, ) .join(", "); await emitGameEvent(payload, { type: EventTypes.ProductionOutput, message: `${structure.name} produced ${summary}`, structure: structure.id, targetCollection: "game-structures", targetId: structure.id, data: { deltaHours, lines: producedLines }, }); result.produced++; } catch (error) { log?.error?.( `Production tick failed for structure #${structure.id}: ${ error instanceof Error ? error.message : String(error) }`, ); } } return result; } async function stall( payload: PayloadType, structure: GameStructure, reason: string, nowIso: string, detail?: string, ): Promise { await payload.update({ collection: "game-structures", id: structure.id, data: { productionStallReason: reason, lastProductionAt: nowIso }, overrideAccess: true, }); if ((structure.productionStallReason ?? null) !== reason) { await emitGameEvent(payload, { type: EventTypes.ProductionPaused, message: `${structure.name} production paused: ${reason}${detail ? ` (${detail})` : ""}`, structure: structure.id, targetCollection: "game-structures", targetId: structure.id, }); } }