From 3abdc955000f9e4075864cfff10d36c356ecf9ea Mon Sep 17 00:00:00 2001 From: Lucio Chen Date: Sat, 8 Aug 2026 16:40:09 -0700 Subject: [PATCH] Add interactive map placement and sizing editor --- .gitignore | 3 + DOCUMENTATION.md | 63 +++++++---- PLAN.md | 6 +- README.md | 23 +++- docs/adding-a-map.md | 13 ++- maps.json | 70 +++++++----- server/run.ps1 | 14 ++- server/serve.py | 137 +++++++++++++++++++++++- tools/common.py | 7 +- tools/place_preview.py | 17 +-- tools/tile.py | 37 ++++++- web/app.js | 237 ++++++++++++++++++++++++++++++++++++++++- web/index.html | 21 ++++ web/style.css | 80 ++++++++++++++ 14 files changed, 647 insertions(+), 81 deletions(-) diff --git a/.gitignore b/.gitignore index 9b6f439..fa9ae49 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ __pycache__/ *.pyc .venv/ node_modules/ + +# Local Git worktrees used for parallel feature development. +.worktrees/ diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 7640856..09acdaa 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -109,13 +109,13 @@ expressed here. internally; you never author in this space. **3. Overall-map pixels (rotated)** — the same image after -`rotate(world.rotate, expand=True)`, currently 1816 × 1812 at 35°. **This is +`rotate(world.rotate, expand=True)`, currently 1842 × 1842 at 45°. **This is where `place` lives**, because it is the north-up image you actually look at. `tools/place_preview.py` draws a 100 px grid over it so you can read coordinates directly. **4. World pixels** — rotated overall-map pixels × `world.overallScale` (64). -The world is 116 160 × 115 968. Tiles, origins and Leaflet coordinates all use +The world is 117 824 × 117 824. Tiles, origins and Leaflet coordinates all use this space. In the viewer, a Leaflet `LatLng` is `(y, x)` in world pixels at native @@ -157,7 +157,7 @@ every zoom level. That holds only when the origin is a multiple of cellSize = tileSize · 2^maxZoom = 256 · 2^9 = 131 072 world pixels ``` -131 072 px is larger than the entire world (116 160 px). Useless for +131 072 px is larger than the entire world (117 824 px). Useless for positioning — every map would land at (0, 0). **The fix is to pad, not to snap.** The tiler: @@ -284,7 +284,7 @@ around 8 GB for the largest PSDs. | `maxZoom` | 9 | World zoom depth; sets `cellSize = tileSize · 2^maxZoom` | | `attribution` | HTML | Shown in the viewer; **must** keep the re3mr credit | | `world.image` | path | The base map | -| `world.rotate` | 35 | Degrees counter-clockwise to put north up | +| `world.rotate` | 45 | Degrees counter-clockwise to put north up | | `world.overallScale` | 64 | World pixels per overall-map pixel | ### Per map @@ -297,11 +297,18 @@ around 8 GB for the largest PSDs. | `baseLayers` | yes | Slash-paths from the document root; everything else hidden | | `excludeLayers` | no | Layer names to hide anywhere inside the kept set | | `crop` | no | `[x0, y0, x1, y1]` in PSD pixels, or `null` | -| `place` | yes | `{cx, cy, w}` in **rotated** overall-map pixels | +| `minZoom` | no | Raise the automatically derived zoom at which a nested detail layer appears | +| `place` | yes | `{cx, cy, w, h?}`: center anchor and dimensions in **rotated** overall-map pixels | | `pxPerMeter` | no | From the map's scale bar; recorded for future use | -`place.w` is the map's width in overall-map pixels; height follows from the -source aspect ratio. +`place.w` is the map's width in overall-map pixels. Height follows from the +source aspect ratio unless optional `place.h` is set, in which case width and +height can be tuned independently. + +`minZoom` is normally derived from placed size so a layer does not load while +it would be a speck. An explicit value is a lower visibility bound: it can +delay a nested detail layer until a closer zoom, but cannot force it to appear +earlier than the automatic threshold or above its native tile level. **Changing `world.rotate` by hand will move every map**, because `place` lives in the rotated frame. Use `python tools/retilt.py `, which converts each @@ -318,9 +325,9 @@ a map is a data change. { "tileSize": 256, "maxZoom": 9, - "worldSize": [116160, 115968], + "worldSize": [117824, 117824], "cellSize": 131072, - "rotate": 35.0, + "rotate": 45.0, "overallScale": 64.0, "attribution": "Maps by re3mr.com · CC BY-NC-SA 4.0", "maps": [ @@ -410,6 +417,20 @@ LAN. The boost switches itself off on a 1:1 display with integer zoom. - Mobile: `viewport-fit=cover`, safe-area insets, 44 px touch targets, collapsible picker, zoom buttons hidden under 640 px in favour of pinch. +### Placement editor + +Each detail map's `place.cx/cy` is its center anchor in rotated overall-map +pixels. Select a map and choose **Edit placement** to expose that anchor. A +drag or numeric X/Y edit translates the map's dedicated Leaflet pane live. +Width and Height scale the same pane independently around the anchor, providing +horizontal and vertical stretch with a live aspect-ratio readout. + +**Save & rebuild** posts the new center and dimensions to `server/serve.py`. +The server writes `maps.json` atomically, runs a tiles-only build for that map, +and returns only after `world.json` contains its new origin, size and +cache-busting version. Use +`pwsh server/run.ps1 -Editable`; the Caddy-only mode remains read-only. + --- ## 9. Serving @@ -547,7 +568,7 @@ Two attempts failed: filled region came out at 2 % coverage with elongation 1.24 against the PSD's 3.73. -The current **35°** is a visual judgement, not a measurement. `retilt.py` makes +The current **45°** is a visual judgement, not a measurement. `retilt.py` makes it a one-number change. ### PowerShell here-strings in Bash @@ -612,21 +633,21 @@ whose tiles were deleted. Re-run `build.py`. ## 14. Current state -World 116 160 × 115 968 px, `maxZoom` 9, rotated 35°. Ten layers, **6096 tiles, +World 117 824 × 117 824 px, `maxZoom` 9, rotated 45°. Ten layers, **6101 tiles, 45.1 MB**. | Layer | Origin | World size | Zooms | Tiles | Size | | --- | --- | --- | --- | --- | --- | -| overall (base) | 0, 0 | 116160 × 115968 | z0–3 | 85 | 0.3 MB | -| woods | 39936, 34825 | 24320 × 16365 | z2–7 | 466 | 4.2 MB | -| shoreline | 37184, 72904 | 24320 × 13680 | z2–7 | 506 | 3.1 MB | -| lighthouse | 27360, 61385 | 17600 × 16110 | z3–8 | 1580 | 16.2 MB | -| customs | 53600, 58752 | 16960 × 6529 | z3–8 | 646 | 9.3 MB | -| reserve | 46208, 64296 | 8960 × 5040 | z4–8 | 277 | 1.7 MB | -| shoreline-resort | 40192, 74716 | 8320 × 4680 | z4–9 | 924 | 2.4 MB | -| streets | 67584, 26111 | 7040 × 4481 | z4–9 | 713 | 2.8 MB | -| interchange | 70112, 54098 | 6080 × 3420 | z4–9 | 392 | 3.3 MB | -| customs-dorms | 63040, 61190 | 4480 × 5108 | z5–9 | 507 | 1.9 MB | +| overall (base) | 0, 0 | 117824 × 117824 | z0–3 | 85 | 0.2 MB | +| woods | 38272, 37001 | 24320 × 16365 | z2–7 | 486 | 4.2 MB | +| shoreline | 41920, 75016 | 24320 × 13680 | z2–7 | 498 | 3.1 MB | +| lighthouse | 30560, 65929 | 17600 × 16110 | z3–8 | 1639 | 16.2 MB | +| customs | 55072, 58944 | 16960 × 6529 | z3–8 | 623 | 9.3 MB | +| reserve | 48704, 66408 | 8960 × 5040 | z4–8 | 287 | 1.7 MB | +| shoreline-resort | 44544, 77724 | 8320 × 4680 | z6–9 | 871 | 2.4 MB | +| streets | 63104, 25215 | 7040 × 4481 | z4–9 | 707 | 2.8 MB | +| interchange | 70368, 52434 | 6080 × 3420 | z6–9 | 375 | 3.3 MB | +| customs-dorms | 64768, 60806 | 4480 × 5108 | z6–9 | 530 | 1.9 MB | Verified across zoom 0–9: zero broken tiles; every tile carries `?v=`; the focused map is topmost in all seven tested cases. diff --git a/PLAN.md b/PLAN.md index 8483d5c..5c160e6 100644 --- a/PLAN.md +++ b/PLAN.md @@ -89,11 +89,11 @@ Licence in both files: **CC BY-NC-SA 4.0**, "Made by re3mr.com". ### The world canvas (A5) -The base is `overall.jpeg`, rotated **35°** to put north at the top. An +The base is `overall.jpeg`, rotated **45°** to put north at the top. An aspect-ratio fit of the Customs zone outline first suggested 31°, but that polygon encloses more than the playable strip so the estimate ran low, and attempts to register the two polygons directly failed — the zone outline is -dashed and will not flood-fill. 35° is therefore a visual judgement. +dashed and will not flood-fill. 45° is therefore the current visual starting point. `tools/retilt.py` makes it a one-number change, converting every placement through the old and new angles. The rotation maths itself is verified sub-pixel against PIL in `rotate_point`. @@ -146,7 +146,7 @@ sources/ build/ web/tiles/ gitignored (except sources/overall/) | Excluding `Map Borders` also removes the playable-area boundary outline | Customs no longer shows the dotted play-area edge; the out-of-bounds grey-out still marks it | Accepted. Revisit only if the boundary is missed | | ~~No retina / DPR tiles~~ | ~~Soft on high-DPI screens~~ | **Fixed** — `DENSITY_BOOST` requests one level deeper; 0.56 → 1.33 source px per device px at DPR 1.5 | | Each map has a hard detail ceiling | Upscaling past a map's native level is browser-side and blurry | Inherent. Customs' embedded terrain smart object is 7832 × 3720 placed 1:1 — no further source detail exists | -| The 35° tilt is a visual judgement, not a measurement | Alignment may still be slightly off | Both automated approaches failed (see DOCUMENTATION.md §11). `retilt.py` makes it a one-number change | +| The 45° tilt is a visual judgement, not a measurement | Alignment may still be slightly off | The interactive center-anchor editor now supports manual tuning; `retilt.py` changes the global angle | | Placement accuracy varies | Lighthouse and Shoreline are noticeably offset | Focus-based stacking stops overlaps hiding maps; nudge `place` when it matters | | Some maps keep dark surrounds baked into their art | Streets, Lighthouse, Shoreline show dark edges | Identifiable plates stripped; the rest is part of the source renders | | `flyToBounds` depends on `requestAnimationFrame` | Picker doesn't move the view in a non-compositing tab | Cosmetic; not seen in a real browser | diff --git a/README.md b/README.md index a9a9a9f..c360b76 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,10 @@ web/tiles/ gitignored — generated tiles ## How the shared canvas works -The base is `sources/overall/overall.jpeg`, rotated **35°** so north is up. +The base is `sources/overall/overall.jpeg`, rotated **45°** so north is up. (An aspect-ratio fit of the Customs zone outline suggested 31°, but the zone -polygon encloses more than the playable strip so that estimate ran low; 35° -lines the maps up better by eye. Adjust with `tools/retilt.py`, which converts +polygon encloses more than the playable strip so that estimate ran low; 45° +is the current visual starting point. Adjust with `tools/retilt.py`, which converts every placement through the old and new angles so geography is preserved.) World pixels are overall-map pixels × `overallScale` (64), which puts Customs @@ -93,6 +93,19 @@ Each map is tiled only down to its **native level** — the deepest zoom still downscaling its source — and has a `minZoom` below which it doesn't load at all. So the overview is just the base map, and detail maps appear as you go in. +### Interactive placement + +Select a detail map, choose **Edit placement**, then drag its yellow center +anchor or enter exact X/Y values. Width and Height can be changed independently +to stretch the map horizontally or vertically around that anchor. All changes +preview live without rebuilding. **Save & rebuild** writes the new geometry to +`maps.json`, rebuilds only that map, and reloads its versioned tiles. Start the +writable local server with: + +```bash +pwsh server/run.ps1 -Port 8081 -Editable +``` + ## No black gaps The base map is the backdrop. It is 85 tiles / 0.3 MB, always resident, and @@ -121,7 +134,7 @@ map you came to see. ## Current maps -Base: `overall.jpeg` 1308 × 1296 → 1816 × 1812 rotated → world 116 160 × 115 968. +Base: `overall.jpeg` 1308 × 1296 → 1842 × 1842 rotated → world 117 824 × 117 824. | Map | PSD | Base layers | | --- | --- | --- | @@ -140,7 +153,7 @@ There is **no shared naming convention** between these PSDs — see ## Tile resolution and sharpness -World `maxZoom` is 9, set so the whole 116 160 px world fits the pyramid. Each +World `maxZoom` is 9, set so the whole 117 824 px world fits the pyramid. Each map is tiled only to its own **native level** — the deepest zoom still downscaling its source — recorded as `maxNativeZoom` in `world.json`. The base map is native at z3; detail maps land at z7–z9. diff --git a/docs/adding-a-map.md b/docs/adding-a-map.md index d278910..361e696 100644 --- a/docs/adding-a-map.md +++ b/docs/adding-a-map.md @@ -71,7 +71,8 @@ solid fills, so they may need `excludeLayers`. | `baseLayers` | slash-paths from the document root; everything else is hidden | | `excludeLayers` | layer names to hide anywhere inside the kept set | | `crop` | `[x0, y0, x1, y1]` in PSD pixels, or `null` for the full canvas | -| `place` | where it sits on the world map — see step 4 | +| `minZoom` | optional close-view reveal threshold for nested detail maps; otherwise derived from size | +| `place` | center anchor and dimensions on the world map; optional `h` enables independent stretch — see step 4 | | `pxPerMeter` | optional, from the map's scale bar; recorded for later use | --- @@ -98,7 +99,7 @@ A failed map no longer aborts the batch; check the summary at the end. ## 4. Position it on the world map The base of the canvas is `sources/overall/overall.jpeg`, rotated by -`world.rotate` (35°) so north is up. `place` is in **rotated overall-map +`world.rotate` (45°) so north is up. `place` is in **rotated overall-map pixels** — the north-up image you actually look at. ```bash @@ -186,3 +187,11 @@ Each map is also only tiled down to its **native level** — the deepest zoom at which we are still downscaling its source. Past that the browser upscales, which looks the same as upscaling during the build but without storing tiles. `minZoom` likewise stops a map loading while it would be a speck on screen. +The build derives it from the placed size by default. Set it explicitly for a +nested detail view that should stay out of the main view until the user zooms +closer; the configured value can only raise the automatic threshold. + +For visual placement, run `pwsh server/run.ps1 -Editable`, select the map in +the viewer, and use **Edit placement**. Dragging the center anchor previews the +move immediately. Width and Height stretch it independently around that anchor; +**Save & rebuild** updates `maps.json` and retiles that map. diff --git a/maps.json b/maps.json index 923dcde..ce73ab6 100644 --- a/maps.json +++ b/maps.json @@ -6,10 +6,10 @@ "$comment_world": "The overall map is the base everything else sits on. It is rotated by `rotate` degrees (counter-clockwise) to put north at the top; 31 deg was measured from the Customs zone outline, whose detail map is north-up and 2.6:1 east-west. `overallScale` is world pixels per overall-map pixel, set so Customs lands at its native 7832 px.", "world": { "image": "sources/overall/overall.jpeg", - "rotate": 35.0, + "rotate": 45.0, "overallScale": 64 }, - "$comment_place": "`place` is in ROTATED overall-map pixels (the north-up image, which is what tools/place_preview.py draws a grid over): cx/cy = centre, w = width. Positions are deliberately approximate -- the game's maps do not tile exactly onto the satellite view.", + "$comment_place": "`place` is in ROTATED overall-map pixels (the north-up image, which is what tools/place_preview.py draws a grid over): cx/cy = centre, w = width, optional h = explicit height for independent vertical/horizontal stretch. Positions are deliberately approximate -- the game's maps do not tile exactly onto the satellite view.", "maps": [ { "id": "customs", @@ -29,9 +29,10 @@ ], "pxPerMeter": 7.39, "place": { - "cx": 970, - "cy": 969, - "w": 265 + "cx": 998.79, + "cy": 979.34, + "w": 281.5, + "h": 142.0 } }, { @@ -42,10 +43,12 @@ "LOCATION" ], "crop": null, + "minZoom": 6, "place": { - "cx": 1020, - "cy": 996, - "w": 70 + "cx": 1047.0, + "cy": 990.0, + "w": 70.0, + "h": 79.81 } }, { @@ -58,9 +61,10 @@ ], "crop": null, "place": { - "cx": 814, - "cy": 672, - "w": 380 + "cx": 833.68, + "cy": 766.15, + "w": 450.0, + "h": 450.0 } }, { @@ -71,10 +75,12 @@ "3DRENDER" ], "crop": null, + "minZoom": 6, "place": { - "cx": 1143, - "cy": 872, - "w": 95 + "cx": 1202.97, + "cy": 849.77, + "w": 218.5, + "h": 122.9 } }, { @@ -86,9 +92,10 @@ ], "crop": null, "place": { - "cx": 792, - "cy": 1044, - "w": 140 + "cx": 848.04, + "cy": 1113.56, + "w": 238.0, + "h": 132.75 } }, { @@ -100,9 +107,10 @@ ], "crop": null, "place": { - "cx": 771, - "cy": 1246, - "w": 380 + "cx": 852.5, + "cy": 1340.5, + "w": 460.0, + "h": 333.75 } }, { @@ -114,10 +122,12 @@ "BASEMAP+2DLAYERS" ], "crop": null, + "minZoom": 6, "place": { - "cx": 693, - "cy": 1204, - "w": 130 + "cx": 1045.65, + "cy": 1220.14, + "w": 130.0, + "h": 73.12 } }, { @@ -129,9 +139,10 @@ ], "crop": null, "place": { - "cx": 565, - "cy": 1085, - "w": 275 + "cx": 546.0, + "cy": 1198.5, + "w": 375.0, + "h": 421.72 } }, { @@ -143,9 +154,10 @@ ], "crop": null, "place": { - "cx": 1111, - "cy": 443, - "w": 110 + "cx": 1021.9, + "cy": 433.27, + "w": 220.0, + "h": 140.02 } } ] diff --git a/server/run.ps1 b/server/run.ps1 index 2866852..63d2d95 100644 --- a/server/run.ps1 +++ b/server/run.ps1 @@ -2,13 +2,17 @@ # # pwsh server/run.ps1 # port 8080 # pwsh server/run.ps1 -Port 9000 +# pwsh server/run.ps1 -Port 9000 -Editable # enable placement saves # # Uses Caddy when server/caddy.exe is present (get it with get-caddy.ps1) and # falls back to the dependency-free serve.py otherwise. Caddy is roughly 3x # faster at low concurrency and does not fall over at high concurrency -- see # the table in the README. -param([int]$Port = 8080) +param( + [int]$Port = 8080, + [switch]$Editable +) $ErrorActionPreference = 'Stop' $here = Split-Path -Parent $MyInvocation.MyCommand.Path @@ -24,7 +28,9 @@ $ip = (Get-NetIPConfiguration | if (-not $ip) { $ip = '127.0.0.1' } $caddy = Join-Path $here 'caddy.exe' -$engine = if (Test-Path $caddy) { 'caddy' } else { 'serve.py (slower)' } +$engine = if ($Editable) { 'serve.py (placement editing enabled)' } + elseif (Test-Path $caddy) { 'caddy' } + else { 'serve.py (slower)' } Write-Host "" Write-Host " serving with $engine" @@ -34,11 +40,11 @@ Write-Host "" Write-Host " Ctrl+C to stop" Write-Host "" -if (Test-Path $caddy) { +if (-not $Editable -and (Test-Path $caddy)) { $env:TARKOVMAP_PORT = "$Port" & $caddy run --config (Join-Path $here 'Caddyfile') } else { - Write-Host " (run get-caddy.ps1 for the faster server)" + if (-not $Editable) { Write-Host " (run get-caddy.ps1 for the faster server)" } python (Join-Path $here 'serve.py') $Port } diff --git a/server/serve.py b/server/serve.py index c1e42f8..a5c489e 100644 --- a/server/serve.py +++ b/server/serve.py @@ -14,12 +14,22 @@ from __future__ import annotations import functools import http.server +import json +import math +import os import socket import socketserver +import subprocess import sys +import threading from pathlib import Path +from urllib.parse import urlsplit -WEB = Path(__file__).resolve().parent.parent / "web" +ROOT = Path(__file__).resolve().parent.parent +WEB = ROOT / "web" +CONFIG = ROOT / "maps.json" +BUILD_TOOL = ROOT / "tools" / "build.py" +CONFIG_LOCK = threading.Lock() class Handler(http.server.SimpleHTTPRequestHandler): @@ -33,6 +43,45 @@ class Handler(http.server.SimpleHTTPRequestHandler): protocol_version = "HTTP/1.1" timeout = 10 # don't let idle keep-alive sockets pin threads forever + def send_json(self, status: int, payload: dict) -> None: + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: # noqa: N802 - stdlib handler API + if urlsplit(self.path).path != "/api/placement": + self.send_json(404, {"error": "unknown API endpoint"}) + return + + try: + length = int(self.headers.get("Content-Length", "0")) + if not 0 < length <= 16_384: + raise ValueError("request body must be between 1 and 16384 bytes") + payload = json.loads(self.rfile.read(length)) + map_id = payload["id"] + cx, cy = float(payload["cx"]), float(payload["cy"]) + width, height = float(payload["w"]), float(payload["h"]) + if not isinstance(map_id, str) or not map_id or map_id == "overall": + raise ValueError("id must name a detail map") + if not all(math.isfinite(v) for v in (cx, cy, width, height)): + raise ValueError("cx, cy, w and h must be finite numbers") + if width <= 0 or height <= 0: + raise ValueError("w and h must be greater than zero") + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: + self.send_json(400, {"error": str(exc)}) + return + + try: + result = save_placement(map_id, cx, cy, width, height) + except PlacementError as exc: + self.send_json(exc.status, {"error": str(exc)}) + return + self.send_json(200, result) + def end_headers(self): if "/tiles/" in self.path: self.send_header("Cache-Control", "public, max-age=604800, immutable") @@ -44,6 +93,92 @@ class Handler(http.server.SimpleHTTPRequestHandler): pass # one line per tile is unreadable +class PlacementError(Exception): + def __init__(self, message: str, status: int = 500): + super().__init__(message) + self.status = status + + +def _write_config(raw: dict) -> None: + temporary = CONFIG.with_name(f"{CONFIG.name}.{os.getpid()}.tmp") + temporary.write_text( + json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + temporary.replace(CONFIG) + + +def save_placement(map_id: str, cx: float, cy: float, width: float, height: float) -> dict: + """Persist one map's center and dimensions, then rebuild its tile pyramid.""" + with CONFIG_LOCK: + original = CONFIG.read_text(encoding="utf-8") + raw = json.loads(original) + selected = next((m for m in raw["maps"] if m["id"] == map_id), None) + if selected is None: + raise PlacementError(f"unknown map id: {map_id}", 404) + + world_path = WEB / "data" / "world.json" + if world_path.exists(): + world = json.loads(world_path.read_text(encoding="utf-8")) + max_x = world["worldSize"][0] / world["overallScale"] + max_y = world["worldSize"][1] / world["overallScale"] + if not 0 <= cx <= max_x or not 0 <= cy <= max_y: + raise PlacementError( + f"center must remain inside the rotated overall map " + f"(x 0–{max_x:.0f}, y 0–{max_y:.0f})", + 400, + ) + if width > max_x * 2 or height > max_y * 2: + raise PlacementError( + f"map dimensions are too large (maximum {max_x * 2:.0f} × {max_y * 2:.0f})", + 400, + ) + + base = ROOT / "build" / map_id / "base.png" + if not base.exists(): + raise PlacementError( + f"{base.relative_to(ROOT)} is missing; export the map before saving placement", + 409, + ) + + selected["place"]["cx"] = round(cx, 2) + selected["place"]["cy"] = round(cy, 2) + selected["place"]["w"] = round(width, 2) + selected["place"]["h"] = round(height, 2) + _write_config(raw) + + try: + proc = subprocess.run( + [sys.executable, str(BUILD_TOOL), map_id, "--tiles-only"], + cwd=ROOT, + capture_output=True, + text=True, + timeout=300, + check=False, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + CONFIG.write_text(original, encoding="utf-8") + raise PlacementError(f"tile rebuild could not finish; maps.json was restored: {exc}") \ + from exc + if proc.returncode: + CONFIG.write_text(original, encoding="utf-8") + raise PlacementError( + "tile rebuild failed; maps.json was restored\n" + + (proc.stderr or proc.stdout)[-2000:] + ) + + manifest = json.loads(world_path.read_text(encoding="utf-8")) + entry = next(m for m in manifest["maps"] if m["id"] == map_id) + return { + "ok": True, + "id": map_id, + "cx": selected["place"]["cx"], + "cy": selected["place"]["cy"], + "w": selected["place"]["w"], + "h": selected["place"]["h"], + "map": entry, + } + + class Server(socketserver.ThreadingTCPServer): allow_reuse_address = True daemon_threads = True diff --git a/tools/common.py b/tools/common.py index 28e28a5..9624335 100644 --- a/tools/common.py +++ b/tools/common.py @@ -114,7 +114,12 @@ class Config: """ p = m["place"] s = self.overall_scale - return {"cx": p["cx"] * s, "cy": p["cy"] * s, "width": p["w"] * s} + return { + "cx": p["cx"] * s, + "cy": p["cy"] * s, + "width": p["w"] * s, + "height": p["h"] * s if p.get("h") is not None else None, + } def rotated_base_size(self) -> tuple[int, int]: return rotated_size(*self.base_size(), self.rotate) diff --git a/tools/place_preview.py b/tools/place_preview.py index 66193cc..a88989e 100644 --- a/tools/place_preview.py +++ b/tools/place_preview.py @@ -41,13 +41,16 @@ def main() -> None: p = m.get("place") if not p: continue - src = BUILD / m["id"] / "base.png" - aspect = 0.6 - if src.exists(): - with Image.open(src) as s: - cw, ch = (m["crop"][2] - m["crop"][0], m["crop"][3] - m["crop"][1]) \ - if m.get("crop") else s.size - aspect = ch / cw + if p.get("h") is not None: + aspect = p["h"] / p["w"] + else: + src = BUILD / m["id"] / "base.png" + aspect = 0.6 + if src.exists(): + with Image.open(src) as s: + cw, ch = (m["crop"][2] - m["crop"][0], m["crop"][3] - m["crop"][1]) \ + if m.get("crop") else s.size + aspect = ch / cw hw = p["w"] / 2.0 hh = hw * aspect box = [p["cx"] - hw, p["cy"] - hh, p["cx"] + hw, p["cy"] + hh] diff --git a/tools/tile.py b/tools/tile.py index 664a311..8b74448 100644 --- a/tools/tile.py +++ b/tools/tile.py @@ -33,6 +33,35 @@ WEBP = {"format": "WEBP", "quality": 82, "method": 4} MIN_VISIBLE_PX = 160 # a map below this on screen isn't worth loading +def minimum_zoom(m: dict, zmax: int, native_level: int, world_width: float) -> int: + """First zoom at which a detail layer may be shown and requested. + + The automatic threshold keeps tiny maps out of the overview. A map can + raise that threshold with ``minZoom`` in maps.json when it is a nested + detail view that should only appear once the user is close to it. + """ + if m["id"] == WORLD_ID: + return 0 + + automatic = max(0, math.ceil(zmax + math.log2(MIN_VISIBLE_PX / world_width))) \ + if world_width > 0 else 0 + automatic = min(automatic, native_level) + + configured = m.get("minZoom") + if configured is None: + return automatic + if type(configured) is not int or not 0 <= configured <= zmax: + raise SystemExit( + f"[{m['id']}] minZoom must be an integer from 0 to {zmax}, got {configured!r}" + ) + if configured > native_level: + raise SystemExit( + f"[{m['id']}] minZoom {configured} is above its native tile level " + f"{native_level}; lower minZoom or increase the map's source/placed resolution" + ) + return max(automatic, configured) + + def load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float, float, float]]: """Return (image, world rect x0,y0,x1,y1) for a map or the base layer.""" if m["id"] == WORLD_ID: @@ -52,7 +81,7 @@ def load_source(cfg: Config, m: dict) -> tuple[Image.Image, tuple[float, float, pl = cfg.placement(m) tw = pl["width"] - th = tw * img.size[1] / img.size[0] + th = pl["height"] if pl["height"] is not None else tw * img.size[1] / img.size[0] return img, (pl["cx"] - tw / 2, pl["cy"] - th / 2, pl["cx"] + tw / 2, pl["cy"] + th / 2) @@ -69,10 +98,8 @@ def tile_map(cfg: Config, m: dict) -> dict: native_level = max(0, min(zmax, math.floor(native + 0.25))) # Don't bother rendering the map when it would be a speck on screen. - min_zoom = max(0, math.ceil(zmax + math.log2(MIN_VISIBLE_PX / tw))) if tw > 0 else 0 - min_zoom = min(min_zoom, native_level) - if m["id"] == WORLD_ID: - min_zoom = 0 + # Nested detail views can opt into a later reveal with maps.json minZoom. + min_zoom = minimum_zoom(m, zmax, native_level, tw) gx, gy = math.floor(x0 / cell), math.floor(y0 / cell) pad_x, pad_y = x0 - gx * cell, y0 - gy * cell diff --git a/web/app.js b/web/app.js index 9411a0b..eb8ff97 100644 --- a/web/app.js +++ b/web/app.js @@ -38,6 +38,22 @@ const rectOf = (m) => L.latLngBounds( [m.origin[1] + m.size[1], m.origin[0] + m.size[0]], ); +const centerOf = (m) => L.latLng( + m.origin[1] + m.size[1] / 2, + m.origin[0] + m.size[0] / 2, +); + +const geometryOf = (m) => ({ + center: centerOf(m), + width: m.size[0], + height: m.size[1], +}); + +const rectAt = (geometry) => L.latLngBounds( + [geometry.center.lat - geometry.height / 2, geometry.center.lng - geometry.width / 2], + [geometry.center.lat + geometry.height / 2, geometry.center.lng + geometry.width / 2], +); + function readHash() { const p = location.hash.replace(/^#/, '').split('/'); if (p.length !== 3) return null; @@ -96,22 +112,50 @@ async function main() { const baseZ = new Map(stackOrder.map((m, i) => [m.id, 2 + i])); const TOP_Z = 2 + stackOrder.length; const layers = new Map(); + const panes = new Map(); + const previewGeometry = new Map(detail.map((m) => [m.id, geometryOf(m)])); const focus = (id) => { - for (const [mid, layer] of layers) { + for (const [mid, pane] of panes) { if (mid === base.id) continue; - layer.setZIndex(mid === id ? TOP_Z : baseZ.get(mid)); + pane.style.zIndex = String(mid === id ? 300 + TOP_Z : 300 + baseZ.get(mid)); } }; + const updatePreviewTransform = (m) => { + const pane = panes.get(m.id); + if (!pane) return; + const saved = geometryOf(m); + const preview = previewGeometry.get(m.id) ?? saved; + const scale = 2 ** (map.getZoom() - ZMAX); + const dx = (preview.center.lng - saved.center.lng) * scale; + const dy = (preview.center.lat - saved.center.lat) * scale; + const sx = preview.width / saved.width; + const sy = preview.height / saved.height; + const origin = map.latLngToLayerPoint(saved.center); + pane.style.transformOrigin = `${origin.x}px ${origin.y}px`; + pane.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`; + }; + + const updatePreviewTransforms = () => detail.forEach(updatePreviewTransform); + for (const m of world.maps) { // The base map is the backdrop: it is a handful of tiles, always loaded, // and Leaflet upscales it past its native level -- so a gap while detail // tiles load shows blurry terrain rather than the page background. const isBase = !!m.base; + let paneName; + if (!isBase) { + paneName = `map-${m.id}`; + const pane = map.createPane(paneName); + pane.style.zIndex = String(300 + baseZ.get(m.id)); + pane.style.pointerEvents = 'none'; + panes.set(m.id, pane); + } const layer = new OffsetTileLayer(`tiles/${m.id}/{z}/{x}/{y}.webp`, { cell: m.cell, bounds: rectOf(m), + pane: isBase ? 'tilePane' : paneName, version: m.version, baseTileSize: world.tileSize, tileSize: world.tileSize / 2 ** boost, @@ -132,12 +176,127 @@ async function main() { // --- picker ----------------------------------------------------------- const list = document.getElementById('maplist'); + const editButton = document.getElementById('edit-placement'); + const editorPanel = document.getElementById('placement-editor'); + const editorName = document.getElementById('placement-name'); + const xInput = document.getElementById('placement-x'); + const yInput = document.getElementById('placement-y'); + const widthInput = document.getElementById('placement-width'); + const heightInput = document.getElementById('placement-height'); + const aspectOutput = document.getElementById('placement-aspect'); + const resetButton = document.getElementById('placement-reset'); + const saveButton = document.getElementById('placement-save'); + const status = document.getElementById('placement-status'); + const byId = new Map(world.maps.map((m) => [m.id, m])); + const editor = { + selectedId: null, + active: false, + marker: null, + outline: null, + }; + + const showStatus = (message, isError = false) => { + status.textContent = message; + status.dataset.error = String(isError); + }; + + const writeGeometry = (geometry) => { + xInput.value = (geometry.center.lng / world.overallScale).toFixed(3); + yInput.value = (geometry.center.lat / world.overallScale).toFixed(3); + widthInput.value = (geometry.width / world.overallScale).toFixed(3); + heightInput.value = (geometry.height / world.overallScale).toFixed(3); + aspectOutput.textContent = `Aspect ratio ${(geometry.width / geometry.height).toFixed(3)}:1`; + }; + + const setPreviewGeometry = (m, geometry) => { + const normalized = { ...geometry, center: L.latLng(geometry.center) }; + previewGeometry.set(m.id, normalized); + updatePreviewTransform(m); + editor.marker?.setLatLng(normalized.center); + editor.outline?.setBounds(rectAt(normalized)); + writeGeometry(normalized); + }; + + const clearEditorLayers = () => { + if (editor.marker) map.removeLayer(editor.marker); + if (editor.outline) map.removeLayer(editor.outline); + editor.marker = null; + editor.outline = null; + }; + + const resetPreview = (m) => { + if (!m) return; + previewGeometry.set(m.id, geometryOf(m)); + updatePreviewTransform(m); + }; + + const closeEditor = () => { + const m = byId.get(editor.selectedId); + resetPreview(m); + clearEditorLayers(); + editor.active = false; + editorPanel.hidden = true; + editButton.setAttribute('aria-pressed', 'false'); + editButton.textContent = editor.selectedId ? 'Edit placement' : 'Select a map to edit'; + showStatus(''); + }; + + const openEditor = (m) => { + if (!m || m.base) return; + const previous = byId.get(editor.selectedId); + if (previous && previous.id !== m.id) resetPreview(previous); + clearEditorLayers(); + editor.selectedId = m.id; + editor.active = true; + editorPanel.hidden = false; + editButton.disabled = false; + editButton.textContent = 'Close placement editor'; + editButton.setAttribute('aria-pressed', 'true'); + editorName.textContent = m.name; + showStatus('Unsaved changes stay in this preview until you save.'); + + const geometry = previewGeometry.get(m.id) ?? geometryOf(m); + editor.outline = L.rectangle(rectAt(geometry), { + color: '#ffe66d', + weight: 2, + dashArray: '8 7', + fill: false, + interactive: false, + }).addTo(map); + editor.marker = L.marker(geometry.center, { + draggable: true, + zIndexOffset: 10000, + icon: L.divIcon({ className: 'placement-anchor', iconSize: [28, 28] }), + }).addTo(map); + editor.marker.on('drag', (event) => setPreviewGeometry(m, { + ...previewGeometry.get(m.id), + center: event.target.getLatLng(), + })); + editor.marker.on('dragend', () => showStatus('Ready to save and rebuild.')); + writeGeometry(geometry); + focus(m.id); + }; + + const selectTarget = (m) => { + const previous = byId.get(editor.selectedId); + if (editor.active && previous && previous.id !== m.id) resetPreview(previous); + editor.selectedId = m.base ? null : m.id; + editButton.disabled = !!m.base; + editButton.textContent = m.base ? 'Select a map to edit' : 'Edit placement'; + buttons.forEach((b) => { b.dataset.selected = String(b.dataset.id === m.id); }); + if (editor.active) { + if (m.base) closeEditor(); + else openEditor(m); + } + }; + const targets = [base, ...world.maps.filter((m) => !m.base)]; const buttons = targets.map((m) => { const b = document.createElement('button'); b.textContent = m.base ? 'Overview' : m.name; b.dataset.id = m.id; b.addEventListener('click', () => { + selectTarget(m); map.flyToBounds(rectOf(m), { padding: [24, 24], duration: 0.7 }); if (window.matchMedia('(max-width: 640px)').matches) { document.getElementById('panel').open = false; @@ -147,6 +306,77 @@ async function main() { return b; }); + editButton.setAttribute('aria-pressed', 'false'); + editButton.textContent = 'Select a map to edit'; + editButton.addEventListener('click', () => { + if (editor.active) closeEditor(); + else openEditor(byId.get(editor.selectedId)); + }); + + const applyInputs = () => { + const m = byId.get(editor.selectedId); + const cx = Number(xInput.value); + const cy = Number(yInput.value); + const width = Number(widthInput.value); + const height = Number(heightInput.value); + if (!m || ![cx, cy, width, height].every(Number.isFinite) || width <= 0 || height <= 0) return; + setPreviewGeometry(m, { + center: L.latLng(cy * world.overallScale, cx * world.overallScale), + width: width * world.overallScale, + height: height * world.overallScale, + }); + showStatus('Ready to save and rebuild.'); + }; + xInput.addEventListener('input', applyInputs); + yInput.addEventListener('input', applyInputs); + widthInput.addEventListener('input', applyInputs); + heightInput.addEventListener('input', applyInputs); + + resetButton.addEventListener('click', () => { + const m = byId.get(editor.selectedId); + if (!m) return; + setPreviewGeometry(m, geometryOf(m)); + showStatus('Reset to the last saved center.'); + }); + + saveButton.addEventListener('click', async () => { + const m = byId.get(editor.selectedId); + const geometry = m && previewGeometry.get(m.id); + if (!m || !geometry) return; + saveButton.disabled = true; + resetButton.disabled = true; + showStatus('Saving maps.json and rebuilding this map…'); + try { + const response = await fetch('api/placement', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id: m.id, + cx: geometry.center.lng / world.overallScale, + cy: geometry.center.lat / world.overallScale, + w: geometry.width / world.overallScale, + h: geometry.height / world.overallScale, + }), + }); + const responseText = await response.text(); + let result; + try { result = JSON.parse(responseText); } catch { result = {}; } + if (!response.ok) throw new Error( + result.error || 'This server is read-only; start it with server/run.ps1 -Editable', + ); + showStatus('Saved. Reloading rebuilt tiles…'); + const z = Math.round(map.getZoom() * 4) / 4; + history.replaceState( + null, '', `#${z}/${Math.round(geometry.center.lat)}/${Math.round(geometry.center.lng)}`, + ); + location.reload(); + } catch (error) { + showStatus(`Save failed: ${error.message}`, true); + saveButton.disabled = false; + resetButton.disabled = false; + } + }); + const syncUI = () => { const c = map.getCenter(); // Smallest non-base map containing the centre wins -- Dorms beats Customs. @@ -155,12 +385,13 @@ async function main() { .sort((a, b) => a.size[0] * a.size[1] - b.size[0] * b.size[1])[0]; buttons.forEach((b) => b.setAttribute( 'aria-current', String(hit ? hit.id === b.dataset.id : b.dataset.id === base.id))); - focus(hit?.id); + focus(editor.active ? editor.selectedId : hit?.id); const z = Math.round(map.getZoom() * 4) / 4; history.replaceState(null, '', `#${z}/${Math.round(c.lat)}/${Math.round(c.lng)}`); }; map.on('moveend zoomend', syncUI); + map.on('move zoom zoomend', updatePreviewTransforms); const h = readHash(); if (h) map.setView([h.y, h.x], h.z); diff --git a/web/index.html b/web/index.html index e0c8e26..2ff24b4 100644 --- a/web/index.html +++ b/web/index.html @@ -14,6 +14,27 @@
Maps +
+ + +
Loading…
diff --git a/web/style.css b/web/style.css index ee0a5e6..2bf5df1 100644 --- a/web/style.css +++ b/web/style.css @@ -88,6 +88,86 @@ html, body { #maplist button[aria-current="true"] { color: var(--accent); } #maplist button[aria-current="true"]::before { content: "●"; font-size: 9px; } #maplist button:not([aria-current="true"])::before { content: "○"; font-size: 9px; color: var(--muted); } +#maplist button[data-selected="true"] { background: #ffffff12; } + +/* --- interactive placement editor ---------------------------------- */ + +#placement-tools { + border-top: 1px solid var(--line); + padding: 10px; +} + +#placement-tools button, +#placement-tools input { + font: inherit; +} + +#edit-placement, +.placement-actions button { + min-height: 38px; + border: 1px solid var(--line); + border-radius: 5px; + color: var(--text); + background: #2a3038; + cursor: pointer; +} + +#edit-placement { width: 100%; } +#edit-placement:disabled { cursor: default; opacity: .45; } +#edit-placement[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } + +#placement-editor { padding-top: 10px; } +#placement-editor p { margin: 5px 0 9px; color: var(--muted); font-size: 12px; } + +.coordinate-fields, +.placement-actions { + display: flex; + gap: 7px; +} + +.coordinate-fields label { flex: 1; color: var(--muted); font-size: 11px; } +.coordinate-fields input { + display: block; + width: 100%; + margin-top: 3px; + padding: 6px; + border: 1px solid var(--line); + border-radius: 4px; + background: #14171c; + color: var(--text); +} + +.size-fields { margin-top: 7px; } +#placement-aspect { + display: block; + margin-top: 5px; + color: var(--muted); + font-size: 11px; +} + +.placement-actions { margin-top: 8px; } +.placement-actions button { flex: 1; padding: 6px 8px; } +#placement-save { background: #27513a; border-color: #3f7957; } +#placement-status { display: block; min-height: 17px; margin-top: 7px; color: var(--muted); font-size: 11px; } +#placement-status[data-error="true"] { color: #ff9b94; } + +.placement-anchor { + width: 28px !important; + height: 28px !important; + margin: -14px 0 0 -14px !important; + border: 2px solid #ffe66d; + border-radius: 50%; + background: #111a; + box-shadow: 0 0 0 2px #111a; +} +.placement-anchor::before, +.placement-anchor::after { + content: ""; + position: absolute; + background: #ffe66d; +} +.placement-anchor::before { left: 12px; top: -7px; width: 2px; height: 38px; } +.placement-anchor::after { left: -7px; top: 12px; width: 38px; height: 2px; } /* --- leaflet chrome --------------------------------------------------- */