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.
This commit is contained in:
parent
84939cc839
commit
12cb62b487
14 changed files with 37298 additions and 17 deletions
|
|
@ -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.
|
- **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).
|
- **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`.
|
- **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.
|
- **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"`.
|
- **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"`.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3604,6 +3604,33 @@
|
||||||
pointer-events: none;
|
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 <body>
|
/* Radix floating panels (Select/DropdownMenu/Popover/Tooltip) portal to <body>
|
||||||
and would otherwise paint below the map page's high-z overlays (authoring
|
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
|
toolbar z-[1000], structure drawer z-[1200]). Pin every popper wrapper above
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import {
|
||||||
isOperationalMember,
|
isOperationalMember,
|
||||||
} from "@/lib/map/compounds";
|
} from "@/lib/map/compounds";
|
||||||
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
||||||
|
import { gridConfigFromMapDoc } from "@/lib/map/grid";
|
||||||
import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types";
|
import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
|
|
@ -288,6 +289,7 @@ export async function GET(req: NextRequest) {
|
||||||
maxZoom: mapDoc.maxZoom ?? 12,
|
maxZoom: mapDoc.maxZoom ?? 12,
|
||||||
defaultZoom: mapDoc.defaultZoom ?? 2,
|
defaultZoom: mapDoc.defaultZoom ?? 2,
|
||||||
defaultCenter: [mapDoc.defaultCenterX ?? worldW / 2, mapDoc.defaultCenterY ?? worldH / 2],
|
defaultCenter: [mapDoc.defaultCenterX ?? worldW / 2, mapDoc.defaultCenterY ?? worldH / 2],
|
||||||
|
grid: gridConfigFromMapDoc(mapDoc as unknown as Record<string, unknown>),
|
||||||
},
|
},
|
||||||
structures,
|
structures,
|
||||||
nodes,
|
nodes,
|
||||||
|
|
|
||||||
|
|
@ -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).",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,8 @@ import {
|
||||||
import type { MapPoint } from "@/lib/map/points";
|
import type { MapPoint } from "@/lib/map/points";
|
||||||
import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style";
|
import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style";
|
||||||
import type { MapFeaturesResponse } from "@/lib/map/types";
|
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 { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers";
|
||||||
import {
|
import {
|
||||||
areaOutline,
|
areaOutline,
|
||||||
|
|
@ -38,12 +40,18 @@ export interface MissionMapCanvasProps {
|
||||||
canEdit: boolean;
|
canEdit: boolean;
|
||||||
showRoads: boolean;
|
showRoads: boolean;
|
||||||
showZones: boolean;
|
showZones: boolean;
|
||||||
|
showGrid: boolean;
|
||||||
onSelect: (id: number | null) => void;
|
onSelect: (id: number | null) => void;
|
||||||
onCreate: (data: MissionMarkerData) => void;
|
onCreate: (data: MissionMarkerData) => void;
|
||||||
/** persist=false for live drag previews, true on drag end. */
|
/** persist=false for live drag previews, true on drag end. */
|
||||||
onChange: (marker: MissionMarker, persist: boolean) => void;
|
onChange: (marker: MissionMarker, persist: boolean) => void;
|
||||||
onCursor: (point: MapPoint | null) => 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]];
|
const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]];
|
||||||
|
|
@ -520,6 +528,7 @@ export function MissionMapCanvas({
|
||||||
canEdit,
|
canEdit,
|
||||||
showRoads,
|
showRoads,
|
||||||
showZones,
|
showZones,
|
||||||
|
showGrid,
|
||||||
onSelect,
|
onSelect,
|
||||||
onCreate,
|
onCreate,
|
||||||
onChange,
|
onChange,
|
||||||
|
|
@ -550,6 +559,7 @@ export function MissionMapCanvas({
|
||||||
(body.map.basemapMode === "image" && body.map.basemapImageUrl) ||
|
(body.map.basemapMode === "image" && body.map.basemapImageUrl) ||
|
||||||
(body.map.basemapMode === "tiles" && body.map.tileUrlTemplate),
|
(body.map.basemapMode === "tiles" && body.map.tileUrlTemplate),
|
||||||
),
|
),
|
||||||
|
grid: body.map.grid,
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch((e: unknown) => {
|
.catch((e: unknown) => {
|
||||||
|
|
@ -669,6 +679,10 @@ export function MissionMapCanvas({
|
||||||
(mapConfig.basemapMode === "tiles" && mapConfig.tileUrlTemplate)
|
(mapConfig.basemapMode === "tiles" && mapConfig.tileUrlTemplate)
|
||||||
) && <Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK} interactive={false} />}
|
) && <Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK} interactive={false} />}
|
||||||
|
|
||||||
|
{mapConfig?.grid.enabled && showGrid && (
|
||||||
|
<GridLayer config={mapConfig.grid} worldWidth={worldW} worldHeight={worldH} />
|
||||||
|
)}
|
||||||
|
|
||||||
{showZones &&
|
{showZones &&
|
||||||
zonePolys.map(({ zone, positions, options }) => (
|
zonePolys.map(({ zone, positions, options }) => (
|
||||||
<Polygon key={`zone-${zone.id}`} positions={positions} pathOptions={options} />
|
<Polygon key={`zone-${zone.id}`} positions={positions} pathOptions={options} />
|
||||||
|
|
|
||||||
|
|
@ -24,12 +24,12 @@ import {
|
||||||
DEFAULT_MARKER_TYPE,
|
DEFAULT_MARKER_TYPE,
|
||||||
} from "@/lib/arma-markers";
|
} from "@/lib/arma-markers";
|
||||||
import {
|
import {
|
||||||
armaGridRef,
|
|
||||||
markersToSqf,
|
markersToSqf,
|
||||||
normalizeMarkerInput,
|
normalizeMarkerInput,
|
||||||
type MissionMarker,
|
type MissionMarker,
|
||||||
type MissionMarkerData,
|
type MissionMarkerData,
|
||||||
} from "@/lib/arma-markers/missionMarkers";
|
} from "@/lib/arma-markers/missionMarkers";
|
||||||
|
import { DEFAULT_MAP_GRID, gridRef, type MapGridConfig } from "@/lib/map/grid";
|
||||||
import type { MapPoint } from "@/lib/map/points";
|
import type { MapPoint } from "@/lib/map/points";
|
||||||
import {
|
import {
|
||||||
clearMissionMapMarkers,
|
clearMissionMapMarkers,
|
||||||
|
|
@ -112,7 +112,9 @@ export function MissionPlanningMap({
|
||||||
const [cursor, setCursor] = useState<MapPoint | null>(null);
|
const [cursor, setCursor] = useState<MapPoint | null>(null);
|
||||||
const [showRoads, setShowRoads] = useState(true);
|
const [showRoads, setShowRoads] = useState(true);
|
||||||
const [showZones, setShowZones] = useState(true);
|
const [showZones, setShowZones] = useState(true);
|
||||||
|
const [showGrid, setShowGrid] = useState(true);
|
||||||
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
|
const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight });
|
||||||
|
const [gridConfig, setGridConfig] = useState<MapGridConfig>(DEFAULT_MAP_GRID);
|
||||||
const [toggling, setToggling] = useState(false);
|
const [toggling, setToggling] = useState(false);
|
||||||
|
|
||||||
const timers = useRef(new Map<number, ReturnType<typeof setTimeout>>());
|
const timers = useRef(new Map<number, ReturnType<typeof setTimeout>>());
|
||||||
|
|
@ -278,8 +280,10 @@ export function MissionPlanningMap({
|
||||||
}, [enabled, canEdit, selectedId, tool, handleDelete]);
|
}, [enabled, canEdit, selectedId, tool, handleDelete]);
|
||||||
|
|
||||||
const handleLoaded = useCallback(
|
const handleLoaded = useCallback(
|
||||||
(info: { worldWidth: number; worldHeight: number }) =>
|
(info: { worldWidth: number; worldHeight: number; grid: MapGridConfig }) => {
|
||||||
setWorld({ width: info.worldWidth, height: info.worldHeight }),
|
setWorld({ width: info.worldWidth, height: info.worldHeight });
|
||||||
|
setGridConfig(info.grid);
|
||||||
|
},
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -362,6 +366,15 @@ export function MissionPlanningMap({
|
||||||
Planning map // {missionLabel}
|
Planning map // {missionLabel}
|
||||||
</span>
|
</span>
|
||||||
<div className="flex shrink-0 items-center gap-3">
|
<div className="flex shrink-0 items-center gap-3">
|
||||||
|
<label className="flex items-center gap-1.5">
|
||||||
|
<Switch size="sm" checked={showGrid} onCheckedChange={setShowGrid} id="plan-grid" />
|
||||||
|
<Label
|
||||||
|
htmlFor="plan-grid"
|
||||||
|
className="font-mono text-[9px] uppercase tracking-widest text-white/60"
|
||||||
|
>
|
||||||
|
Grid
|
||||||
|
</Label>
|
||||||
|
</label>
|
||||||
<label className="flex items-center gap-1.5">
|
<label className="flex items-center gap-1.5">
|
||||||
<Switch size="sm" checked={showRoads} onCheckedChange={setShowRoads} id="plan-roads" />
|
<Switch size="sm" checked={showRoads} onCheckedChange={setShowRoads} id="plan-roads" />
|
||||||
<Label
|
<Label
|
||||||
|
|
@ -401,6 +414,7 @@ export function MissionPlanningMap({
|
||||||
canEdit={canEdit}
|
canEdit={canEdit}
|
||||||
showRoads={showRoads}
|
showRoads={showRoads}
|
||||||
showZones={showZones}
|
showZones={showZones}
|
||||||
|
showGrid={showGrid}
|
||||||
onSelect={setSelectedId}
|
onSelect={setSelectedId}
|
||||||
onCreate={(data) => void handleCreate(data)}
|
onCreate={(data) => void handleCreate(data)}
|
||||||
onChange={handleChange}
|
onChange={handleChange}
|
||||||
|
|
@ -469,7 +483,10 @@ export function MissionPlanningMap({
|
||||||
<ReadoutCell value={String(counts.icons)} label="Icons" />
|
<ReadoutCell value={String(counts.icons)} label="Icons" />
|
||||||
<ReadoutCell value={String(counts.areas)} label="Areas" />
|
<ReadoutCell value={String(counts.areas)} label="Areas" />
|
||||||
<ReadoutCell value={String(counts.lines)} label="Lines" />
|
<ReadoutCell value={String(counts.lines)} label="Lines" />
|
||||||
<ReadoutCell value={cursor ? armaGridRef(cursor, world.height) : "--- ---"} label="Grid" />
|
<ReadoutCell
|
||||||
|
value={cursor ? gridRef(cursor, world.height, gridConfig) : "--- ---"}
|
||||||
|
label="Grid"
|
||||||
|
/>
|
||||||
<ReadoutCell
|
<ReadoutCell
|
||||||
value={`${(Math.max(world.width, world.height) / 1000).toFixed(1)} km`}
|
value={`${(Math.max(world.width, world.height) / 1000).toFixed(1)} km`}
|
||||||
label="World"
|
label="World"
|
||||||
|
|
|
||||||
208
src/components/frontend/map/GridLayer.tsx
Normal file
208
src/components/frontend/map/GridLayer.tsx
Normal file
|
|
@ -0,0 +1,208 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import L from "leaflet";
|
||||||
|
import { Fragment, memo, useCallback, useEffect, useState } from "react";
|
||||||
|
import { Marker, Polyline, useMap, useMapEvents } from "react-leaflet";
|
||||||
|
import {
|
||||||
|
gridLinesForBounds,
|
||||||
|
type GridBounds,
|
||||||
|
type MapGridConfig,
|
||||||
|
} from "@/lib/map/grid";
|
||||||
|
import { metersPerPx } from "@/lib/map/style";
|
||||||
|
|
||||||
|
export interface GridLayerProps {
|
||||||
|
config: MapGridConfig;
|
||||||
|
worldWidth: number;
|
||||||
|
worldHeight: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layer styling is hoisted to module constants: react-leaflet re-applies
|
||||||
|
// pathOptions by reference, and a fresh object literal every render forces a
|
||||||
|
// canvas redraw that glitches mid-zoom-animation.
|
||||||
|
const GRID_CASING_PATH_OPTIONS: L.PathOptions = {
|
||||||
|
color: "#0f172a",
|
||||||
|
weight: 3,
|
||||||
|
opacity: 0.35,
|
||||||
|
interactive: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const GRID_HAIRLINE_PATH_OPTIONS: L.PathOptions = {
|
||||||
|
color: "#ffffff",
|
||||||
|
weight: 1,
|
||||||
|
opacity: 0.22,
|
||||||
|
interactive: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Same slack the maps give maxBounds; viewport clamps stay inside it.
|
||||||
|
const BOUNDS_PAD_METERS = 2000;
|
||||||
|
|
||||||
|
type GridLabelAnchor = "top" | "bottom" | "left" | "right";
|
||||||
|
|
||||||
|
// The iconAnchor nudges the 0x0 icon off the viewport edge; the per-kind
|
||||||
|
// transform pins the matching corner of the text to it, so the glyph always
|
||||||
|
// sits just inside the map.
|
||||||
|
const GRID_LABEL_ICON_ANCHORS: Record<GridLabelAnchor, [number, number]> = {
|
||||||
|
top: [0, -2],
|
||||||
|
bottom: [0, 2],
|
||||||
|
left: [-2, 0],
|
||||||
|
right: [2, 0],
|
||||||
|
};
|
||||||
|
|
||||||
|
const GRID_LABEL_TRANSFORMS: Record<GridLabelAnchor, string> = {
|
||||||
|
top: "translate(-50%, 0)",
|
||||||
|
bottom: "translate(-50%, -100%)",
|
||||||
|
left: "translate(0, -50%)",
|
||||||
|
right: "translate(-100%, -50%)",
|
||||||
|
};
|
||||||
|
|
||||||
|
const gridLabelIconCache = new Map<string, L.DivIcon>();
|
||||||
|
|
||||||
|
function gridLabelIcon(value: string, anchor: GridLabelAnchor): L.DivIcon {
|
||||||
|
const key = `${value}:${anchor}`;
|
||||||
|
let icon = gridLabelIconCache.get(key);
|
||||||
|
if (!icon) {
|
||||||
|
icon = L.divIcon({
|
||||||
|
className: "map-grid-label-icon",
|
||||||
|
html: `<div class="map-grid-label" style="transform: ${GRID_LABEL_TRANSFORMS[anchor]}">${value}</div>`,
|
||||||
|
iconSize: [0, 0],
|
||||||
|
iconAnchor: GRID_LABEL_ICON_ANCHORS[anchor],
|
||||||
|
});
|
||||||
|
gridLabelIconCache.set(key, icon);
|
||||||
|
}
|
||||||
|
return icon;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GridLineRender {
|
||||||
|
key: string;
|
||||||
|
positions: [number, number][];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GridLabelRender {
|
||||||
|
key: string;
|
||||||
|
position: [number, number];
|
||||||
|
icon: L.DivIcon;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GridView {
|
||||||
|
verticalLines: GridLineRender[];
|
||||||
|
horizontalLines: GridLineRender[];
|
||||||
|
labels: GridLabelRender[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arma-style coordinate grid: hairlines over a dark casing plus edge labels.
|
||||||
|
* Geometry is recomputed on moveend/zoomend (and once on mount or config
|
||||||
|
* change), never on mousemove, so cursor tracking stays cheap. Line spans
|
||||||
|
* are padded by one cell past the viewport.
|
||||||
|
*/
|
||||||
|
export const GridLayer = memo(function GridLayer({
|
||||||
|
config,
|
||||||
|
worldWidth,
|
||||||
|
worldHeight,
|
||||||
|
}: GridLayerProps) {
|
||||||
|
const map = useMap();
|
||||||
|
const worldSize = Math.max(worldWidth, worldHeight);
|
||||||
|
|
||||||
|
const computeView = useCallback((): GridView => {
|
||||||
|
const raw = map.getBounds();
|
||||||
|
// Viewport bounds in map meters (lng = x, lat = -y), clamped to the
|
||||||
|
// max-bounds slack so a flung viewport stays in a sane range.
|
||||||
|
const clampX = (x: number): number =>
|
||||||
|
Math.min(worldWidth + BOUNDS_PAD_METERS, Math.max(-BOUNDS_PAD_METERS, x));
|
||||||
|
const clampY = (y: number): number =>
|
||||||
|
Math.min(worldHeight + BOUNDS_PAD_METERS, Math.max(-BOUNDS_PAD_METERS, y));
|
||||||
|
const bounds: GridBounds = {
|
||||||
|
minX: clampX(raw.getWest()),
|
||||||
|
maxX: clampX(raw.getEast()),
|
||||||
|
minY: clampY(-raw.getNorth()),
|
||||||
|
maxY: clampY(-raw.getSouth()),
|
||||||
|
};
|
||||||
|
const lineSet = gridLinesForBounds(
|
||||||
|
config,
|
||||||
|
worldHeight,
|
||||||
|
bounds,
|
||||||
|
metersPerPx(map.getZoom(), worldSize),
|
||||||
|
);
|
||||||
|
const pad = lineSet.level.spacing;
|
||||||
|
|
||||||
|
const verticalLines: GridLineRender[] = lineSet.verticalLines.map((x) => ({
|
||||||
|
key: `v-${x}`,
|
||||||
|
positions: [
|
||||||
|
[-(bounds.minY - pad), x],
|
||||||
|
[-(bounds.maxY + pad), x],
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
const horizontalLines: GridLineRender[] = lineSet.horizontalLines.map((y) => ({
|
||||||
|
key: `h-${y}`,
|
||||||
|
positions: [
|
||||||
|
[-y, bounds.minX - pad],
|
||||||
|
[-y, bounds.maxX + pad],
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
const labels: GridLabelRender[] = [
|
||||||
|
...lineSet.eastingLabels.flatMap((label): GridLabelRender[] => [
|
||||||
|
{
|
||||||
|
key: `e-t-${label.at}`,
|
||||||
|
position: [-bounds.minY, label.at],
|
||||||
|
icon: gridLabelIcon(label.value, "top"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: `e-b-${label.at}`,
|
||||||
|
position: [-bounds.maxY, label.at],
|
||||||
|
icon: gridLabelIcon(label.value, "bottom"),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
...lineSet.northingLabels.flatMap((label): GridLabelRender[] => [
|
||||||
|
{
|
||||||
|
key: `n-l-${label.at}`,
|
||||||
|
position: [-label.at, bounds.minX],
|
||||||
|
icon: gridLabelIcon(label.value, "left"),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: `n-r-${label.at}`,
|
||||||
|
position: [-label.at, bounds.maxX],
|
||||||
|
icon: gridLabelIcon(label.value, "right"),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
return { verticalLines, horizontalLines, labels };
|
||||||
|
}, [map, config, worldWidth, worldHeight, worldSize]);
|
||||||
|
|
||||||
|
const [view, setView] = useState<GridView>(computeView);
|
||||||
|
|
||||||
|
// Recompute on mount and whenever the config (or world) changes; pan/zoom
|
||||||
|
// updates arrive through the map events below.
|
||||||
|
useEffect(() => {
|
||||||
|
setView(computeView());
|
||||||
|
}, [computeView]);
|
||||||
|
|
||||||
|
useMapEvents({
|
||||||
|
moveend: () => setView(computeView()),
|
||||||
|
zoomend: () => setView(computeView()),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{view.verticalLines.map((line) => (
|
||||||
|
<Fragment key={line.key}>
|
||||||
|
<Polyline positions={line.positions} pathOptions={GRID_CASING_PATH_OPTIONS} />
|
||||||
|
<Polyline positions={line.positions} pathOptions={GRID_HAIRLINE_PATH_OPTIONS} />
|
||||||
|
</Fragment>
|
||||||
|
))}
|
||||||
|
{view.horizontalLines.map((line) => (
|
||||||
|
<Fragment key={line.key}>
|
||||||
|
<Polyline positions={line.positions} pathOptions={GRID_CASING_PATH_OPTIONS} />
|
||||||
|
<Polyline positions={line.positions} pathOptions={GRID_HAIRLINE_PATH_OPTIONS} />
|
||||||
|
</Fragment>
|
||||||
|
))}
|
||||||
|
{view.labels.map((label) => (
|
||||||
|
<Marker
|
||||||
|
key={label.key}
|
||||||
|
position={label.position}
|
||||||
|
icon={label.icon}
|
||||||
|
interactive={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
@ -46,6 +46,8 @@ import {
|
||||||
splinePolyline,
|
splinePolyline,
|
||||||
} from "@/lib/map/style";
|
} from "@/lib/map/style";
|
||||||
import type { MapFeaturesResponse, ShipmentFeature, StructureFeature } from "@/lib/map/types";
|
import type { MapFeaturesResponse, ShipmentFeature, StructureFeature } from "@/lib/map/types";
|
||||||
|
import { gridRef, type MapGridConfig } from "@/lib/map/grid";
|
||||||
|
import { GridLayer } from "./GridLayer";
|
||||||
import { PlacementDialog } from "./PlacementDialog";
|
import { PlacementDialog } from "./PlacementDialog";
|
||||||
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
|
import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar";
|
||||||
import { StructureDetailDrawer } from "./StructureDetailDrawer";
|
import { StructureDetailDrawer } from "./StructureDetailDrawer";
|
||||||
|
|
@ -64,6 +66,7 @@ type LayerToggles = {
|
||||||
zones: boolean;
|
zones: boolean;
|
||||||
shipments: boolean;
|
shipments: boolean;
|
||||||
ranges: boolean;
|
ranges: boolean;
|
||||||
|
grid: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STRUCTURE_STATUS: Record<string, { color: string; label: string }> = {
|
const STRUCTURE_STATUS: Record<string, { color: string; label: string }> = {
|
||||||
|
|
@ -353,7 +356,13 @@ function formatEta(estimatedArrival: string | null, nowMs: number): string | nul
|
||||||
return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MousePosition() {
|
function MousePosition({
|
||||||
|
grid,
|
||||||
|
worldHeight,
|
||||||
|
}: {
|
||||||
|
grid: MapGridConfig | null;
|
||||||
|
worldHeight: number;
|
||||||
|
}) {
|
||||||
const [position, setPosition] = useState<MapPoint | null>(null);
|
const [position, setPosition] = useState<MapPoint | null>(null);
|
||||||
useMapEvents({
|
useMapEvents({
|
||||||
mousemove: (event) => {
|
mousemove: (event) => {
|
||||||
|
|
@ -363,7 +372,11 @@ function MousePosition() {
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<div className="pointer-events-none absolute bottom-2 left-2 z-[1000] rounded border border-white/15 bg-black/70 px-2 py-1 font-mono text-[10px] text-white/80 backdrop-blur-sm">
|
<div className="pointer-events-none absolute bottom-2 left-2 z-[1000] rounded border border-white/15 bg-black/70 px-2 py-1 font-mono text-[10px] text-white/80 backdrop-blur-sm">
|
||||||
{position ? `X ${position[0]} m, Y ${position[1]} m` : "\u00a0"}
|
{position
|
||||||
|
? grid
|
||||||
|
? `${gridRef(position, worldHeight, grid)} // X ${position[0]} m, Y ${position[1]} m`
|
||||||
|
: `X ${position[0]} m, Y ${position[1]} m`
|
||||||
|
: "\u00a0"}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -1162,6 +1175,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
zones: true,
|
zones: true,
|
||||||
shipments: true,
|
shipments: true,
|
||||||
ranges: false,
|
ranges: false,
|
||||||
|
grid: true,
|
||||||
});
|
});
|
||||||
const fetchingRef = useRef(false);
|
const fetchingRef = useRef(false);
|
||||||
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
|
const [mode, setMode] = useState<"view" | "place" | "edit">("view");
|
||||||
|
|
@ -1314,6 +1328,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
setToggles((current) => ({ ...current, [key]: !current[key] }));
|
setToggles((current) => ({ ...current, [key]: !current[key] }));
|
||||||
|
|
||||||
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
|
const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [
|
||||||
|
...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []),
|
||||||
{ key: "structures", label: "Structures" },
|
{ key: "structures", label: "Structures" },
|
||||||
{ key: "nodes", label: "Nodes" },
|
{ key: "nodes", label: "Nodes" },
|
||||||
{ key: "roads", label: "Roads" },
|
{ key: "roads", label: "Roads" },
|
||||||
|
|
@ -1371,6 +1386,10 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
<Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK_PATH_OPTIONS} />
|
<Rectangle bounds={worldBounds} pathOptions={BASEMAP_FALLBACK_PATH_OPTIONS} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{features && mapConfig?.grid.enabled && toggles.grid && (
|
||||||
|
<GridLayer config={mapConfig.grid} worldWidth={worldW} worldHeight={worldH} />
|
||||||
|
)}
|
||||||
|
|
||||||
{features && toggles.zones && (
|
{features && toggles.zones && (
|
||||||
<>
|
<>
|
||||||
{zonePolys.map(({ zone, positions, options }) => (
|
{zonePolys.map(({ zone, positions, options }) => (
|
||||||
|
|
@ -1602,7 +1621,10 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<MousePosition />
|
<MousePosition
|
||||||
|
grid={mapConfig?.grid.enabled ? mapConfig.grid : null}
|
||||||
|
worldHeight={worldH}
|
||||||
|
/>
|
||||||
<MapAttribution prefix="Polaris Task Force // Arma 3 // Leaflet" />
|
<MapAttribution prefix="Polaris Task Force // Arma 3 // Leaflet" />
|
||||||
<FitToViewport worldW={worldW} worldH={worldH} minZoomFloor={mapConfig?.minZoom ?? 0} />
|
<FitToViewport worldW={worldW} worldH={worldH} minZoomFloor={mapConfig?.minZoom ?? 0} />
|
||||||
{mapConfig && (
|
{mapConfig && (
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@
|
||||||
* export flips y against the world height.
|
* export flips y against the world height.
|
||||||
*/
|
*/
|
||||||
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
import { isPointArray, type MapPoint } from "@/lib/map/points";
|
||||||
|
import { DEFAULT_MAP_GRID, gridRef } from "@/lib/map/grid";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MARKER_BRUSH,
|
DEFAULT_MARKER_BRUSH,
|
||||||
DEFAULT_MARKER_COLOR,
|
DEFAULT_MARKER_COLOR,
|
||||||
|
|
@ -426,17 +427,11 @@ export function toArmaPosition(point: MapPoint, worldHeight: number): [number, n
|
||||||
/**
|
/**
|
||||||
* Arma map grid reference (6 digits = 100 m squares, 8 digits = 10 m), the
|
* Arma map grid reference (6 digits = 100 m squares, 8 digits = 10 m), the
|
||||||
* same numbers the in-game map shows: easting then northing, from the
|
* same numbers the in-game map shows: easting then northing, from the
|
||||||
* bottom-left origin. Off-world points clamp to the edge.
|
* bottom-left origin. Thin wrapper over gridRef with the default (vanilla)
|
||||||
|
* grid; off-world points wrap at the digit width like the in-game readout.
|
||||||
*/
|
*/
|
||||||
export function armaGridRef(point: MapPoint, worldHeight: number, digits: 6 | 8 = 6): string {
|
export function armaGridRef(point: MapPoint, worldHeight: number, digits: 6 | 8 = 6): string {
|
||||||
const [x, y] = toArmaPosition(point, worldHeight);
|
return gridRef(point, worldHeight, DEFAULT_MAP_GRID, digits);
|
||||||
const per = digits / 2;
|
|
||||||
const cell = 10 ** (5 - per);
|
|
||||||
const fmt = (value: number) =>
|
|
||||||
String(Math.max(0, Math.floor(value / cell)))
|
|
||||||
.padStart(per, "0")
|
|
||||||
.slice(-per);
|
|
||||||
return `${fmt(x)} ${fmt(y)}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
273
src/lib/map/grid.ts
Normal file
273
src/lib/map/grid.ts
Normal file
|
|
@ -0,0 +1,273 @@
|
||||||
|
/**
|
||||||
|
* Arma-style coordinate grid: per-map configuration, label math, zoom level
|
||||||
|
* selection, and grid references. Pure module (client-safe, no Payload).
|
||||||
|
*
|
||||||
|
* The model mirrors CfgWorlds `class Grid` on A3 terrains. Vanilla terrains
|
||||||
|
* place the grid zero line on the south-west world corner so labels equal raw
|
||||||
|
* world meters; the config below can shift that origin (placement), renumber
|
||||||
|
* the first line (starting numbers), and resize the base cell, so each map
|
||||||
|
* can reproduce its in-game grid exactly.
|
||||||
|
*
|
||||||
|
* Coordinate spaces: our maps store meters with origin top-left and y running
|
||||||
|
* south. Arma world coordinates run origin bottom-left, y north. Grid math
|
||||||
|
* happens in Arma space (y north); conversion is `armaY = worldHeight - mapY`.
|
||||||
|
*
|
||||||
|
* Label rules (verified against in-game anchors on Altis/Stratis/Malden/Tanoa):
|
||||||
|
* values are floor-truncated cell indices, wrapped modulo 10^digits and
|
||||||
|
* zero-padded (negative indices wrap the same way, e.g. -1 at 3 digits reads
|
||||||
|
* "999"). Zoom levels step by powers of ten and nest exactly: the 1 km cell
|
||||||
|
* labeled "10" contains the 100 m lines "100" through "109".
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { MapPoint } from "./points";
|
||||||
|
|
||||||
|
export interface MapGridConfig {
|
||||||
|
/** Master switch: overlay + configured grid references. */
|
||||||
|
enabled: boolean;
|
||||||
|
/** Arma-space meters from the west edge to the grid zero line (in-game X). */
|
||||||
|
originEasting: number;
|
||||||
|
/** Arma-space meters from the south edge to the grid zero line (in-game Y). */
|
||||||
|
originNorthing: number;
|
||||||
|
/** Label value shown on the zero line at the base spacing (eastings). */
|
||||||
|
startEasting: number;
|
||||||
|
/** Label value shown on the zero line at the base spacing (northings). */
|
||||||
|
startNorthing: number;
|
||||||
|
/** Base cell size in meters (Arma's 1 km level by default). */
|
||||||
|
spacingMeters: number;
|
||||||
|
/** Digits shown per axis at the base spacing (Arma shows 2 at 1 km). */
|
||||||
|
labelDigits: number;
|
||||||
|
/** Tanoa style: draw numbers over the lines instead of centered in cells. */
|
||||||
|
numbersOverLines: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default grid: zero line on the south-west corner, 1 km base cells, numbers
|
||||||
|
* from zero. gridRef with these values reproduces the legacy armaGridRef
|
||||||
|
* output exactly (100 m cells at 6 digits, 10 m at 8).
|
||||||
|
*/
|
||||||
|
export const DEFAULT_MAP_GRID: MapGridConfig = {
|
||||||
|
enabled: false,
|
||||||
|
originEasting: 0,
|
||||||
|
originNorthing: 0,
|
||||||
|
startEasting: 0,
|
||||||
|
startNorthing: 0,
|
||||||
|
spacingMeters: 1000,
|
||||||
|
labelDigits: 2,
|
||||||
|
numbersOverLines: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
function finite(value: unknown): value is number {
|
||||||
|
return typeof value === "number" && Number.isFinite(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampInt(value: number, min: number, max: number): number {
|
||||||
|
return Math.min(max, Math.max(min, Math.round(value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Coerce a maps collection row into a grid config, tolerating nulls. */
|
||||||
|
export function gridConfigFromMapDoc(doc: Record<string, unknown> | null | undefined): MapGridConfig {
|
||||||
|
const raw = doc ?? {};
|
||||||
|
const spacing = finite(raw.gridSpacingMeters) && raw.gridSpacingMeters >= 1
|
||||||
|
? raw.gridSpacingMeters
|
||||||
|
: DEFAULT_MAP_GRID.spacingMeters;
|
||||||
|
return {
|
||||||
|
enabled: raw.gridEnabled === true,
|
||||||
|
originEasting: finite(raw.gridOriginEasting) ? raw.gridOriginEasting : 0,
|
||||||
|
originNorthing: finite(raw.gridOriginNorthing) ? raw.gridOriginNorthing : 0,
|
||||||
|
startEasting: finite(raw.gridStartEasting) ? Math.trunc(raw.gridStartEasting) : 0,
|
||||||
|
startNorthing: finite(raw.gridStartNorthing) ? Math.trunc(raw.gridStartNorthing) : 0,
|
||||||
|
spacingMeters: spacing,
|
||||||
|
labelDigits: finite(raw.gridLabelDigits)
|
||||||
|
? clampInt(raw.gridLabelDigits, 1, 6)
|
||||||
|
: DEFAULT_MAP_GRID.labelDigits,
|
||||||
|
numbersOverLines: raw.gridNumbersOverLines === true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Floor-modulo that wraps negatives into [0, modulus), matching Arma. */
|
||||||
|
function wrapMod(value: number, modulus: number): number {
|
||||||
|
return ((value % modulus) + modulus) % modulus;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zero-padded label for a cell index at `digits` precision, wrapped modulo
|
||||||
|
* 10^digits with leading zeros ("7" at 3 digits reads "007", -1 reads "999").
|
||||||
|
*/
|
||||||
|
export function gridLabel(cellIndex: number, digits: number): string {
|
||||||
|
const modulus = 10 ** digits;
|
||||||
|
return String(wrapMod(Math.trunc(cellIndex), modulus)).padStart(digits, "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cell index of an Arma-space coordinate at a given spacing, including the
|
||||||
|
* configured origin and starting-number offset. Starting numbers are defined
|
||||||
|
* at the base spacing and scale into finer levels (a base start of 5 reads
|
||||||
|
* "05" at 1 km and "050" at 100 m); at coarser-than-base levels the start
|
||||||
|
* contribution floors out and is ignored.
|
||||||
|
*/
|
||||||
|
function cellValue(armaCoord: number, origin: number, start: number, spacing: number, baseSpacing: number): number {
|
||||||
|
const index = Math.floor((armaCoord - origin) / spacing);
|
||||||
|
const scale = baseSpacing / spacing;
|
||||||
|
return index + (scale >= 1 ? Math.floor(start * scale) : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GridLevel {
|
||||||
|
/** Cell size of the active level in meters. */
|
||||||
|
spacing: number;
|
||||||
|
/** Label digits per axis at this level. */
|
||||||
|
digits: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On-screen cell size below which a finer level is chosen instead. Sized so a
|
||||||
|
* typical viewport shows roughly 15-40 lines, close to the in-game map.
|
||||||
|
*/
|
||||||
|
export const GRID_MIN_CELL_PX = 56;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pick the zoom level for a meters-per-pixel scale. The ladder runs from
|
||||||
|
* 100x coarser to 100x finer than the base spacing in power-of-ten steps
|
||||||
|
* (with default config: 10 km/1 digit, 1 km/2, 100 m/3, 10 m/4, the A3
|
||||||
|
* ladder). The finest level whose on-screen cell stays readable wins; zooming
|
||||||
|
* out past the coarsest level just keeps it.
|
||||||
|
*/
|
||||||
|
export function gridLevelFor(metersPerPxValue: number, config: MapGridConfig): GridLevel {
|
||||||
|
const base = config.spacingMeters;
|
||||||
|
const levels: GridLevel[] = [];
|
||||||
|
for (let k = -2; k <= 2; k++) {
|
||||||
|
const digits = config.labelDigits + k;
|
||||||
|
if (digits < 1 || digits > 8) continue;
|
||||||
|
levels.push({ spacing: base / 10 ** k, digits });
|
||||||
|
}
|
||||||
|
if (levels.length === 0) return { spacing: base, digits: config.labelDigits };
|
||||||
|
// levels run coarse to fine; take the finest that still reads on screen.
|
||||||
|
let chosen = levels[0];
|
||||||
|
for (const level of levels) {
|
||||||
|
if (level.spacing / metersPerPxValue >= GRID_MIN_CELL_PX) chosen = level;
|
||||||
|
}
|
||||||
|
return chosen;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GridLabel {
|
||||||
|
/** Line index (or cell index in cell-centered mode) this label shows. */
|
||||||
|
value: string;
|
||||||
|
/** Anchor position on the label's axis, in map meters. */
|
||||||
|
at: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GridLineSet {
|
||||||
|
level: GridLevel;
|
||||||
|
/** Vertical line positions, map meters (x, measured from the west edge). */
|
||||||
|
verticalLines: number[];
|
||||||
|
/** Horizontal line positions, map meters (y, measured from the north edge). */
|
||||||
|
horizontalLines: number[];
|
||||||
|
/** Easting labels (top/bottom edges), x in map meters. */
|
||||||
|
eastingLabels: GridLabel[];
|
||||||
|
/** Northing labels (left/right edges), y in map meters. */
|
||||||
|
northingLabels: GridLabel[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GridBounds {
|
||||||
|
minX: number;
|
||||||
|
minY: number;
|
||||||
|
maxX: number;
|
||||||
|
maxY: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lines and labels covering a viewport, in map meters (origin top-left, y
|
||||||
|
* south). Labels are cell-centered by default (Arma draws numbers between the
|
||||||
|
* lines) and sit on the lines when `numbersOverLines` is set (Tanoa style).
|
||||||
|
* Bounds are padded by one cell so labels do not pop while panning.
|
||||||
|
*/
|
||||||
|
export function gridLinesForBounds(
|
||||||
|
config: MapGridConfig,
|
||||||
|
worldHeight: number,
|
||||||
|
bounds: GridBounds,
|
||||||
|
metersPerPxValue: number,
|
||||||
|
): GridLineSet {
|
||||||
|
const level = gridLevelFor(metersPerPxValue, config);
|
||||||
|
const { spacing, digits } = level;
|
||||||
|
const pad = spacing;
|
||||||
|
|
||||||
|
const firstV = Math.floor((bounds.minX - config.originEasting - pad) / spacing);
|
||||||
|
const lastV = Math.ceil((bounds.maxX - config.originEasting + pad) / spacing);
|
||||||
|
const verticalLines: number[] = [];
|
||||||
|
const eastingLabels: GridLabel[] = [];
|
||||||
|
for (let k = firstV; k <= lastV; k++) {
|
||||||
|
const x = config.originEasting + k * spacing;
|
||||||
|
verticalLines.push(x);
|
||||||
|
if (x < bounds.minX - pad || x > bounds.maxX + pad) continue;
|
||||||
|
if (config.numbersOverLines) {
|
||||||
|
eastingLabels.push({ value: gridLabel(cellValue(x, config.originEasting, config.startEasting, spacing, config.spacingMeters), digits), at: x });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!config.numbersOverLines) {
|
||||||
|
for (let k = firstV; k <= lastV; k++) {
|
||||||
|
const center = config.originEasting + (k + 0.5) * spacing;
|
||||||
|
if (center < bounds.minX - pad || center > bounds.maxX + pad) continue;
|
||||||
|
eastingLabels.push({
|
||||||
|
value: gridLabel(
|
||||||
|
cellValue(config.originEasting + k * spacing, config.originEasting, config.startEasting, spacing, config.spacingMeters),
|
||||||
|
digits,
|
||||||
|
),
|
||||||
|
at: center,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Arma-space northing of the viewport: map y runs south, so flip.
|
||||||
|
const armaMin = worldHeight - bounds.maxY;
|
||||||
|
const armaMax = worldHeight - bounds.minY;
|
||||||
|
const firstH = Math.floor((armaMin - config.originNorthing - pad) / spacing);
|
||||||
|
const lastH = Math.ceil((armaMax - config.originNorthing + pad) / spacing);
|
||||||
|
const horizontalLines: number[] = [];
|
||||||
|
const northingLabels: GridLabel[] = [];
|
||||||
|
for (let k = firstH; k <= lastH; k++) {
|
||||||
|
const armaY = config.originNorthing + k * spacing;
|
||||||
|
horizontalLines.push(worldHeight - armaY);
|
||||||
|
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
|
||||||
|
if (config.numbersOverLines) {
|
||||||
|
northingLabels.push({ value: gridLabel(cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters), digits), at: worldHeight - armaY });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!config.numbersOverLines) {
|
||||||
|
for (let k = firstH; k <= lastH; k++) {
|
||||||
|
const armaY = config.originNorthing + (k + 0.5) * spacing;
|
||||||
|
if (armaY < armaMin - pad || armaY > armaMax + pad) continue;
|
||||||
|
northingLabels.push({
|
||||||
|
value: gridLabel(
|
||||||
|
cellValue(config.originNorthing + k * spacing, config.originNorthing, config.startNorthing, spacing, config.spacingMeters),
|
||||||
|
digits,
|
||||||
|
),
|
||||||
|
at: worldHeight - armaY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { level, verticalLines, horizontalLines, eastingLabels, northingLabels };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Arma grid reference for a map-meter point: easting group then northing
|
||||||
|
* group, 6 digits (3+3, 100 m cells with default config) or 8 digits (4+4,
|
||||||
|
* 10 m). Values wrap at the digit width like the in-game readout. With
|
||||||
|
* DEFAULT_MAP_GRID this reproduces the legacy armaGridRef output for any
|
||||||
|
* in-world point.
|
||||||
|
*/
|
||||||
|
export function gridRef(
|
||||||
|
point: MapPoint,
|
||||||
|
worldHeight: number,
|
||||||
|
config: MapGridConfig = DEFAULT_MAP_GRID,
|
||||||
|
digits: 6 | 8 = 6,
|
||||||
|
): string {
|
||||||
|
const per = digits / 2;
|
||||||
|
// Precision relative to the base level: default config lands on 100 m at
|
||||||
|
// 6 digits and 10 m at 8, matching Arma's finest zoom classes.
|
||||||
|
const spacing = config.spacingMeters / 10 ** (per - config.labelDigits);
|
||||||
|
const armaX = point[0];
|
||||||
|
const armaY = worldHeight - point[1];
|
||||||
|
const easting = cellValue(armaX, config.originEasting, config.startEasting, spacing, config.spacingMeters);
|
||||||
|
const northing = cellValue(armaY, config.originNorthing, config.startNorthing, spacing, config.spacingMeters);
|
||||||
|
return `${gridLabel(easting, per)} ${gridLabel(northing, per)}`;
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type { MapPoint } from "./points";
|
import type { MapPoint } from "./points";
|
||||||
|
import type { MapGridConfig } from "./grid";
|
||||||
|
|
||||||
export interface MapConfig {
|
export interface MapConfig {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -12,6 +13,7 @@ export interface MapConfig {
|
||||||
maxZoom: number;
|
maxZoom: number;
|
||||||
defaultZoom: number;
|
defaultZoom: number;
|
||||||
defaultCenter: MapPoint;
|
defaultCenter: MapPoint;
|
||||||
|
grid: MapGridConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RangeRequirementFeature {
|
export interface RangeRequirementFeature {
|
||||||
|
|
|
||||||
36325
src/migrations/20261005_001212_add_map_grid_config.json
Normal file
36325
src/migrations/20261005_001212_add_map_grid_config.json
Normal file
File diff suppressed because it is too large
Load diff
35
src/migrations/20261005_001212_add_map_grid_config.ts
Normal file
35
src/migrations/20261005_001212_add_map_grid_config.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the per-map Arma-style coordinate grid config to the maps collection.
|
||||||
|
* Hand-trimmed: the generated diff also carried unrelated snapshot drift from
|
||||||
|
* earlier hand-written migrations missing their .json sidecars
|
||||||
|
* (mission_map_markers, ai plugin model enum, assets accessory enum value,
|
||||||
|
* payload_mcp_api_keys columns). Those objects already exist in every
|
||||||
|
* migrated database via their own migrations, so this migration applies only
|
||||||
|
* the maps grid columns. The committed .json snapshot is intentionally the
|
||||||
|
* full current schema so future diffs exclude that drift.
|
||||||
|
*/
|
||||||
|
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_enabled" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_origin_easting" numeric DEFAULT 0;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_origin_northing" numeric DEFAULT 0;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_start_easting" numeric DEFAULT 0;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_start_northing" numeric DEFAULT 0;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_spacing_meters" numeric DEFAULT 1000;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_label_digits" numeric DEFAULT 2;
|
||||||
|
ALTER TABLE "maps" ADD COLUMN "grid_numbers_over_lines" boolean DEFAULT false;`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_enabled";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_origin_easting";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_origin_northing";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_start_easting";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_start_northing";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_spacing_meters";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_label_digits";
|
||||||
|
ALTER TABLE "maps" DROP COLUMN "grid_numbers_over_lines";`)
|
||||||
|
}
|
||||||
260
tests/int/map-grid.int.spec.ts
Normal file
260
tests/int/map-grid.int.spec.ts
Normal file
|
|
@ -0,0 +1,260 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { armaGridRef } from "@/lib/arma-markers/missionMarkers";
|
||||||
|
import {
|
||||||
|
DEFAULT_MAP_GRID,
|
||||||
|
GRID_MIN_CELL_PX,
|
||||||
|
gridConfigFromMapDoc,
|
||||||
|
gridLabel,
|
||||||
|
gridLevelFor,
|
||||||
|
gridLinesForBounds,
|
||||||
|
gridRef,
|
||||||
|
} from "@/lib/map/grid";
|
||||||
|
|
||||||
|
const WORLD = 8192;
|
||||||
|
const FULL_WORLD = { minX: 0, minY: 0, maxX: WORLD, maxY: WORLD };
|
||||||
|
|
||||||
|
describe("gridLabel", () => {
|
||||||
|
it("zero-pads to the digit width", () => {
|
||||||
|
expect(gridLabel(7, 3)).toBe("007");
|
||||||
|
expect(gridLabel(0, 2)).toBe("00");
|
||||||
|
expect(gridLabel(42, 4)).toBe("0042");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wraps at the digit width", () => {
|
||||||
|
expect(gridLabel(1234, 3)).toBe("234");
|
||||||
|
expect(gridLabel(100, 2)).toBe("00");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wraps negatives like Arma", () => {
|
||||||
|
expect(gridLabel(-1, 3)).toBe("999");
|
||||||
|
expect(gridLabel(-25, 2)).toBe("75");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("truncates fractional input", () => {
|
||||||
|
expect(gridLabel(12.9, 2)).toBe("12");
|
||||||
|
expect(gridLabel(-1.5, 2)).toBe("99");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("gridLevelFor", () => {
|
||||||
|
it("walks the A3 ladder with the default config", () => {
|
||||||
|
expect(gridLevelFor(8, DEFAULT_MAP_GRID)).toEqual({ spacing: 1000, digits: 2 });
|
||||||
|
expect(gridLevelFor(0.5, DEFAULT_MAP_GRID)).toEqual({ spacing: 100, digits: 3 });
|
||||||
|
expect(gridLevelFor(0.0625, DEFAULT_MAP_GRID)).toEqual({ spacing: 10, digits: 4 });
|
||||||
|
// Far out: nothing finer reads, the coarsest level wins.
|
||||||
|
expect(gridLevelFor(64, DEFAULT_MAP_GRID)).toEqual({ spacing: 10000, digits: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the coarsest level when zoomed out past every threshold", () => {
|
||||||
|
expect(gridLevelFor(1000, DEFAULT_MAP_GRID)).toEqual({ spacing: 10000, digits: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("chooses a level exactly at GRID_MIN_CELL_PX and never a finer one below it", () => {
|
||||||
|
expect(GRID_MIN_CELL_PX).toBe(56);
|
||||||
|
// 5600 m base cells: at 100 m/px the base cell is exactly 56 px on screen.
|
||||||
|
const config = gridConfigFromMapDoc({ gridEnabled: true, gridSpacingMeters: 5600 });
|
||||||
|
expect(gridLevelFor(100, config)).toEqual({ spacing: 5600, digits: 2 });
|
||||||
|
// A hair further out the base cell drops under the threshold; the finer
|
||||||
|
// levels are smaller still, so the ladder falls back to the coarse level.
|
||||||
|
expect(gridLevelFor(101, config)).toEqual({ spacing: 56000, digits: 1 });
|
||||||
|
// Same crossing on the default ladder between mpp 1.7 and 2 (100 m cell
|
||||||
|
// sits at 58.8 px, then 50 px).
|
||||||
|
expect(gridLevelFor(1.7, DEFAULT_MAP_GRID)).toEqual({ spacing: 100, digits: 3 });
|
||||||
|
expect(gridLevelFor(2, DEFAULT_MAP_GRID)).toEqual({ spacing: 1000, digits: 2 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("gridRef", () => {
|
||||||
|
it("reproduces the legacy armaGridRef output with DEFAULT_MAP_GRID", () => {
|
||||||
|
const point: [number, number] = [4567, WORLD - 1234];
|
||||||
|
expect(gridRef(point, WORLD, DEFAULT_MAP_GRID, 6)).toBe("045 012");
|
||||||
|
expect(gridRef(point, WORLD, DEFAULT_MAP_GRID, 8)).toBe("0456 0123");
|
||||||
|
// Default arguments land on the same 6-digit reference.
|
||||||
|
expect(gridRef(point, WORLD)).toBe("045 012");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("armaGridRef still returns the legacy strings (it delegates to gridRef)", () => {
|
||||||
|
expect(armaGridRef([4567, WORLD - 1234], WORLD)).toBe("045 012");
|
||||||
|
expect(armaGridRef([4567, WORLD - 1234], WORLD, 8)).toBe("0456 0123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses 100 m cells at 6 digits and 10 m cells at 8", () => {
|
||||||
|
const point: [number, number] = [4567, WORLD - 1234];
|
||||||
|
const [e6, n6] = gridRef(point, WORLD, DEFAULT_MAP_GRID, 6).split(" ");
|
||||||
|
const [e8, n8] = gridRef(point, WORLD, DEFAULT_MAP_GRID, 8).split(" ");
|
||||||
|
// The 6-digit groups are the truncation of the 8-digit groups.
|
||||||
|
expect(e8.startsWith(e6)).toBe(true);
|
||||||
|
expect(n8.startsWith(n6)).toBe(true);
|
||||||
|
// 100 m granularity at 6 digits: 4599 stays, 4600 rolls over.
|
||||||
|
expect(gridRef([4599, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 6)).toBe("045 012");
|
||||||
|
expect(gridRef([4600, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 6)).toBe("046 012");
|
||||||
|
// 10 m granularity at 8 digits: 4569 stays, 4570 rolls over.
|
||||||
|
expect(gridRef([4569, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 8)).toBe("0456 0123");
|
||||||
|
expect(gridRef([4570, WORLD - 1234], WORLD, DEFAULT_MAP_GRID, 8)).toBe("0457 0123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shifts the zero line with gridOriginEasting/gridOriginNorthing", () => {
|
||||||
|
const config = gridConfigFromMapDoc({
|
||||||
|
gridEnabled: true,
|
||||||
|
gridOriginEasting: 2000,
|
||||||
|
gridOriginNorthing: 3000,
|
||||||
|
});
|
||||||
|
// A point exactly on the configured origin reads zero at every precision.
|
||||||
|
const atOrigin: [number, number] = [2000, WORLD - 3000];
|
||||||
|
expect(gridRef(atOrigin, WORLD, config, 6)).toBe("000 000");
|
||||||
|
expect(gridRef(atOrigin, WORLD, config, 8)).toBe("0000 0000");
|
||||||
|
// The vanilla default would read raw meters at the same spot.
|
||||||
|
expect(gridRef(atOrigin, WORLD, DEFAULT_MAP_GRID, 6)).toBe("020 030");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads the configured starting numbers on the origin line", () => {
|
||||||
|
const config = gridConfigFromMapDoc({
|
||||||
|
gridEnabled: true,
|
||||||
|
gridOriginEasting: 2000,
|
||||||
|
gridOriginNorthing: 3000,
|
||||||
|
gridStartEasting: 5,
|
||||||
|
gridStartNorthing: 7,
|
||||||
|
});
|
||||||
|
// Start numbers are defined at the base spacing and scale into finer
|
||||||
|
// levels: 5 at 1 km reads "050" at 100 m.
|
||||||
|
expect(gridRef([2000, WORLD - 3000], WORLD, config, 6)).toBe("050 070");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("scales starting numbers across levels and keeps the nesting mod rule", () => {
|
||||||
|
const config = gridConfigFromMapDoc({ gridEnabled: true, gridStartEasting: 100 });
|
||||||
|
// Base level (1 km, 2 digits): the first cell east of the zero line adds
|
||||||
|
// the start value, then wraps to the digit width.
|
||||||
|
const set = gridLinesForBounds(config, WORLD, FULL_WORLD, 8);
|
||||||
|
expect(set.level).toEqual({ spacing: 1000, digits: 2 });
|
||||||
|
const baseLabel = set.eastingLabels.find((l) => l.at === 500);
|
||||||
|
expect(baseLabel?.value).toBe("00"); // 0 + 100, wrapped to 2 digits
|
||||||
|
// 100 m level (6-digit ref) at the zero line: 0 + 100*10 = 1000 -> "000".
|
||||||
|
const [easting6] = gridRef([0, WORLD - 1234], WORLD, config, 6).split(" ");
|
||||||
|
expect(easting6).toBe("000");
|
||||||
|
// Nesting: the finer label's trailing digits match the base label.
|
||||||
|
expect(easting6.slice(-2)).toBe(baseLabel?.value);
|
||||||
|
// 10 m level (8-digit ref): 0 + 100*100 = 10000 -> "0000".
|
||||||
|
expect(gridRef([0, WORLD - 1234], WORLD, config, 8).split(" ")[0]).toBe("0000");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("wraps labels west of an origin that sits east of the point", () => {
|
||||||
|
const config = gridConfigFromMapDoc({ gridEnabled: true, gridOriginEasting: 5000 });
|
||||||
|
// x = 1000 lies 4000 m west of the zero line: -40 cells at 100 m.
|
||||||
|
expect(gridRef([1000, WORLD - 1000], WORLD, config, 6)).toBe("960 010");
|
||||||
|
// Base level: the cell holding x = 1000 is index -4, wrapped to "96".
|
||||||
|
const set = gridLinesForBounds(
|
||||||
|
config,
|
||||||
|
WORLD,
|
||||||
|
{ minX: 0, minY: 0, maxX: 2000, maxY: 2000 },
|
||||||
|
8,
|
||||||
|
);
|
||||||
|
expect(set.eastingLabels.find((l) => l.at === 1500)?.value).toBe("96");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("gridLinesForBounds", () => {
|
||||||
|
it("covers the viewport plus one padded cell of lines at the 1 km level", () => {
|
||||||
|
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
|
||||||
|
expect(set.level).toEqual({ spacing: 1000, digits: 2 });
|
||||||
|
// Lines span one padded cell past each edge; the east/south side ceils to
|
||||||
|
// the next line because 8192 is not cell-aligned.
|
||||||
|
expect(set.verticalLines).toEqual([
|
||||||
|
-1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000,
|
||||||
|
]);
|
||||||
|
expect(set.horizontalLines).toEqual([
|
||||||
|
9192, 8192, 7192, 6192, 5192, 4192, 3192, 2192, 1192, 192, -808, -1808,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("centers easting labels in their cells by default", () => {
|
||||||
|
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
|
||||||
|
expect(set.eastingLabels).toHaveLength(10);
|
||||||
|
expect(set.eastingLabels[1]).toEqual({ value: "00", at: 500 });
|
||||||
|
expect(set.eastingLabels[2]).toEqual({ value: "01", at: 1500 });
|
||||||
|
// One padded cell west of the zero line wraps to "99".
|
||||||
|
expect(set.eastingLabels[0]).toEqual({ value: "99", at: -500 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("places northing labels in map space (y south) with the Arma y-flip", () => {
|
||||||
|
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
|
||||||
|
// Arma northing cell 0 centers 500 m above the south edge.
|
||||||
|
expect(set.northingLabels.find((l) => l.value === "00")?.at).toBe(WORLD - 500);
|
||||||
|
// Cell 7 centers at 7500 m Arma-north: map y = 8192 - 7500 = 692.
|
||||||
|
const seven = set.northingLabels.find((l) => l.value === "07");
|
||||||
|
expect(seven?.at).toBe(WORLD - 7500);
|
||||||
|
expect(seven?.at).toBe(692);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("puts labels on the lines when numbersOverLines is set", () => {
|
||||||
|
const config = gridConfigFromMapDoc({ gridEnabled: true, gridNumbersOverLines: true });
|
||||||
|
const set = gridLinesForBounds(config, WORLD, FULL_WORLD, 8);
|
||||||
|
expect(set.eastingLabels.find((l) => l.at === 0)?.value).toBe("00");
|
||||||
|
expect(set.eastingLabels.find((l) => l.at === 1000)?.value).toBe("01");
|
||||||
|
expect(set.northingLabels.find((l) => l.at === WORLD)?.value).toBe("00");
|
||||||
|
// Every anchor is a line position, not a cell center.
|
||||||
|
expect(set.eastingLabels.every((l) => set.verticalLines.includes(l.at))).toBe(true);
|
||||||
|
expect(set.northingLabels.every((l) => set.horizontalLines.includes(l.at))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("extends lines and labels past the world edge, counting and wrapping", () => {
|
||||||
|
const set = gridLinesForBounds(DEFAULT_MAP_GRID, WORLD, FULL_WORLD, 8);
|
||||||
|
// Lines run past the east and south edges.
|
||||||
|
expect(set.verticalLines).toContain(9000);
|
||||||
|
expect(set.verticalLines).toContain(10000);
|
||||||
|
expect(set.horizontalLines).toContain(-808);
|
||||||
|
// Values keep counting past the east edge (cell 8 centered at 8500).
|
||||||
|
expect(set.eastingLabels.find((l) => l.at === 8500)?.value).toBe("08");
|
||||||
|
// Past the north edge (map y negative): northing cell 8 at y = -308.
|
||||||
|
expect(set.northingLabels.find((l) => l.at === -308)?.value).toBe("08");
|
||||||
|
// West of the zero line and south of the world the values wrap.
|
||||||
|
expect(set.eastingLabels.find((l) => l.at === -500)?.value).toBe("99");
|
||||||
|
expect(set.northingLabels.find((l) => l.at === WORLD + 500)?.value).toBe("99");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("gridConfigFromMapDoc", () => {
|
||||||
|
it("returns DEFAULT_MAP_GRID for null, undefined and empty docs", () => {
|
||||||
|
expect(gridConfigFromMapDoc(null)).toEqual(DEFAULT_MAP_GRID);
|
||||||
|
expect(gridConfigFromMapDoc(undefined)).toEqual(DEFAULT_MAP_GRID);
|
||||||
|
expect(gridConfigFromMapDoc({})).toEqual(DEFAULT_MAP_GRID);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tolerates null fields and falls back to defaults", () => {
|
||||||
|
const config = gridConfigFromMapDoc({
|
||||||
|
gridEnabled: null,
|
||||||
|
gridOriginEasting: null,
|
||||||
|
gridOriginNorthing: null,
|
||||||
|
gridStartEasting: null,
|
||||||
|
gridStartNorthing: null,
|
||||||
|
gridSpacingMeters: null,
|
||||||
|
gridLabelDigits: null,
|
||||||
|
gridNumbersOverLines: null,
|
||||||
|
});
|
||||||
|
expect(config).toEqual(DEFAULT_MAP_GRID);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to 1000 m when gridSpacingMeters is 0 or missing", () => {
|
||||||
|
expect(gridConfigFromMapDoc({ gridSpacingMeters: 0 }).spacingMeters).toBe(1000);
|
||||||
|
expect(gridConfigFromMapDoc({}).spacingMeters).toBe(1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clamps gridLabelDigits to [1, 6]", () => {
|
||||||
|
expect(gridConfigFromMapDoc({ gridLabelDigits: 0 }).labelDigits).toBe(1);
|
||||||
|
expect(gridConfigFromMapDoc({ gridLabelDigits: -4 }).labelDigits).toBe(1);
|
||||||
|
expect(gridConfigFromMapDoc({ gridLabelDigits: 9 }).labelDigits).toBe(6);
|
||||||
|
expect(gridConfigFromMapDoc({ gridLabelDigits: 3 }).labelDigits).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("truncates fractional starting numbers", () => {
|
||||||
|
expect(gridConfigFromMapDoc({ gridStartEasting: 3.9 }).startEasting).toBe(3);
|
||||||
|
expect(gridConfigFromMapDoc({ gridStartNorthing: -2.7 }).startNorthing).toBe(-2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads the boolean flags strictly", () => {
|
||||||
|
expect(gridConfigFromMapDoc({ gridEnabled: true }).enabled).toBe(true);
|
||||||
|
expect(gridConfigFromMapDoc({ gridEnabled: 1 }).enabled).toBe(false);
|
||||||
|
expect(gridConfigFromMapDoc({ gridNumbersOverLines: true }).numbersOverLines).toBe(true);
|
||||||
|
expect(gridConfigFromMapDoc({ gridNumbersOverLines: "yes" }).numbersOverLines).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue