import { CollectionConfig } from "payload"; import { isDeveloper } from "@/utils/access-control/isRole"; import type { Resource } from "@/payload-types"; import { emitGameEvent } from "@/utils/event-log/emit"; import { createStaffingFields } from "@/collections/game/staffingFields"; import { createProductionFields } from "@/collections/game/productionFields"; import { createModuleFields } from "@/collections/game/moduleFields"; import { createAuraFields } from "@/collections/game/auraFields"; export const Structures: CollectionConfig = { slug: "structures", admin: { useAsTitle: "name", group: "Logistics", }, hooks: { beforeChange: [ async ({ data, originalDoc, req, context }) => { if (!data || !originalDoc) return data; if ((context as any)?.skipGridRepack) return data; const doc = data as any; const orig = originalDoc as any; const oldX = orig.xSize ?? 0; const oldY = orig.ySize ?? 0; const newX = doc.xSize ?? 0; const newY = doc.ySize ?? 0; if (oldX === newX && oldY === newY) return data; if (!newX || !newY) return data; const { docs: gameStructures } = await req.payload.find({ collection: "game-structures", depth: 1, where: { type: { equals: originalDoc.id } }, limit: 1000, }); for (const gs of gameStructures) { const gsDoc = gs as any; const storedResources = [...(gsDoc.storedResources ?? [])]; const voidStorage = [...(gsDoc.voidStorage ?? [])]; const newVoid: any[] = []; const remaining: any[] = []; let changed = false; // Step 1: try to recover void items back to grid if space allows const gridExpanded = newX > oldX || newY > oldY; if (gridExpanded) { for (const entry of voidStorage) { const res = entry.resource as Resource | undefined; if (!res || typeof res !== "object") { newVoid.push(entry); continue; } const rotated = entry.rotated ?? false; const ew = rotated ? ((res as any).gridHeight ?? 1) : ((res as any).gridWidth ?? 1); const eh = rotated ? ((res as any).gridWidth ?? 1) : ((res as any).gridHeight ?? 1); let spot: { x: number; y: number } | null = null; for (let y = 0; y <= newY - eh && !spot; y++) { for (let x = 0; x <= newX - ew && !spot; x++) { let overlaps = false; for (const placed of remaining) { const pRes = placed.resource as Resource | undefined; if (!pRes || typeof pRes !== "object") continue; const pRotated = placed.rotated ?? false; const pw = pRotated ? ((pRes as any).gridHeight ?? 1) : ((pRes as any).gridWidth ?? 1); const ph = pRotated ? ((pRes as any).gridWidth ?? 1) : ((pRes as any).gridHeight ?? 1); const px = placed.gridX; const py = placed.gridY; for (let dx = 0; dx < ew && !overlaps; dx++) { for (let dy = 0; dy < eh && !overlaps; dy++) { const cx = x + dx; const cy = y + dy; for (let pdx = 0; pdx < pw; pdx++) { for (let pdy = 0; pdy < ph; pdy++) { if (px + pdx === cx && py + pdy === cy) { overlaps = true; break; } } if (overlaps) break; } } } if (overlaps) break; } if (!overlaps) spot = { x, y }; } } if (spot) { remaining.push({ ...entry, gridX: spot.x, gridY: spot.y }); changed = true; } else { newVoid.push(entry); } } } else { newVoid.push(...voidStorage); } // Step 2: repack stored resources for the new grid size for (const entry of storedResources) { const res = entry.resource as Resource | undefined; if (!res || typeof res !== "object") { remaining.push(entry); continue; } const rotated = entry.rotated ?? false; const ew = rotated ? ((res as any).gridHeight ?? 1) : ((res as any).gridWidth ?? 1); const eh = rotated ? ((res as any).gridWidth ?? 1) : ((res as any).gridHeight ?? 1); const gx = entry.gridX; const gy = entry.gridY; const inBounds = gx + ew <= newX && gy + eh <= newY; if (inBounds) { let overlaps = false; for (const placed of remaining) { const pRes = placed.resource as Resource | undefined; if (!pRes || typeof pRes !== "object") continue; const pRotated = placed.rotated ?? false; const pw = pRotated ? ((pRes as any).gridHeight ?? 1) : ((pRes as any).gridWidth ?? 1); const ph = pRotated ? ((pRes as any).gridWidth ?? 1) : ((pRes as any).gridHeight ?? 1); const px = placed.gridX; const py = placed.gridY; for (let dx = 0; dx < ew && !overlaps; dx++) { for (let dy = 0; dy < eh && !overlaps; dy++) { const cx = gx + dx; const cy = gy + dy; for (let pdx = 0; pdx < pw; pdx++) { for (let pdy = 0; pdy < ph; pdy++) { if (px + pdx === cx && py + pdy === cy) { overlaps = true; break; } } if (overlaps) break; } } } if (overlaps) break; } if (!overlaps) { remaining.push(entry); continue; } } let spot: { x: number; y: number } | null = null; for (let y = 0; y <= newY - eh && !spot; y++) { for (let x = 0; x <= newX - ew && !spot; x++) { let overlaps = false; for (const placed of remaining) { const pRes = placed.resource as Resource | undefined; if (!pRes || typeof pRes !== "object") continue; const pRotated = placed.rotated ?? false; const pw = pRotated ? ((pRes as any).gridHeight ?? 1) : ((pRes as any).gridWidth ?? 1); const ph = pRotated ? ((pRes as any).gridWidth ?? 1) : ((pRes as any).gridHeight ?? 1); const px = placed.gridX; const py = placed.gridY; for (let dx = 0; dx < ew && !overlaps; dx++) { for (let dy = 0; dy < eh && !overlaps; dy++) { const cx = x + dx; const cy = y + dy; for (let pdx = 0; pdx < pw; pdx++) { for (let pdy = 0; pdy < ph; pdy++) { if (px + pdx === cx && py + pdy === cy) { overlaps = true; break; } } if (overlaps) break; } } } if (overlaps) break; } if (!overlaps) spot = { x, y }; } } if (spot) { remaining.push({ ...entry, gridX: spot.x, gridY: spot.y }); if (spot.x !== gx || spot.y !== gy) changed = true; } else { newVoid.push(entry); changed = true; } } if (changed) { await req.payload.update({ collection: "game-structures", id: gsDoc.id, data: { storedResources: remaining, voidStorage: newVoid }, context: { skipGridRepack: true }, }); } await emitGameEvent(req.payload, { type: "structure:resize", message: `Resized "${gsDoc.name}" from ${oldX}×${oldY} to ${newX}×${newY}`, structure: gsDoc.id, targetCollection: "game-structures", targetId: gsDoc.id, data: { oldX, oldY, newX, newY, structureName: gsDoc.name, voidCount: newVoid.length, repositioned: changed, }, }); } return data; }, ], }, fields: [ { label: "Identity & Visuals", type: "group", fields: [ { name: "name", type: "text", required: true, admin: { description: 'The display name (e.g., "Forward Operating Base").', }, }, { name: "codeName", type: "text", required: true, admin: { description: 'Internal ID for scripts (e.g., "fob_alpha_tier1").', }, }, { name: "approvalStatus", type: "select", label: "Approval Status", options: [ { label: "In Progress", value: "in_progress" }, { label: "Ready for Review", value: "ready_for_review" }, { label: "Approved", value: "approved" }, { label: "Rejected", value: "rejected" }, { label: "Revision Requested", value: "revision_requested" }, ], defaultValue: "in_progress", filterOptions: ({ options, data: _data, req }) => { return !isDeveloper({ req }) ? options.filter((option) => typeof option === "string" ? options : ["in_progress", "ready_for_review"].includes(option.value), ) : options; }, required: true, admin: { description: "Mark whether this structure is ready for developer approval and implementation into the live environment.", }, }, { name: "description", type: "richText", required: true, admin: { description: "A detailed description of the structure, including details like tactical advantages, resource production, and/or world lore regarding this structure.", }, }, { name: "image", type: "upload", relationTo: "media", admin: { description: "An image depicting the structure. While not required, it is highly recommended as the existence of an image will affect the layout of the structure's page on the front-end.", }, }, { name: "category", type: "select", required: true, options: [ { label: "Logistics", value: "logistics", }, { label: "Military", value: "military", }, { label: "Civilian", value: "civilian", }, ], }, ], }, { label: "Construction & Progression", type: "group", fields: [ { name: "materials", type: "array", required: true, fields: [ { name: "resource", type: "relationship", relationTo: "resources", required: true, }, { name: "amount", type: "number", }, ], }, { name: "constructionDurationMinutes", type: "number", required: true, label: "Build Time (minutes)", min: 1, admin: { description: "How many real minutes it takes to complete construction of this structure after materials are delivered and building starts.", }, }, { name: "constructionCrewRequired", type: "number", min: 0, defaultValue: 0, label: "Construction Crew Required", admin: { description: "Effective crew needed for the listed build time. 0 builds at full speed with no labor. Understaffed sites build proportionally slower.", }, }, { name: "requiredTech", type: "relationship", relationTo: "technologies", hasMany: true, label: "Required Technology", admin: { description: "What research must be done before this can be built.", }, }, { name: "requiresUpgrade", type: "checkbox", admin: { description: "If true, this structure can only be constructed as the result of an upgrade to an existing structure. If false, this structure can be constructed independently of any other structure's upgrade tree, even if another structure can upgrade into this one.", }, }, { name: "upgradesInto", type: "relationship", relationTo: "structures", admin: { description: 'When this structure is upgraded, it becomes this type of structure. Note that the costs of the new structure apply - if this field is set, the new structure\'s build costs will still be consumed when this building is upgraded. To make it cheaper to upgrade, lower the "Upgrade Cost Multiplier".', }, }, { name: "upgradeCostMultiplier", type: "number", defaultValue: 1, admin: { description: "The multiplier applied to the base build cost of the structure being upgraded into. A value of one (1) means the cost will exactly equal the structure's normal build cost, while a value of zero (0) would make the upgrade entirely free, only taking up construction time instead.", }, }, { label: "Placement Rules", type: "group", fields: [ { name: "terrainType", type: "select", required: true, options: [ { label: "Land", value: "land", }, { label: "Water", value: "water", }, ], }, { name: "resourcesInRange", type: "array", admin: { description: "What resources, if any, must be within a certain distance of this structure on placement.", }, fields: [ { name: "resource", type: "relationship", relationTo: "resources", }, { name: "range", type: "number", }, ], }, { name: "structuresInRange", type: "array", admin: { description: "What structures, if any, must be within a certain distance of this structure on placement.", }, fields: [ { name: "structure", type: "relationship", relationTo: "structures", }, { name: "range", type: "number", }, ], }, ], }, ], }, { label: "Economy & Upkeep", type: "group", fields: [ { name: "upkeep", type: "array", admin: { description: "Recurring costs to keep this structure online.", }, fields: [ { name: "resource", type: "relationship", relationTo: "resources", }, { name: "amount", type: "number", admin: { description: 'How much of this resource is consumed per "game tick" (every hour.)', }, }, ], }, { name: "sellPrice", type: "number", admin: { description: "A base price that this structure could sell for when fully operational. Leaving this empty will make this structure unsellable.", }, }, ], }, { label: "Staffing Defaults", type: "group", fields: createStaffingFields("defaults"), }, { label: "Production Recipe Defaults", type: "group", fields: createProductionFields("defaults"), }, { label: "Modules", type: "group", fields: createModuleFields("defaults"), }, ...createAuraFields(), { label: "Production & Function", type: "group", fields: [ { name: "functionType", type: "select", admin: { description: "The app will use this type to determine what processes should run for this structure type.", }, options: [ { label: "Producer", value: "producer", }, { label: "Storage", value: "storage", }, { label: "Sensor", value: "sensor", }, { label: "Converter", value: "converter", }, { label: "Defense", value: "defense", }, { label: "Miscellaneous", value: "miscellaneous", }, ], }, { label: "Production Capabilities", type: "group", fields: [ { name: "canProduce", type: "relationship", relationTo: ["assets", "vehicles", "resources"], hasMany: true, }, { name: "autoGeneratedResources", type: "array", fields: [ { name: "resource", type: "relationship", required: true, relationTo: "resources", }, { name: "minAmount", type: "number", required: true, admin: { description: "The minimum amount of this resource produced each production cycle.", }, }, { name: "maxAmount", type: "number", admin: { description: "The maximum amount of this resource produced each production cycle. If this field is left empty, will produce a static amount equal to the minimum value.", }, }, { name: "minFrequency", type: "text", required: true, defaultValue: "1", admin: { description: "The minimum number of ticks it takes to produce this resource (e.g., '5' would produce this resource, at minimum, every 5 ticks).", }, }, { name: "maxFrequency", type: "text", admin: { description: "The maximum number of ticks it takes to produce this resource (e.g., '5' would produce this resource, at maximum, every 5 ticks, ignoring production chance).", }, }, { name: "produceChance", type: "number", defaultValue: 100, min: 1, max: 100, admin: { description: "The chance (1-100) that this resource will be produced each production cycle.", }, }, ], }, ], }, { label: "Storage", type: "group", fields: [ { name: "maxCapacityMass", type: "number", label: "Max Capacity (mass)", admin: { description: "The maximum storage capacity of this structure as mass (retrieved from the mass defined for every asset stored here.)", }, }, { name: "restrictToAllowed", type: "checkbox", label: "Restrict to allowed items only", defaultValue: false, admin: { description: "When enabled, ONLY the items listed in Allowed Storage can be stored here. Everything else is rejected. When disabled, the Allowed Storage list still enforces per-item quantity caps, but other items are permitted up to the mass capacity.", }, }, { label: "Storage Slot Dimensions", type: "group", fields: [ { name: "xSize", type: "number", label: "Columns (X)", }, { name: "ySize", type: "number", label: "Rows (Y)", }, ], }, { // Named group on purpose: an unnamed group would flatten its // xSize/ySize onto the document and collide with the top-level // storage slot dimensions above. name: "vehicleBay", label: "Vehicle Bay Dimensions", type: "group", admin: { description: "Grid capacity for the Garage view. Structures whose blueprint defines a bay with both dimensions greater than zero expose a garage grid holding parked vehicle instances. Empty = no vehicle storage.", }, fields: [ { name: "xSize", type: "number", label: "Columns (X)", }, { name: "ySize", type: "number", label: "Rows (Y)", }, ], }, { name: "allowedStorage", type: "array", fields: [ { name: "item", type: "relationship", relationTo: ["assets", "vehicles", "resources"], }, { name: "amount", type: "number", admin: { description: "How many of this asset, vehicle, or resource can be stored here.", }, }, ], }, { name: "prohibitedStorage", type: "array", admin: { description: "Any items from this list can never be stored here, even if they meet all other criteria.", }, fields: [ { name: "item", type: "relationship", relationTo: ["assets", "vehicles", "resources"], }, ], }, ], }, ], }, { label: "Physical Properties", type: "group", fields: [ { label: "Durability", type: "group", fields: [ { name: "maxHealth", type: "number", required: true, }, { name: "repairSpeed", type: "number", admin: { description: "So long as the structure meets its operational requirements, this is the amount of health restored to the structure every game tick.", }, }, ], }, ], }, ], };