1
0
Fork 0

feat(garage): add vehicle bay schema fields, geometry helpers, and backfill

This commit is contained in:
Jason Fraley 2026-10-13 15:13:23 -04:00
parent 8f91bfedbd
commit 6c1bbda944
11 changed files with 41288 additions and 1 deletions

View file

@ -21,6 +21,7 @@
"payload": "cross-env NODE_OPTIONS=--no-deprecation payload",
"migrate": "bun run src/scripts/run-migrations.ts",
"mcp:key": "bun run src/tools/cli/create-mcp-key.ts",
"garage:backfill": "bun run src/tools/cli/backfillGaragePlacement.ts",
"db": "cross-env NODE_OPTIONS=--no-deprecation pnpm drizzle-kit",
"start": "cross-env NODE_OPTIONS=--no-deprecation next start",
"staging": "cross-env NODE_ENV=test NODE_OPTIONS=--no-deprecation next start",

View file

@ -39,6 +39,42 @@ export const GameVehicles: CollectionConfig = {
description: "The structure where this vehicle is currently stationed. Null if in transit.",
},
},
{
name: "garageGridX",
type: "number",
min: 0,
admin: {
description:
"Column position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.",
},
},
{
name: "garageGridY",
type: "number",
min: 0,
admin: {
description:
"Row position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.",
},
},
{
name: "garageRotated",
type: "checkbox",
defaultValue: false,
admin: {
description: "Whether this vehicle is rotated 90 degrees in the garage bay (swaps width and height).",
},
},
{
name: "bridgeUid",
type: "text",
unique: true,
index: true,
admin: {
description:
"Per-instance identity assigned by the Arma bridge (docs/arma-bridge/garage-sync.md). Two identical vehicles are told apart by this tag. Null = never seen by the game.",
},
},
{
name: "faction",
type: "relationship",

View file

@ -671,6 +671,30 @@ export const Structures: CollectionConfig = {
},
],
},
{
// 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",

View file

@ -273,6 +273,28 @@ export const Vehicles: CollectionConfig = {
},
],
},
{
label: "Garage Footprint",
type: "group",
admin: {
description:
"Cells this vehicle's type occupies in a structure's Garage vehicle bay (width = columns, height = rows). Unset defaults to 1x1. Independent of the display-only storage grid dimensions above.",
},
fields: [
{
name: "garageWidth",
type: "number",
label: "Garage Width (cells)",
min: 1,
},
{
name: "garageHeight",
type: "number",
label: "Garage Height (cells)",
min: 1,
},
],
},
{
label: "Cargo Capacity",
type: "group",

222
src/lib/garage/index.ts Normal file
View file

@ -0,0 +1,222 @@
import type { GameStructure, GameVehicle, Structure, Vehicle } from "@/payload-types";
/**
* Garage grid geometry for vehicle bays.
*
* Clones the proven shape of src/lib/logistics.ts (footprint / occupancy /
* placement validity / auto-arrange) for vehicle instances parked in a
* structure's vehicle bay. Vehicles never stack; rotation swaps width and
* height. Footprints come from the vehicle template's dedicated
* garageWidth/garageHeight fields (default 1x1 when unset).
*/
export type GridDimensions = { width: number; height: number };
export type GarageGridItem = {
/** Stable client identity: String(gameVehicleId). */
id: string;
vehicleId: number;
gridX: number;
gridY: number;
rotated: boolean;
template: Vehicle;
};
/**
* Resolve a blueprint's vehicle bay dimensions. Returns null when the
* blueprint defines no usable bay (either dimension missing or <= 0).
*/
export function getGarageBayDimensions(blueprint: Structure | null | undefined): GridDimensions | null {
const x = blueprint?.vehicleBay?.xSize ?? 0;
const y = blueprint?.vehicleBay?.ySize ?? 0;
if (!x || !y || x <= 0 || y <= 0) return null;
return { width: Math.floor(x), height: Math.floor(y) };
}
/** True when a game structure's populated blueprint exposes a vehicle bay. */
export function structureHasVehicleBay(
structure: (GameStructure & { type?: Structure | null }) | null | undefined,
): boolean {
return getGarageBayDimensions(structure?.type ?? null) !== null;
}
/**
* Get the effective footprint of a vehicle in the bay, accounting for
* rotation. Falls back to 1x1 when the template has no garage dimensions.
*/
export function getVehicleFootprint(template: Vehicle | null | undefined, rotated: boolean): GridDimensions {
const w = Math.max(1, Math.floor(template?.garageWidth ?? 1));
const h = Math.max(1, Math.floor(template?.garageHeight ?? 1));
return rotated ? { width: h, height: w } : { width: w, height: h };
}
/**
* Get the cells occupied by a footprint as an array of "x,y" strings.
*/
export function getGarageOccupiedCells(
gridX: number,
gridY: number,
width: number,
height: number,
): string[] {
const cells: string[] = [];
for (let dx = 0; dx < width; dx++) {
for (let dy = 0; dy < height; dy++) {
cells.push(`${gridX + dx},${gridY + dy}`);
}
}
return cells;
}
/**
* Check whether placing a vehicle at (targetX, targetY) would overlap any
* other parked vehicle or leave the bay. Returns true if VALID.
*/
export function isGaragePlacementValid(
items: GarageGridItem[],
excludeId: string | null,
targetX: number,
targetY: number,
width: number,
height: number,
bayWidth: number,
bayHeight: number,
): boolean {
if (targetX < 0 || targetY < 0) return false;
if (targetX + width > bayWidth || targetY + height > bayHeight) return false;
const targetCells = new Set(getGarageOccupiedCells(targetX, targetY, width, height));
for (const item of items) {
if (item.id === excludeId) continue;
const fp = getVehicleFootprint(item.template, item.rotated);
const occupied = getGarageOccupiedCells(item.gridX, item.gridY, fp.width, fp.height);
for (const cell of occupied) {
if (targetCells.has(cell)) return false;
}
}
return true;
}
/**
* Find the first available spot for a footprint, scanning left-to-right,
* top-to-bottom (row-major). Returns {x, y} or null when the bay is full.
*/
export function findGarageEmptySpot(
items: GarageGridItem[],
width: number,
height: number,
bayWidth: number,
bayHeight: number,
): { x: number; y: number } | null {
for (let y = 0; y <= bayHeight - height; y++) {
for (let x = 0; x <= bayWidth - width; x++) {
if (isGaragePlacementValid(items, null, x, y, width, height, bayWidth, bayHeight)) {
return { x, y };
}
}
}
return null;
}
/**
* Auto-arrange all parked vehicles into the bay (row-major greedy repack in
* input order). Vehicles that no longer fit are returned in `overflow` and
* should stay unplaced (they surface in the Elsewhere section instead).
*/
export function autoArrangeGarageItems(
items: GarageGridItem[],
bayWidth: number,
bayHeight: number,
): { placed: Array<{ id: string; gridX: number; gridY: number }>; overflow: string[] } {
const placed: Array<GarageGridItem> = [];
const result: Array<{ id: string; gridX: number; gridY: number }> = [];
const overflow: string[] = [];
for (const item of items) {
const fp = getVehicleFootprint(item.template, item.rotated);
const spot = findGarageEmptySpot(placed, fp.width, fp.height, bayWidth, bayHeight);
if (spot) {
const moved = { ...item, gridX: spot.x, gridY: spot.y };
placed.push(moved);
result.push({ id: item.id, gridX: spot.x, gridY: spot.y });
} else {
overflow.push(item.id);
}
}
return { placed: result, overflow };
}
/**
* Get the number of bay cells occupied vs total.
*/
export function getGarageGridOccupancy(
items: GarageGridItem[],
bayWidth: number,
bayHeight: number,
): { used: number; total: number } {
const occupied = new Set<string>();
for (const item of items) {
const fp = getVehicleFootprint(item.template, item.rotated);
const cells = getGarageOccupiedCells(item.gridX, item.gridY, fp.width, fp.height);
for (const c of cells) occupied.add(c);
}
return { used: occupied.size, total: bayWidth * bayHeight };
}
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Convert populated game-vehicles rows into grid items, keeping only the
* instances actually parked on bay cells (garageGridX/garageGridY set) whose
* template is populated.
*/
export function parkedVehiclesToGridItems(
vehicles: Array<GameVehicle & { type?: Vehicle | number | null }>,
): GarageGridItem[] {
const items: GarageGridItem[] = [];
for (const vehicle of vehicles) {
if (vehicle.garageGridX == null || vehicle.garageGridY == null) continue;
const template = typeof vehicle.type === "object" ? vehicle.type : null;
if (!template) continue;
items.push({
id: String(vehicle.id),
vehicleId: vehicle.id,
gridX: vehicle.garageGridX,
gridY: vehicle.garageGridY,
rotated: vehicle.garageRotated ?? false,
template,
});
}
return items;
}
/** Instance ref used on the bridge wire: `garage:<storageSlug>` (A1). */
export function formatGarageInstanceRef(slug: string): string {
return `garage:${slug}`;
}
/** Parse a `garage:<storageSlug>` instance ref; null when malformed. */
export function parseGarageInstanceRef(value: unknown): { slug: string } | null {
if (typeof value !== "string") return null;
const separator = value.indexOf(":");
if (separator <= 0) return null;
if (value.slice(0, separator) !== "garage") return null;
const slug = value.slice(separator + 1);
if (!/^[a-z0-9][a-z0-9-_]{1,63}$/.test(slug)) return null;
return { slug };
}
/** Numeric id of a possibly-populated relationship, or null. */
export function garageRelId(value: unknown): number | null {
return relId(value);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,27 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_vehicles" ADD COLUMN "garage_grid_x" numeric;
ALTER TABLE "game_vehicles" ADD COLUMN "garage_grid_y" numeric;
ALTER TABLE "game_vehicles" ADD COLUMN "garage_rotated" boolean DEFAULT false;
ALTER TABLE "game_vehicles" ADD COLUMN "bridge_uid" varchar;
ALTER TABLE "vehicles" ADD COLUMN "garage_width" numeric;
ALTER TABLE "vehicles" ADD COLUMN "garage_height" numeric;
ALTER TABLE "structures" ADD COLUMN "vehicle_bay_x_size" numeric;
ALTER TABLE "structures" ADD COLUMN "vehicle_bay_y_size" numeric;
CREATE UNIQUE INDEX "game_vehicles_bridge_uid_idx" ON "game_vehicles" USING btree ("bridge_uid");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "game_vehicles_bridge_uid_idx";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_grid_x";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_grid_y";
ALTER TABLE "game_vehicles" DROP COLUMN "garage_rotated";
ALTER TABLE "game_vehicles" DROP COLUMN "bridge_uid";
ALTER TABLE "vehicles" DROP COLUMN "garage_width";
ALTER TABLE "vehicles" DROP COLUMN "garage_height";
ALTER TABLE "structures" DROP COLUMN "vehicle_bay_x_size";
ALTER TABLE "structures" DROP COLUMN "vehicle_bay_y_size";`)
}

View file

@ -133,6 +133,7 @@ import * as migration_20261012_181310_add_journals_collection from './20261012_1
import * as migration_20261012_182016_add_journals_event_target from './20261012_182016_add_journals_event_target';
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
export const migrations = [
{
@ -808,6 +809,11 @@ export const migrations = [
{
up: migration_20261013_183041_add_journal_contribution_type.up,
down: migration_20261013_183041_add_journal_contribution_type.down,
name: '20261013_183041_add_journal_contribution_type'
name: '20261013_183041_add_journal_contribution_type',
},
{
up: migration_20261013_184745_add_garage_fields.up,
down: migration_20261013_184745_add_garage_fields.down,
name: '20261013_184745_add_garage_fields'
},
];

View file

@ -1542,6 +1542,13 @@ export interface Structure {
restrictToAllowed?: boolean | null;
xSize?: number | null;
ySize?: number | null;
/**
* 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.
*/
vehicleBay?: {
xSize?: number | null;
ySize?: number | null;
};
allowedStorage?:
| {
item?:
@ -2134,6 +2141,8 @@ export interface Vehicle {
transportMode: 'ground' | 'air' | 'sea';
width?: number | null;
height?: number | null;
garageWidth?: number | null;
garageHeight?: number | null;
maxMass?: number | null;
/**
* The number of ACE cargo slots this vehicle has by default.
@ -2413,6 +2422,22 @@ export interface GameVehicle {
* The structure where this vehicle is currently stationed. Null if in transit.
*/
deployedAt?: (number | null) | GameStructure;
/**
* Column position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.
*/
garageGridX?: number | null;
/**
* Row position in the deployed structure's Garage vehicle bay (0-indexed). Null = not parked in a bay cell.
*/
garageGridY?: number | null;
/**
* Whether this vehicle is rotated 90 degrees in the garage bay (swaps width and height).
*/
garageRotated?: boolean | null;
/**
* Per-instance identity assigned by the Arma bridge (docs/arma-bridge/garage-sync.md). Two identical vehicles are told apart by this tag. Null = never seen by the game.
*/
bridgeUid?: string | null;
/**
* The faction that owns this vehicle.
*/
@ -8790,6 +8815,10 @@ export interface GameVehiclesSelect<T extends boolean = true> {
name?: T;
type?: T;
deployedAt?: T;
garageGridX?: T;
garageGridY?: T;
garageRotated?: T;
bridgeUid?: T;
faction?: T;
status?: T;
currentFuel?: T;
@ -9928,6 +9957,8 @@ export interface VehiclesSelect<T extends boolean = true> {
transportMode?: T;
width?: T;
height?: T;
garageWidth?: T;
garageHeight?: T;
maxMass?: T;
aceCargoSlots?: T;
allowedVirtualCargo?:
@ -10081,6 +10112,12 @@ export interface StructuresSelect<T extends boolean = true> {
restrictToAllowed?: T;
xSize?: T;
ySize?: T;
vehicleBay?:
| T
| {
xSize?: T;
ySize?: T;
};
allowedStorage?:
| T
| {

View file

@ -0,0 +1,181 @@
#!/usr/bin/env bun
/**
* backfillGaragePlacement.ts - seed garage bay placement for existing vehicles.
*
* Row-major auto-places existing IDLE game-vehicles whose deployedAt structure
* has a vehicle bay (blueprint vehicleBay.xSize/ySize > 0) into free bay cells.
* Anything that does not fit stays unplaced (null cells) and shows up in the
* Garage "Elsewhere" section. Mirrors the locker sync auto-placement posture:
* never moves vehicles that already have a cell, never touches non-idle or
* non-garaged vehicles.
*
* Usage (targets the DATABASE_URI from .env, same as other local tooling):
* bun run garage:backfill --dry-run # report only, no writes
* bun run garage:backfill # apply
*/
import { getPayload } from "payload";
import type { Payload } from "payload";
import type { GameStructure, GameVehicle, Structure } from "@/payload-types";
import {
getGarageBayDimensions,
getVehicleFootprint,
isGaragePlacementValid,
type GarageGridItem,
} from "@/lib/garage";
const DRY_RUN = process.argv.includes("--dry-run") || process.argv.includes("-n");
function log(msg: string) {
console.log(`[garage-backfill] ${msg}`);
}
async function main() {
const payloadConfig = await (await import("@payload-config")).default;
const payload: Payload = await getPayload({ config: payloadConfig });
// Structures whose blueprint exposes a vehicle bay.
const { docs: blueprints } = await payload.find({
collection: "structures",
depth: 0,
limit: 1000,
overrideAccess: true,
});
const bayBlueprintIds = new Map<number, { width: number; height: number }>();
for (const bp of blueprints as Structure[]) {
const bay = getGarageBayDimensions(bp);
if (bay) bayBlueprintIds.set(bp.id, bay);
}
if (bayBlueprintIds.size === 0) {
log("No structure blueprints define a vehicle bay. Nothing to do.");
return;
}
const { docs: structures } = await payload.find({
collection: "game-structures",
depth: 0,
limit: 1000,
overrideAccess: true,
where: {
type: { in: Array.from(bayBlueprintIds.keys()) },
},
});
if (structures.length === 0) {
log("No built structures use a blueprint with a vehicle bay. Nothing to do.");
return;
}
let totalPlaced = 0;
let totalOverflow = 0;
for (const structure of structures as GameStructure[]) {
const bay = bayBlueprintIds.get(
typeof structure.type === "object" ? (structure.type as Structure).id : (structure.type as number),
);
if (!bay) continue;
const { docs: vehicles } = await payload.find({
collection: "game-vehicles",
depth: 1, // populate type (template) for footprints
limit: 1000,
overrideAccess: true,
where: { deployedAt: { equals: structure.id } },
});
const rows = vehicles as Array<GameVehicle & { type?: unknown }>;
// Occupancy from vehicles already parked on cells (never moved).
const occupied: GarageGridItem[] = [];
for (const v of rows) {
if (v.garageGridX == null || v.garageGridY == null) continue;
const template = typeof v.type === "object" ? (v.type as never) : null;
if (!template) continue;
occupied.push({
id: String(v.id),
vehicleId: v.id,
gridX: v.garageGridX,
gridY: v.garageGridY,
rotated: v.garageRotated ?? false,
template,
});
}
// Idle, unplaced candidates, in stable order.
const candidates = rows.filter(
(v) => v.status === "idle" && v.garageGridX == null && v.garageGridY == null,
);
if (candidates.length === 0) continue;
const placements: Array<{ id: number; gridX: number; gridY: number }> = [];
const working = [...occupied];
let overflow = 0;
for (const candidate of candidates) {
const template = typeof candidate.type === "object" ? (candidate.type as never) : null;
if (!template) {
overflow += 1;
continue;
}
const fp = getVehicleFootprint(template as never, false);
let spot: { x: number; y: number } | null = null;
outer: for (let y = 0; y <= bay.height - fp.height; y++) {
for (let x = 0; x <= bay.width - fp.width; x++) {
if (
isGaragePlacementValid(working, null, x, y, fp.width, fp.height, bay.width, bay.height)
) {
spot = { x, y };
break outer;
}
}
}
if (!spot) {
overflow += 1;
continue;
}
working.push({
id: String(candidate.id),
vehicleId: candidate.id,
gridX: spot.x,
gridY: spot.y,
rotated: false,
template: template as never,
});
placements.push({ id: candidate.id, gridX: spot.x, gridY: spot.y });
}
if (placements.length > 0 || overflow > 0) {
log(
`Structure "${structure.name}" (bay ${bay.width}x${bay.height}): ` +
`${placements.length} to place, ${overflow} overflow (stays unplaced).`,
);
}
for (const p of placements) {
if (DRY_RUN) {
log(` dry-run: vehicle ${p.id} -> cell (${p.gridX}, ${p.gridY})`);
} else {
await payload.update({
collection: "game-vehicles",
id: p.id,
data: { garageGridX: p.gridX, garageGridY: p.gridY, garageRotated: false },
overrideAccess: true,
depth: 0,
});
}
}
totalPlaced += placements.length;
totalOverflow += overflow;
}
log(
`${DRY_RUN ? "Dry run complete. Would place" : "Placed"} ${totalPlaced} vehicle(s); ` +
`${totalOverflow} left unplaced (Elsewhere).`,
);
}
main()
.then(() => process.exit(0))
.catch((err) => {
console.error("[garage-backfill] Failed:", err);
process.exit(1);
});

View file

@ -245,6 +245,13 @@ export const EventTypes = {
ProductionToggled: "production:toggled",
StructureModuleInstall: "structure:module-install",
StructureModuleUninstall: "structure:module-uninstall",
// Garage (vehicle bay grid)
GarageMove: "garage:move",
GarageRotate: "garage:rotate",
GarageAutoArrange: "garage:auto-arrange",
GarageDispatch: "garage:dispatch",
GarageStore: "garage:store",
} as const;
export type EventType = (typeof EventTypes)[keyof typeof EventTypes];