LuminaWebsite/assets/map/scripts/download_all_maps.py
Maaxxs c5213b5736 Karte: replace the tactical map with the interactive map viewer
The Karte page now embeds a standalone viewer (assets/map/) covering all ten
regions - Verteron, Altgard, Elthen, Morheim, Poeta, Ishalgen and the
Reshanta maps - with markers and category filters from interactivemap.app.
map.php loads it in an iframe because its stylesheet restyles body, button
and * globally and would otherwise break the site layout.

The tile, marker and icon data (~230 MB, ~39,000 files) is kept out of Git
and uploaded by FTP; the README explains where it comes from.

Removed with it: own markers and categories, tactic layers, the in-browser
map builder, the tile/stitch/viewer tools, the bundled Leaflet, the four map
tables in schema.sql and the map.manage / map.tactics permissions. Existing
databases keep their old map tables untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 06:54:17 +02:00

239 lines
No EOL
8.7 KiB
Python

#!/usr/bin/env python3
"""Download all Aion 2 map tiles from interactivemap.app.
Discovers all available maps, downloads their tiles using the actual tile
directory paths from the API (which may differ from map slugs). Generates
tile manifests by attempting to download and tracking which tiles exist.
Also generates a local maps.json for the viewer to use (avoids CORS issues).
Usage:
python download_all_maps.py # Download all maps
python download_all_maps.py --map verteron # Download specific map only
python download_all_maps.py -o ./tiles # Custom output directory
"""
import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
API_BASE = "https://interactivemap.app/aion2/maps/imapp"
TILES_BASE = "https://interactivemap.app/aion2/maps/imapp/uploads/tiles"
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) aion2-map-downloader/2.0"
def http_get_json(url: str, retries: int = 3) -> object:
"""GET a JSON endpoint with retry logic."""
last_err = None
for attempt in range(1, retries + 1):
try:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=30) as resp:
text = resp.read().decode("utf-8")
if text.lstrip()[:1] == "<":
raise ValueError("HTML fallback received instead of JSON")
return json.loads(text)
except (urllib.error.URLError, ValueError, TimeoutError) as exc:
last_err = exc
if attempt < retries:
time.sleep(1.5 * attempt)
raise RuntimeError(f"GET {url} failed after {retries} attempts: {last_err}")
def discover_maps() -> list:
"""Discover all available maps from the API."""
print("Discovering available maps...")
maps_data = http_get_json(f"{API_BASE}/api/getmaps")
# API returns a list of zones directly
maps = []
for zone in maps_data:
zone_name = zone.get("name", "Unknown") or "General"
for entry in zone.get("maps", []):
# Extract actual tile directory from tiles_url field
tiles_url = entry.get("tiles_url", "")
# Format: uploads/tiles/{dir}/{z}_{x}_{y}.jpg or uploads/tiles/{dir}/{subdir}/{z}_{x}_{y}.jpg
if tiles_url.startswith("uploads/tiles/"):
path_parts = tiles_url[len("uploads/tiles/"):].split("/")
tile_dir = "/".join(path_parts[:-1]) # Remove the {z}_{x}_{y}.jpg part
else:
tile_dir = entry.get("slug")
maps.append({
"id": str(entry.get("id")),
"slug": str(entry.get("slug")),
"name": entry.get("name"),
"zone": zone_name,
"tile_dir": tile_dir,
"min_zoom": int(entry.get("min_tiles_zoom", 0)),
"max_zoom": int(entry.get("max_tiles_zoom", 7))
})
print(f"Found {len(maps)} maps")
for m in maps:
print(f" {m['name']} (slug={m['slug']}, tiles={m['tile_dir']})")
return maps
def save_maps_list(maps, out_dir):
"""Save the maps list to a local JSON file for the viewer."""
# Save in both data root and scripts/../data for easy access
script_dir = os.path.dirname(os.path.abspath(__file__))
data_root = os.path.join(script_dir, "..", "data")
maps_json_path = os.path.join(data_root, "maps.json")
with open(maps_json_path, "w") as f:
json.dump({"maps": maps}, f, indent=2)
print(f"Saved maps list to {maps_json_path}")
def enumerate_tiles(min_z: int, max_z: int):
"""Yield (z, x, y) for every tile of zoom levels min_z..max_z."""
for z in range(min_z, max_z + 1):
n = 2 ** z
for x in range(n):
for y in range(n):
yield z, x, y
def fetch_tile(url: str, dest: str, retries: int) -> str:
"""Download a single tile. Returns status string."""
if os.path.exists(dest) and os.path.getsize(dest) > 0:
return "exists"
tmp = dest + ".part"
last_err = ""
for attempt in range(1, retries + 1):
try:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=30) as resp:
data = resp.read()
if not data:
last_err = "empty response"
else:
with open(tmp, "wb") as fh:
fh.write(data)
os.replace(tmp, dest)
return "ok"
except urllib.error.HTTPError as e:
if e.code == 404:
last_err = ""
return "missing"
last_err = f"HTTP {e.code}"
except Exception as e:
last_err = repr(e)
if attempt < retries:
time.sleep(0.5 * attempt)
try:
os.unlink(tmp)
except OSError:
pass
return f"error:{last_err}"
def download_map_tiles(map_info: dict, out_dir: str, workers: int = 16) -> None:
"""Download all tiles for a single map."""
slug = map_info["slug"]
tile_dir_name = map_info["tile_dir"]
min_z = max(2, map_info.get("min_zoom", 0))
max_z = min(6, map_info.get("max_zoom", 7))
print(f"\n{'='*60}")
print(f"Downloading tiles for: {map_info['name']} ({slug})")
print(f" Tile directory: {tile_dir_name}")
print(f" Zoom range: {min_z}-{max_z}")
print(f"{'='*60}")
map_out = os.path.join(out_dir, slug)
os.makedirs(map_out, exist_ok=True)
# Enumerate all possible tiles in the zoom range
tasks = list(enumerate_tiles(min_z, max_z))
total = len(tasks)
print(f" Total tile positions to check: {total}")
counts = {"ok": 0, "exists": 0, "missing": 0, "error": 0}
existing_tiles = []
done = 0
t0 = time.time()
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {}
for (z, x, y) in tasks:
url = f"{TILES_BASE}/{tile_dir_name}/{z}_{x}_{y}.jpg"
dest = os.path.join(map_out, f"{z}_{x}_{y}.jpg")
futures[pool.submit(fetch_tile, url, dest, 3)] = (z, x, y)
for fut in as_completed(futures):
z, x, y = futures[fut]
status = fut.result()
kind = status.split(":", 1)[0]
counts[kind] += 1
if kind == "ok" or kind == "exists":
existing_tiles.append(f"{z}_{x}_{y}")
done += 1
if done % max(1, total // 20) == 0 or done == total:
rate = done / max(time.time() - t0, 1e-6)
print(f" {done}/{total} ({rate:.1f}/s) "
f"ok={counts['ok']} cached={counts['exists']} missing={counts['missing']} err={counts['error']}",
flush=True)
# Generate manifest from successfully downloaded tiles
manifest_path = os.path.join(map_out, "tile_manifest.json")
with open(manifest_path, "w") as f:
json.dump({"tiles": existing_tiles}, f)
elapsed = time.time() - t0
print(f" Done in {elapsed:.0f}s: downloaded={counts['ok']} cached={counts['exists']} "
f"missing={counts['missing']} failed={counts['error']}")
print(f" Manifest saved with {len(existing_tiles)} existing tiles")
def main():
parser = argparse.ArgumentParser(description="Download all Aion 2 map tiles")
parser.add_argument("--map", type=str, default=None, help="Download specific map by slug only")
parser.add_argument("-o", "--out-dir", default="../data/tiles", help="Output directory for tiles")
parser.add_argument("-w", "--workers", type=int, default=16, help="Number of concurrent downloads")
args = parser.parse_args()
# Resolve output directory relative to script location
script_dir = os.path.dirname(os.path.abspath(__file__))
out_dir = os.path.join(script_dir, args.out_dir) if not os.path.isabs(args.out_dir) else args.out_dir
maps = discover_maps()
# Save the complete maps list for the viewer (always, even if downloading specific map)
save_maps_list(maps, out_dir)
if args.map:
# Filter to specific map
target = [m for m in maps if m["slug"] == args.map]
if not target:
print(f"Error: Map '{args.map}' not found. Available slugs:")
for m in maps:
print(f" {m['slug']}")
sys.exit(1)
maps = target
t_start = time.time()
for map_info in maps:
download_map_tiles(map_info, out_dir, args.workers)
elapsed = time.time() - t_start
print(f"\n{'='*60}")
print(f"All downloads complete in {elapsed:.0f}s")
print(f"Output directory: {out_dir}")
if __name__ == "__main__":
main()