From 12cb62b487f6b59ddf660ac4a0263b1dd69b114a Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Mon, 5 Oct 2026 03:17:52 -0400 Subject: [PATCH] feat(map): add Arma-style coordinate grid config, overlay and mission-map wiring Per-map grid config (gridEnabled, easting/northing origin, spacing, label digits, over-lines) rides on the Maps collection and surfaces via /api/map-features. Pure math in src/lib/map/grid.ts mirrors CfgWorlds Grid (floor truncation, mod-10^digits wrapping, nested levels). GridLayer renders hairlines + edge labels on the world map and mission planning maps, and armaGridRef now delegates to gridRef. Migration 20261005_001212_add_map_grid_config. --- AGENTS.md | 1 + src/app/(frontend)/styles.css | 27 + src/app/api/map-features/route.ts | 2 + src/collections/world/Maps.ts | 100 + .../missionMap/MissionMapCanvas.tsx | 16 +- .../missionMap/MissionPlanningMap.tsx | 25 +- src/components/frontend/map/GridLayer.tsx | 208 + src/components/frontend/map/MapClient.tsx | 28 +- src/lib/arma-markers/missionMarkers.ts | 13 +- src/lib/map/grid.ts | 273 + src/lib/map/types.ts | 2 + .../20261005_001212_add_map_grid_config.json | 36325 ++++++++++++++++ .../20261005_001212_add_map_grid_config.ts | 35 + tests/int/map-grid.int.spec.ts | 260 + 14 files changed, 37298 insertions(+), 17 deletions(-) create mode 100644 src/components/frontend/map/GridLayer.tsx create mode 100644 src/lib/map/grid.ts create mode 100644 src/migrations/20261005_001212_add_map_grid_config.json create mode 100644 src/migrations/20261005_001212_add_map_grid_config.ts create mode 100644 tests/int/map-grid.int.spec.ts diff --git a/AGENTS.md b/AGENTS.md index 5940f609..fd04080c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -211,6 +211,7 @@ Leaflet world map at `/map` (top-level sidebar entry, whole unit views it). Full - **Construction**: `src/lib/map/construction.ts`. Construction runs on timestamps: `maybeStartConstruction(payload, siteId, now)` is called at delivery time (shipment `completeShipment`, the structures `addResource`/`transferResource` actions via `addResourceInternal`, and `placeStructure` for materialless blueprints) and, when every blueprint material is stored, consumes them via `consumeStorage`, sets `constructionStartedAt`/`constructionCompletesAt` from the blueprint's `constructionDurationMinutes` (minutes, replacing the old tick-based `constructionTime`), and flips `awaiting_materials` to `building`. The game tick's `processConstructionTick` is a sweeper only: building sites past `constructionCompletesAt` flip to `complete` + `structure:construction-complete` (idempotent). Crew speed (slice 2): blueprint `constructionCrewRequired` gates start (`no_crew` with no labor) and scales duration by staffed fraction (floor 0.25); labor-classifications `buildEfficiency` weights each worker; `setLaborHeadcount` re-prices the remaining work via `applyCrewRateChange` (`src/lib/base/constructionSpeed.ts`). Default constructionStatus on game-structures is `complete` (backward compat). ConstructionPanel on the structure detail page shows required vs delivered + a timestamp-derived progress bar; map markers interpolate progress from the timestamps. - **UI**: `/map` is a **picker screen** (grid of eligible map cards with basemap thumbnails, linking to `/map/[id]`); the map view itself is `/map/[id]` (`MapLoader` ssr:false + `src/components/frontend/map/MapClient.tsx`, single-map props, no switcher). CRS.Simple with y-flip (latlng = [-y, x]), image (ImageOverlay) or XYZ (TileLayer) basemap, layer toggles (structures/nodes/roads/zones/shipments/ranges), structure markers as status-colored pins (emerald building icon = operational, blue hammer = building, amber package = awaiting materials, with a progress bar under construction sites), popovers linking to `/logistics/structures/[id]`, shipment markers interpolated along `routePath` from `dispatchedAt`/`estimatedArrival`, refreshed by `useGameTick`. Feature data served by `GET /api/map-features?mapId=` (view surface, logged-in). Map labels: zone names render at the polygon centroid, road names render as curved SVG textPath labels following a Catmull-Rom smoothed road line every 400 screen px (max 12/road, flipped to a reversed path when the direction would render upside down or straight down, so vertical labels read bottom-to-top; dark casing stroke for contrast), structure names render as persistent labels with cluster priority (`labelVisible` + `labelPriority` on game-structures; winner = highest `labelPriority`, then stored mass, then id; cluster radius 56 screen px, so zooming in reveals suppressed labels). Road/zone stroke + fill colors, widths, dash styles, and opacities are editable in the authoring toolbar (`strokeColor`/`strokeWeight`/`strokeStyle` on roads; `fillColor`/`strokeColor`/`fillOpacity`/`strokeWeight` on zones; hex validated by `validateHexColor` in `src/lib/map/style.ts`, empty = per-type defaults). Pure label/styling math lives in `src/lib/map/style.ts` (`metersPerPx`, `roadLabelPoints`, `polygonCentroid`, `dashArrayFor`, `roadLabelShown`, `labelScreenAngle`; roads under 600 screen px render one straight midpoint label instead of curved text, since glyphs fold on tiny wiggly paths). - **Authoring**: edit mode on `/map` (maps:*-gated) draws roads/zones/nodes, edits existing features (popup Edit loads geometry + attributes into the authoring toolbar; Save passes the feature id and requires `maps:update`), and deletes features (server actions in the same actions.ts). Drafts get vertex editing: draggable square handles per draft vertex (drag-end snaps), right-click deletes (min 2 road / 3 zone points), cyan midpoint handles insert a vertex; clicks and drags snap within 12 screen px to feature vertices and zone/road edges (closing segments included; vertices beat edges unless the edge is 2x closer) via pure `src/lib/map/snapping.ts` (`findSnap`, `closestPointOnSegment`, `segmentMidpoints`; `AuthoringSnapLayer` + `DraftHandles` in MapClient). `POST /api/map-import` imports a GeoJSON FeatureCollection (LineString to roads, Polygon to zones, Point to nodes; [x, y] positions used directly as map meters). Mapping table in `docs/map-system.md`. +- **Coordinate grid**: per-map Arma-style grid config on the Maps collection ("Coordinate Grid" group, admin panel): `gridEnabled` master switch, `gridOriginEasting`/`gridOriginNorthing` (meters from the west/south edges to the grid zero line; vanilla terrains use 0), `gridStartEasting`/`gridStartNorthing` (label numbers on the zero line), `gridSpacingMeters` (base cell, default 1000), `gridLabelDigits` (default 2), `gridNumbersOverLines` (Tanoa style: labels on lines instead of cell-centered). Pure math in `src/lib/map/grid.ts` (`gridConfigFromMapDoc`, `gridLevelFor` (power-of-ten ladder, 10x subdivision at close zoom: 1 km/2-digit -> 100 m/3 -> 10 m/4, chosen by on-screen cell size via `GRID_MIN_CELL_PX`), `gridLinesForBounds` (viewport lines + labels in map meters), `gridRef` (6/8-digit references)). Semantics mirror CfgWorlds Grid: floor truncation, labels wrap mod 10^digits with leading zeros (negatives wrap too), levels nest exactly (1 km cell "10" contains 100 m lines "100".."109"). `armaGridRef` (missionMarkers.ts) is a thin wrapper over `gridRef` with `DEFAULT_MAP_GRID`, which reproduces the legacy output. The config rides `MapConfig.grid` from `/api/map-features`; `GridLayer.tsx` (`src/components/frontend/map/`) renders hairlines + edge labels on the world map (Map Control "Grid" toggle) and mission planning maps (header "Grid" switch); both cursor readouts show the configured reference. Migration `20261005_001212_add_map_grid_config` (hand-trimmed; the .json snapshot intentionally covers the full current schema to repair missing sidecars on the three prior hand-written migrations). - **GameRules**: `proximityThreshold` now means meters (default 1000; migration backfilled rows still at the old default 10). Both call sites (shipments/actions.ts, structures/actions.ts transferResource) use meters. - **Tests**: `tests/int/map-system.int.spec.ts` (routing graph/snap/refusals, cross-map refusal, ground route + path snapshot, air straight-line, proximity, terrain/range validation, placeStructure happy/water/range cases, construction tick lifecycle, permission gating, label/styling helpers + save-action styling validation). Gotcha: Payload applies select `filterOptions` server-side, so test fixtures must use `approvalStatus: "in_progress"`. diff --git a/src/app/(frontend)/styles.css b/src/app/(frontend)/styles.css index 4809c711..dba99a23 100644 --- a/src/app/(frontend)/styles.css +++ b/src/app/(frontend)/styles.css @@ -3604,6 +3604,33 @@ pointer-events: none; } +.map-grid-label-icon { + background: transparent; + border: none; +} + +.map-grid-label { + color: rgb(255 255 255 / 85%); + font-family: + ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", + monospace; + font-size: 10px; + letter-spacing: 0.05em; + white-space: nowrap; + /* Size to the text itself: inside the 0x0 divIcon container a block div + resolves to 0 width, which makes the percentage anchoring transform a + no-op and leaves the label hanging off the edge. */ + width: max-content; + text-shadow: + 0 0 3px rgb(0 0 0 / 90%), + 0 0 1px rgb(0 0 0 / 90%); + pointer-events: none; +} + +.leaflet-container .map-grid-label-icon { + pointer-events: none; +} + /* Radix floating panels (Select/DropdownMenu/Popover/Tooltip) portal to and would otherwise paint below the map page's high-z overlays (authoring toolbar z-[1000], structure drawer z-[1200]). Pin every popper wrapper above diff --git a/src/app/api/map-features/route.ts b/src/app/api/map-features/route.ts index 170049ca..77ca668b 100644 --- a/src/app/api/map-features/route.ts +++ b/src/app/api/map-features/route.ts @@ -9,6 +9,7 @@ import { isOperationalMember, } from "@/lib/map/compounds"; import { isPointArray, type MapPoint } from "@/lib/map/points"; +import { gridConfigFromMapDoc } from "@/lib/map/grid"; import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types"; export const dynamic = "force-dynamic"; @@ -288,6 +289,7 @@ export async function GET(req: NextRequest) { maxZoom: mapDoc.maxZoom ?? 12, defaultZoom: mapDoc.defaultZoom ?? 2, defaultCenter: [mapDoc.defaultCenterX ?? worldW / 2, mapDoc.defaultCenterY ?? worldH / 2], + grid: gridConfigFromMapDoc(mapDoc as unknown as Record), }, structures, nodes, diff --git a/src/collections/world/Maps.ts b/src/collections/world/Maps.ts index a2830fdc..716ccf8d 100644 --- a/src/collections/world/Maps.ts +++ b/src/collections/world/Maps.ts @@ -208,5 +208,105 @@ export const Maps: CollectionConfig = { }, ], }, + { + label: "Coordinate Grid", + type: "group", + admin: { + description: + "Arma-style coordinate grid overlay + grid references. Set up to match the terrain's in-game grid (CfgWorlds Grid class).", + }, + fields: [ + { + name: "gridEnabled", + type: "checkbox", + label: "Enable Grid", + defaultValue: false, + admin: { + description: + "Show a coordinate grid on the world map and mission planning maps, and use it for grid reference readouts.", + }, + }, + { + name: "gridOriginEasting", + type: "number", + label: "Origin Easting (m)", + defaultValue: 0, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Meters from the west edge (in-game X) to the grid's zero line. Vanilla terrains use 0 (zero line on the west edge).", + }, + }, + { + name: "gridOriginNorthing", + type: "number", + label: "Origin Northing (m)", + defaultValue: 0, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Meters from the south edge (in-game Y) to the grid's zero line. Vanilla terrains use 0 (zero line on the south edge).", + }, + }, + { + name: "gridStartEasting", + type: "number", + label: "Starting Easting Number", + defaultValue: 0, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Number shown on the first easting line (at the origin). Applies at the base spacing and finer subdivisions.", + }, + }, + { + name: "gridStartNorthing", + type: "number", + label: "Starting Northing Number", + defaultValue: 0, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Number shown on the first northing line (at the origin). Applies at the base spacing and finer subdivisions.", + }, + }, + { + name: "gridSpacingMeters", + type: "number", + label: "Cell Spacing (m)", + defaultValue: 1000, + min: 1, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Base grid cell size in meters. The map subdivides 10x automatically as you zoom in, like the in-game map.", + }, + }, + { + name: "gridLabelDigits", + type: "number", + label: "Label Digits", + defaultValue: 2, + min: 1, + max: 6, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Digits shown per axis at the base spacing (Arma shows 2 at 1 km, 3 at 100 m). Numbers wrap at the digit width.", + }, + }, + { + name: "gridNumbersOverLines", + type: "checkbox", + label: "Numbers Over Lines", + defaultValue: false, + admin: { + condition: (_data, siblingData) => siblingData?.gridEnabled === true, + description: + "Draw labels on the grid lines instead of centered in the cells (Tanoa style).", + }, + }, + ], + }, ], }; diff --git a/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx b/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx index 0bb73be1..8fe4c0be 100644 --- a/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx +++ b/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx @@ -18,6 +18,8 @@ import { import type { MapPoint } from "@/lib/map/points"; import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style"; import type { MapFeaturesResponse } from "@/lib/map/types"; +import type { MapGridConfig } from "@/lib/map/grid"; +import { GridLayer } from "@/components/frontend/map/GridLayer"; import { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers"; import { areaOutline, @@ -38,12 +40,18 @@ export interface MissionMapCanvasProps { canEdit: boolean; showRoads: boolean; showZones: boolean; + showGrid: boolean; onSelect: (id: number | null) => void; onCreate: (data: MissionMarkerData) => void; /** persist=false for live drag previews, true on drag end. */ onChange: (marker: MissionMarker, persist: boolean) => void; onCursor: (point: MapPoint | null) => void; - onLoaded: (info: { worldWidth: number; worldHeight: number; hasBasemap: boolean }) => void; + onLoaded: (info: { + worldWidth: number; + worldHeight: number; + hasBasemap: boolean; + grid: MapGridConfig; + }) => void; } const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]]; @@ -520,6 +528,7 @@ export function MissionMapCanvas({ canEdit, showRoads, showZones, + showGrid, onSelect, onCreate, onChange, @@ -550,6 +559,7 @@ export function MissionMapCanvas({ (body.map.basemapMode === "image" && body.map.basemapImageUrl) || (body.map.basemapMode === "tiles" && body.map.tileUrlTemplate), ), + grid: body.map.grid, }); }) .catch((e: unknown) => { @@ -669,6 +679,10 @@ export function MissionMapCanvas({ (mapConfig.basemapMode === "tiles" && mapConfig.tileUrlTemplate) ) && } + {mapConfig?.grid.enabled && showGrid && ( + + )} + {showZones && zonePolys.map(({ zone, positions, options }) => ( diff --git a/src/components/frontend/intelligence/missionMap/MissionPlanningMap.tsx b/src/components/frontend/intelligence/missionMap/MissionPlanningMap.tsx index 4e71b479..30b6982d 100644 --- a/src/components/frontend/intelligence/missionMap/MissionPlanningMap.tsx +++ b/src/components/frontend/intelligence/missionMap/MissionPlanningMap.tsx @@ -24,12 +24,12 @@ import { DEFAULT_MARKER_TYPE, } from "@/lib/arma-markers"; import { - armaGridRef, markersToSqf, normalizeMarkerInput, type MissionMarker, type MissionMarkerData, } from "@/lib/arma-markers/missionMarkers"; +import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid"; import type { MapPoint } from "@/lib/map/points"; import { clearMissionMapMarkers, @@ -112,7 +112,9 @@ export function MissionPlanningMap({ const [cursor, setCursor] = useState(null); const [showRoads, setShowRoads] = useState(true); const [showZones, setShowZones] = useState(true); + const [showGrid, setShowGrid] = useState(true); const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight }); + const [gridConfig, setGridConfig] = useState(DEFAULT_MAP_GRID); const [toggling, setToggling] = useState(false); const timers = useRef(new Map>()); @@ -278,8 +280,10 @@ export function MissionPlanningMap({ }, [enabled, canEdit, selectedId, tool, handleDelete]); const handleLoaded = useCallback( - (info: { worldWidth: number; worldHeight: number }) => - setWorld({ width: info.worldWidth, height: info.worldHeight }), + (info: { worldWidth: number; worldHeight: number; grid: MapGridConfig }) => { + setWorld({ width: info.worldWidth, height: info.worldHeight }); + setGridConfig(info.grid); + }, [], ); @@ -362,6 +366,15 @@ export function MissionPlanningMap({ Planning map // {missionLabel}
+