aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/assets/map.js (34585B)


      1 "use strict";
      2 
      3 class AOMap {
      4     constructor(element) {
      5         this.element = element;
      6         this.canvas = element.querySelector("canvas");
      7         this.context = this.canvas.getContext("2d");
      8         this.status = element.querySelector("[data-map-status]");
      9         this.location = element.querySelector("[data-map-location]");
     10         this.view = "world";
     11         this.form = element.querySelector("[data-map-teleport]");
     12         this.character = Number(element.dataset.character);
     13         this.publicStatus = element.hasAttribute("data-server-status");
     14         this.path = this.publicStatus ? "status" : "admin";
     15         this.players = [];
     16         this.sources = [];
     17         this.entities = {npcs: [], warps: []};
     18         this.pointers = new Map();
     19         this.tiles = new Map();
     20         this.tileBytes = 0;
     21         this.loadingTiles = 0;
     22         this.clock = 0;
     23         this.selection = null;
     24         this.center = [0, 0];
     25         this.scale = 1;
     26         this.scheduled = false;
     27         this.initialized = false;
     28     }
     29 
     30     async start() {
     31         const response = await fetch(`${this.path}/map-assets/manifest.json`);
     32         if (!response.ok) {
     33             this.status.textContent = this.publicStatus ? "Map imagery is unavailable." : "Map data is missing. Run tools/data/extract_maps.py from the repository root.";
     34             return;
     35         }
     36         this.manifest = await response.json();
     37         this.zones = new Map(this.manifest.zones.map(zone => [zone.id, zone]));
     38         const sourceData = this.element.parentElement.querySelector("[data-item-sources]");
     39         if (sourceData) this.sources = JSON.parse(sourceData.textContent);
     40         const view = this.element.querySelector("[data-map-view]");
     41         if (view) {
     42             for (const zone of this.manifest.zones.filter(zone => !zone.origin).sort((a, b) => a.name.localeCompare(b.name))) {
     43                 const option = document.createElement("option");
     44                 option.value = zone.id;
     45                 option.textContent = `${zone.name} (${zone.id})`;
     46                 view.append(option);
     47             }
     48         }
     49         const find = this.element.querySelector("[data-map-find]");
     50         if (find) {
     51             for (const zone of this.manifest.zones.filter(zone => zone.origin).sort((a, b) => a.name.localeCompare(b.name))) {
     52                 const option = document.createElement("option");
     53                 option.value = zone.id;
     54                 option.textContent = `${zone.name} (${zone.id})`;
     55                 find.append(option);
     56             }
     57             find.addEventListener("change", () => {
     58                 if (find.value) this.focusZone(this.zones.get(Number(find.value)));
     59             });
     60         }
     61         if (view) {
     62             view.addEventListener("change", () => {
     63                 this.view = view.value;
     64                 find.value = "";
     65                 this.fit(this.bounds());
     66             });
     67         }
     68         if (this.form) {
     69             this.form.elements.playfield.addEventListener("change", () => {
     70                 const zone = this.zones.get(Number(this.form.elements.playfield.value));
     71                 this.form.querySelector("button").disabled = !zone;
     72                 if (zone) this.selectDestination(zone, [this.pendingPoint[0] - zone.origin[0], this.pendingPoint[1] - zone.origin[1]]);
     73             });
     74         }
     75         this.element.querySelector("[data-map-center]")?.addEventListener("click", () => this.centerPlayer());
     76         for (const button of this.element.querySelectorAll("[data-map-zoom]")) {
     77             button.addEventListener("click", () => this.zoom(1.5 ** Number(button.dataset.mapZoom), this.width / 2, this.height / 2));
     78         }
     79         this.canvas.addEventListener("wheel", event => {
     80             event.preventDefault();
     81             const point = this.pointer(event);
     82             this.zoom(Math.exp(-event.deltaY * 0.0015), ...point);
     83         }, {passive: false});
     84         this.canvas.addEventListener("pointerdown", event => this.pointerDown(event));
     85         this.canvas.addEventListener("pointermove", event => this.pointerMove(event));
     86         this.canvas.addEventListener("pointerup", event => this.pointerEnd(event));
     87         this.canvas.addEventListener("pointercancel", event => this.pointerEnd(event, true));
     88         for (const toggle of this.element.querySelectorAll("input[type=checkbox]")) {
     89             toggle.addEventListener("change", () => {
     90                 this.renderSoon();
     91             });
     92         }
     93         new ResizeObserver(() => this.resize()).observe(this.canvas);
     94         this.resize();
     95         this.fit(this.bounds());
     96         if (sourceData) {
     97             for (const link of this.element.parentElement.querySelectorAll("[data-map-source]")) {
     98                 link.addEventListener("click", event => {
     99                     event.preventDefault();
    100                     this.focusSource(this.sources[Number(link.dataset.mapSource)]);
    101                     this.canvas.scrollIntoView({block: "nearest"});
    102                 });
    103             }
    104             if (this.element.hasAttribute("data-map-overview")) this.focusSources();
    105             else this.focusSource(this.sources[0]);
    106             return;
    107         }
    108         const query = new URLSearchParams(window.location.search);
    109         if (!this.publicStatus && query.has("playfield") && query.has("x") && query.has("z")) {
    110             this.sources = [{playfield: Number(query.get("playfield")), position: [Number(query.get("x")), 0, Number(query.get("z"))], name: "Source location"}];
    111             this.focusSource(this.sources[0]);
    112         }
    113         await this.poll();
    114     }
    115 
    116     pointerDown(event) {
    117         if (event.button !== 0) return;
    118         const point = this.pointer(event);
    119         this.pointers.set(event.pointerId, point);
    120         this.drag = {point, center: [...this.center], moved: this.pointers.size > 1};
    121         this.canvas.setPointerCapture(event.pointerId);
    122     }
    123 
    124     pointerMove(event) {
    125         if (!this.pointers.has(event.pointerId)) return;
    126         const before = [...this.pointers.values()];
    127         const point = this.pointer(event);
    128         this.pointers.set(event.pointerId, point);
    129         const after = [...this.pointers.values()];
    130         if (after.length === 2) {
    131             // Keep the world position beneath the midpoint while pinching and panning.
    132             const midpoint = points => [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
    133             const distance = points => Math.hypot(points[0][0] - points[1][0], points[0][1] - points[1][1]);
    134             const oldMid = midpoint(before), newMid = midpoint(after);
    135             this.zoom(distance(after) / Math.max(1, distance(before)), ...oldMid);
    136             this.center[0] -= (newMid[0] - oldMid[0]) / this.scale;
    137             this.center[1] += (newMid[1] - oldMid[1]) / this.scale;
    138             this.drag.moved = true;
    139         } else if (after.length === 1 && this.drag) {
    140             const dx = point[0] - this.drag.point[0], dy = point[1] - this.drag.point[1];
    141             if (Math.hypot(dx, dy) > 4) this.drag.moved = true;
    142             if (this.drag.moved) this.center = [this.drag.center[0] - dx / this.scale, this.drag.center[1] + dy / this.scale];
    143         }
    144         this.renderSoon();
    145     }
    146 
    147     pointerEnd(event, cancelled = false) {
    148         if (!this.pointers.has(event.pointerId)) return;
    149         const clicked = !cancelled && this.pointers.size === 1 && !this.drag.moved;
    150         this.pointers.delete(event.pointerId);
    151         if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId);
    152         this.drag = this.pointers.size ? {point: [...this.pointers.values()][0], center: [...this.center], moved: true} : null;
    153         if (clicked) this.pick(...this.pointer(event));
    154     }
    155 
    156     detailVisible(kind) {
    157         const span = kind === "npcs" ? 2000 : 6000;
    158         return this.scale >= (kind === "npcs" ? 1.2 : 0.3) && this.width / this.scale <= span && this.height / this.scale <= span;
    159     }
    160 
    161     entityQuery() {
    162         const [left, top] = this.toWorld(0, 0), [right, bottom] = this.toWorld(this.width, this.height);
    163         const npcs = this.element.querySelector("[data-map-npcs]").checked && this.detailVisible("npcs");
    164         return new URLSearchParams({view: this.view, left, bottom, right, top,
    165             npcs: npcs ? "1" : "0", warps: this.element.querySelector("[data-map-warps]").checked && this.detailVisible() ? "1" : "0"}).toString();
    166     }
    167 
    168     resize() {
    169         this.width = this.canvas.clientWidth;
    170         this.height = this.canvas.clientHeight;
    171         const ratio = Math.min(window.devicePixelRatio || 1, 2);
    172         this.canvas.width = Math.round(this.width * ratio);
    173         this.canvas.height = Math.round(this.height * ratio);
    174         this.context.setTransform(ratio, 0, 0, ratio, 0, 0);
    175         this.renderSoon();
    176     }
    177 
    178     pointer(event) {
    179         const rect = this.canvas.getBoundingClientRect();
    180         return [event.clientX - rect.left, event.clientY - rect.top];
    181     }
    182 
    183     bounds() {
    184         if (this.view === "world") return this.manifest.planet.bounds;
    185         const zone = this.zones.get(Number(this.view));
    186         return [0, 0, zone.width, zone.height];
    187     }
    188 
    189     fit(bounds) {
    190         this.entities = {npcs: [], warps: []};
    191         const [left, bottom, right, top] = bounds;
    192         this.center = [(left + right) / 2, (bottom + top) / 2];
    193         this.scale = Math.min(this.width / (right - left), this.height / (top - bottom)) * 0.9;
    194         this.selection = null;
    195         if (this.location) this.location.textContent = "";
    196         if (this.form) {
    197             this.form.querySelector("button").disabled = true;
    198             this.form.querySelector("[data-map-zone-choice]").hidden = true;
    199         }
    200         this.renderSoon();
    201     }
    202 
    203     focusZone(zone) {
    204         // Focus the outdoor boundary while keeping the shared world coordinates.
    205         this.view = "world";
    206         const boundary = zone.boundary || [[0, 0], [zone.width, zone.height]];
    207         this.fit([zone.origin[0] + Math.min(...boundary.map(point => point[0])),
    208             zone.origin[1] + Math.min(...boundary.map(point => point[1])),
    209             zone.origin[0] + Math.max(...boundary.map(point => point[0])),
    210             zone.origin[1] + Math.max(...boundary.map(point => point[1]))]);
    211     }
    212 
    213     focusSources() {
    214         this.view = "world";
    215         const points = this.sources.map(source => this.playerPoint(source)).filter(point => point);
    216         if (!points.length) return;
    217         const xs = points.map(point => point[0]), zs = points.map(point => point[1]);
    218         this.fit([Math.min(...xs) - 50, Math.min(...zs) - 50, Math.max(...xs) + 50, Math.max(...zs) + 50]);
    219         this.scale = Math.min(this.scale, 1);
    220         this.initialized = true;
    221     }
    222 
    223     focusSource(source) {
    224         const zone = this.zones.get(source.playfield);
    225         const view = this.element.querySelector("[data-map-view]");
    226         // Unmapped interiors still have local coordinates, but no known map bounds.
    227         if (!zone && view && !view.querySelector(`option[value='${source.playfield}']`)) {
    228             const option = document.createElement("option");
    229             option.value = source.playfield;
    230             option.textContent = `Playfield ${source.playfield} (no map imagery)`;
    231             option.disabled = true;
    232             view.append(option);
    233         }
    234         this.initialized = true;
    235         this.view = zone?.origin ? "world" : String(source.playfield);
    236         this.center = this.playerPoint(source);
    237         this.scale = 1;
    238         this.location.textContent = `${source.name}: ${zone ? `${zone.name} (${zone.id})` : `playfield ${source.playfield}`}, X ${source.position[0].toFixed(1)}, Z ${source.position[2].toFixed(1)}.`;
    239         this.renderSoon();
    240     }
    241 
    242     centerPlayer() {
    243         if (this.sources.length) {
    244             const sourceChoice = this.element.parentElement.querySelector("[data-map-source]");
    245             this.focusSource(this.sources[Number(sourceChoice?.value || 0)]);
    246             return;
    247         }
    248         this.element.querySelector("[data-map-find]").value = "";
    249         const player = this.players.find(player => player.id === this.character);
    250         const zone = player && this.zones.get(player.playfield);
    251         if (zone && !zone.origin && zone.levels.length) {
    252             this.view = player.playfield;
    253             this.fit(this.bounds());
    254             this.center = [player.position[0], player.position[2]];
    255             this.scale = Math.max(this.scale, 0.75);
    256         } else {
    257             this.view = "world";
    258             this.fit(this.bounds());
    259             if (player) {
    260                 const point = this.playerPoint(player);
    261                 if (point) {
    262                     this.center = point;
    263                     this.scale = 0.75;
    264                 }
    265             }
    266         }
    267         this.renderSoon();
    268     }
    269 
    270     zoom(factor, x, y) {
    271         const before = this.toWorld(x, y);
    272         this.scale = Math.max(0.005, Math.min(8, this.scale * factor));
    273         this.center = [before[0] - (x - this.width / 2) / this.scale, before[1] + (y - this.height / 2) / this.scale];
    274         clearTimeout(this.loadTimer);
    275         this.loadTimer = setTimeout(() => {
    276             this.loadTimer = null;
    277             this.renderSoon();
    278         }, 120);
    279         this.renderSoon();
    280     }
    281 
    282     toWorld(x, y) {
    283         return [this.center[0] + (x - this.width / 2) / this.scale, this.center[1] - (y - this.height / 2) / this.scale];
    284     }
    285 
    286     toScreen(x, z) {
    287         return [(x - this.center[0]) * this.scale + this.width / 2, (this.center[1] - z) * this.scale + this.height / 2];
    288     }
    289 
    290     contains(zone, [x, z]) {
    291         if (x < 0 || z < 0 || x > zone.width || z > zone.height) return false;
    292         if (!zone.boundary) return true;
    293 
    294         // Count edge crossings; points directly on an edge belong to the polygon.
    295         let inside = false;
    296         for (let i = 0, j = zone.boundary.length - 1; i < zone.boundary.length; j = i++) {
    297             const [ax, az] = zone.boundary[j];
    298             const [bx, bz] = zone.boundary[i];
    299             if ((x - ax) * (bz - az) === (z - az) * (bx - ax) &&
    300                 x >= Math.min(ax, bx) && x <= Math.max(ax, bx) &&
    301                 z >= Math.min(az, bz) && z <= Math.max(az, bz)) return true;
    302             if ((az > z) !== (bz > z) && x < ax + (z - az) * (bx - ax) / (bz - az)) inside = !inside;
    303         }
    304         return inside;
    305     }
    306 
    307     boundaryPath(zone, origin) {
    308         const path = new Path2D();
    309         for (const [index, point] of zone.boundary.entries()) {
    310             const screen = this.toScreen(origin[0] + point[0], origin[1] + point[1]);
    311             if (index === 0) path.moveTo(...screen);
    312             else path.lineTo(...screen);
    313         }
    314         path.closePath();
    315         return path;
    316     }
    317 
    318     playerPoint(player) {
    319         if (this.view !== "world") {
    320             if (player.playfield === Number(this.view)) return [player.position[0], player.position[2]];
    321             return null;
    322         }
    323         const current = this.zones.get(player.playfield);
    324         const placement = current && current.origin ? player : (player.entrance || player);
    325         const zone = this.zones.get(placement.playfield);
    326         if (!zone || !zone.origin) return null;
    327         return [zone.origin[0] + placement.position[0], zone.origin[1] + placement.position[2]];
    328     }
    329 
    330     async poll() {
    331         try {
    332             if (!document.hidden) {
    333                 const offline = this.element.querySelector("[data-map-offline]")?.checked;
    334                 const feed = this.publicStatus ? "status/map-players" : `admin/map-players?offline=${offline ? 1 : 0}&character=${this.character}`;
    335                 const response = await fetch(feed, {cache: "no-store"});
    336                 if (!response.ok) throw new Error(`Player feed returned HTTP ${response.status}`);
    337                 this.players = (await response.json()).players;
    338                 if (this.publicStatus) this.renderRoster();
    339                 if (!this.initialized) {
    340                     this.initialized = true;
    341                     this.centerPlayer();
    342                 }
    343                 if (!this.publicStatus) {
    344                     const query = this.entityQuery();
    345                     const entities = await fetch(`admin/map-entities?${query}`, {cache: "no-store"});
    346                     if (!entities.ok) throw new Error(`Map feed returned HTTP ${entities.status}`);
    347                     const data = await entities.json();
    348                     if (query === this.entityQuery()) this.entities = data;
    349                 }
    350                 this.renderSoon();
    351             }
    352         } catch (error) {
    353             this.status.textContent = `Cannot refresh player positions: ${error.message}`;
    354         } finally {
    355             setTimeout(() => this.poll(), this.publicStatus ? 5000 : 1000);
    356         }
    357     }
    358 
    359     renderRoster() {
    360         this.element.querySelector("[data-status-total]").textContent = `${this.players.length} ${this.players.length === 1 ? "player" : "players"} online`;
    361         const roster = this.element.querySelector("[data-status-roster]");
    362         const list = document.createElement("ul");
    363         for (const player of [...this.players].sort((a, b) => a.name.localeCompare(b.name))) {
    364             const item = document.createElement("li");
    365             const button = document.createElement("button");
    366             button.textContent = `${player.name} (${player.zone})`;
    367             button.disabled = !this.playerPoint(player);
    368             button.addEventListener("click", () => this.focusStatusPlayer(player));
    369             item.append(button);
    370             if (button.disabled) {
    371                 const note = document.createElement("small");
    372                 note.textContent = "Map location unavailable";
    373                 item.append(note);
    374             }
    375             list.append(item);
    376         }
    377         roster.replaceChildren(list);
    378         if (!this.players.length) roster.textContent = "No players are connected right now.";
    379     }
    380 
    381     focusStatusPlayer(player) {
    382         this.center = this.playerPoint(player);
    383         this.scale = 0.75;
    384         this.canvas.scrollIntoView({block: "nearest"});
    385         this.renderSoon();
    386     }
    387 
    388     tile(path) {
    389         let tile = this.tiles.get(path);
    390         if (!tile) {
    391             tile = {bitmap: null, used: 0, failed: false, loading: false};
    392             this.tiles.set(path, tile);
    393         }
    394         tile.used = ++this.clock;
    395         this.visible.add(path);
    396         return tile.bitmap;
    397     }
    398 
    399     loadTiles() {
    400         // Skip intermediate zoom levels and load only the latest visible view.
    401         if (this.loadTimer) return;
    402         for (const path of this.visible) {
    403             if (this.loadingTiles >= 6) break;
    404             const tile = this.tiles.get(path);
    405             if (tile.bitmap || tile.failed || tile.loading) continue;
    406             tile.loading = true;
    407             this.loadingTiles++;
    408             fetch(`${this.path}/map-assets/${path}`, {cache: "force-cache"}).then(response => {
    409                 if (!response.ok) throw new Error(`HTTP ${response.status}`);
    410                 return response.blob();
    411             }).then(blob => createImageBitmap(blob)).then(bitmap => {
    412                 tile.bitmap = bitmap;
    413                 this.tileBytes += bitmap.width * bitmap.height * 4;
    414             }).catch(() => {
    415                 tile.failed = true;
    416             }).finally(() => {
    417                 tile.loading = false;
    418                 this.loadingTiles--;
    419                 this.renderSoon();
    420             });
    421         }
    422     }
    423 
    424     layer(levels, bounds, boundary) {
    425         if (!levels || !levels.length) return;
    426         // Choose the nearest sufficient resolution and request only visible tiles.
    427         const level = levels.find(level => (level.rect[2] - level.rect[0]) / (bounds[2] - bounds[0]) >= this.scale) || levels[levels.length - 1];
    428         const [left, top, right, bottom] = level.rect;
    429         const tileWidth = level.tile_size / (right - left) * (bounds[2] - bounds[0]);
    430         const tileHeight = level.tile_size / (bottom - top) * (bounds[3] - bounds[1]);
    431         const imageLeft = bounds[0] - left / level.tile_size * tileWidth;
    432         const imageTop = bounds[3] + top / level.tile_size * tileHeight;
    433         let viewportLeft = this.center[0] - this.width / this.scale / 2;
    434         let viewportRight = this.center[0] + this.width / this.scale / 2;
    435         let viewportBottom = this.center[1] - this.height / this.scale / 2;
    436         let viewportTop = this.center[1] + this.height / this.scale / 2;
    437         // Clipping the canvas does not stop requests for unused terrain margins.
    438         if (boundary) {
    439             viewportLeft = Math.max(viewportLeft, bounds[0] + Math.min(...boundary.map(point => point[0])));
    440             viewportRight = Math.min(viewportRight, bounds[0] + Math.max(...boundary.map(point => point[0])));
    441             viewportBottom = Math.max(viewportBottom, bounds[1] + Math.min(...boundary.map(point => point[1])));
    442             viewportTop = Math.min(viewportTop, bounds[1] + Math.max(...boundary.map(point => point[1])));
    443         }
    444         if (viewportLeft >= viewportRight || viewportBottom >= viewportTop) return;
    445         for (let column = Math.max(0, Math.floor((viewportLeft - imageLeft) / tileWidth)); column < Math.min(level.columns, Math.ceil((viewportRight - imageLeft) / tileWidth)); column++) {
    446             for (let row = Math.max(0, Math.floor((imageTop - viewportTop) / tileHeight)); row < Math.min(level.rows, Math.ceil((imageTop - viewportBottom) / tileHeight)); row++) {
    447                 const index = level.order === "column" ? column * level.rows + row : row * level.columns + column;
    448                 const bitmap = this.tile(level.tiles[index]);
    449                 if (!bitmap) continue;
    450                 const [x, y] = this.toScreen(imageLeft + column * tileWidth, imageTop - row * tileHeight);
    451                 const width = Math.min(level.tile_size, level.width - column * level.tile_size);
    452                 const height = Math.min(level.tile_size, level.height - row * level.tile_size);
    453                 this.context.drawImage(bitmap, 0, 0, width, height, x, y, width / level.tile_size * tileWidth * this.scale, height / level.tile_size * tileHeight * this.scale);
    454             }
    455         }
    456     }
    457 
    458     pick(x, y) {
    459         for (const source of this.sources) {
    460             const point = this.playerPoint(source);
    461             if (!point) continue;
    462             const screen = this.toScreen(...point);
    463             if (Math.hypot(x - screen[0], y - screen[1]) < 10) {
    464                 this.location.textContent = `${source.name}: playfield ${source.playfield}, X ${source.position[0].toFixed(1)}, Z ${source.position[2].toFixed(1)}.`;
    465                 return;
    466             }
    467         }
    468         for (const marker of this.entities.warps) {
    469             if (!this.detailVisible() || !this.element.querySelector("[data-map-warps]").checked) break;
    470             const screen = this.toScreen(...marker.point);
    471             if (Math.hypot(x - screen[0], y - screen[1]) < 14) {
    472                 this.location.textContent = `${marker.name}: ${marker.destination}`;
    473                 return;
    474             }
    475         }
    476         // Public markers focus the map; admin markers open the editor.
    477         for (const player of this.players) {
    478             if (!player.connected && player.id !== this.character && !this.element.querySelector("[data-map-offline]")?.checked) continue;
    479             const point = this.playerPoint(player);
    480             if (!point) continue;
    481             const screen = this.toScreen(...point);
    482             if (Math.hypot(x - screen[0], y - screen[1]) < 9 && player.id !== this.character) {
    483                 if (this.publicStatus) {
    484                     this.focusStatusPlayer(player);
    485                 } else {
    486                     window.location.href = new URL(`admin/players/${player.id}`, document.baseURI);
    487                 }
    488                 return;
    489             }
    490         }
    491         if (!this.form) return;
    492         const point = this.toWorld(x, y);
    493         let zone;
    494         if (this.view === "world") {
    495             const candidates = this.manifest.zones.filter(zone => zone.origin && this.contains(zone, [point[0] - zone.origin[0], point[1] - zone.origin[1]]));
    496             if (this.form) {
    497                 const select = this.form.elements.playfield;
    498                 select.replaceChildren();
    499                 if (candidates.length > 1) select.add(new Option("Choose destination playfield", ""));
    500                 for (const candidate of candidates) select.add(new Option(`${candidate.name} (${candidate.id})`, candidate.id));
    501                 this.form.querySelector("[data-map-zone-choice]").hidden = candidates.length < 2;
    502             }
    503             if (candidates.length !== 1) {
    504                 this.location.textContent = candidates.length ? `Overlapping playfields: ${candidates.map(zone => zone.name).join(", ")}.${this.form ? " Choose the destination playfield." : ""}` : "No mapped outdoor playfield at this location.";
    505                 if (this.form) this.form.querySelector("button").disabled = true;
    506                 this.pendingPoint = point;
    507                 this.selection = null;
    508                 this.renderSoon();
    509                 return;
    510             }
    511             zone = candidates[0];
    512             point[0] -= zone.origin[0];
    513             point[1] -= zone.origin[1];
    514         } else {
    515             zone = this.zones.get(Number(this.view));
    516             if (!zone) return;
    517             if (this.form) this.form.elements.playfield.replaceChildren(new Option(zone.name, zone.id));
    518         }
    519         if (!this.contains(zone, point)) {
    520             this.location.textContent = "Outside this playfield's mapped boundary.";
    521             this.selection = null;
    522             if (this.form) this.form.querySelector("button").disabled = true;
    523             this.renderSoon();
    524             return;
    525         }
    526         this.selectDestination(zone, point);
    527     }
    528 
    529     selectDestination(zone, point) {
    530         this.selection = {zone, point};
    531         this.location.textContent = `${zone.name} (${zone.id}): X ${point[0].toFixed(2)}, Z ${point[1].toFixed(2)}.`;
    532         if (this.form) {
    533             this.form.elements.playfield.value = zone.id;
    534             this.form.elements.x.value = point[0].toFixed(3);
    535             this.form.elements.z.value = point[1].toFixed(3);
    536             this.form.querySelector("button").disabled = false;
    537         }
    538         this.renderSoon();
    539     }
    540 
    541     renderSoon() {
    542         if (this.scheduled || !this.manifest) return;
    543         this.scheduled = true;
    544         requestAnimationFrame(() => { this.scheduled = false; this.render(); });
    545     }
    546 
    547     render() {
    548         const view = this.element.querySelector("[data-map-view]");
    549         if (view) view.value = this.view;
    550         const zone = this.zones.get(Number(this.view));
    551         const ctx = this.context;
    552         ctx.fillStyle = "#222";
    553         ctx.fillRect(0, 0, this.width, this.height);
    554         this.visible = new Set();
    555         if (this.view === "world") {
    556             this.layer(this.manifest.planet.levels, this.manifest.planet.bounds);
    557             for (const zone of [...this.manifest.zones].sort((a, b) => b.width * b.height - a.width * a.height)) {
    558                 if (!zone.origin) continue;
    559                 if (Math.max(zone.width, zone.height) * this.scale > 240) {
    560                     ctx.save();
    561                     if (zone.boundary) {
    562                         ctx.clip(this.boundaryPath(zone, zone.origin));
    563                     }
    564                     this.layer(zone.levels, [zone.origin[0], zone.origin[1], zone.origin[0] + zone.width, zone.origin[1] + zone.height], zone.boundary);
    565                     ctx.restore();
    566                 }
    567             }
    568             // Draw borders after all imagery so neighboring overlays cannot hide them.
    569             ctx.strokeStyle = "#fff";
    570             ctx.lineWidth = 1;
    571             for (const zone of this.manifest.zones) {
    572                 if (zone.origin && zone.boundary) ctx.stroke(this.boundaryPath(zone, zone.origin));
    573             }
    574         } else if (zone) {
    575             this.layer(zone.levels, [0, 0, zone.width, zone.height]);
    576             ctx.strokeStyle = "#aaa";
    577             ctx.lineWidth = 1;
    578             if (zone.boundary) ctx.stroke(this.boundaryPath(zone, [0, 0]));
    579             else {
    580                 const [left, top] = this.toScreen(0, zone.height);
    581                 ctx.strokeRect(left, top, zone.width * this.scale, zone.height * this.scale);
    582             }
    583         }
    584 
    585         // Show detailed markers at useful zoom; warp destinations are labelled on tap.
    586         ctx.font = "12px sans-serif";
    587         for (const [kind, color] of [["npcs", "#f4b942"], ["warps", "#bc8cff"]]) {
    588             if (!this.detailVisible(kind) || !this.element.querySelector(`[data-map-${kind}]`)?.checked) continue;
    589             for (const marker of this.entities[kind]) {
    590                 const [x, y] = this.toScreen(...marker.point);
    591                 if (x < 0 || y < 0 || x > this.width || y > this.height) continue;
    592                 ctx.fillStyle = color;
    593                 ctx.strokeStyle = color;
    594                 if (kind === "warps") {
    595                     ctx.strokeRect(x - 5, y - 5, 10, 10);
    596                     if (marker.target && this.scale >= 0.3) {
    597                         const target = this.toScreen(...marker.target);
    598                         ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(...target); ctx.stroke();
    599                         ctx.beginPath(); ctx.arc(...target, 3, 0, Math.PI * 2); ctx.fill();
    600                     }
    601                     if (this.scale >= 0.6) ctx.fillText(marker.destination, x + 9, y - 8);
    602                 } else {
    603                     ctx.beginPath(); ctx.arc(x, y, 3, 0, Math.PI * 2); ctx.fill();
    604                     if (this.scale >= 1.2) ctx.fillText(marker.name, x + 6, y + 4);
    605                 }
    606             }
    607         }
    608 
    609         // Acquisition markers remain visible at every zoom, independently of live NPCs.
    610         for (const source of this.sources) {
    611             const point = this.playerPoint(source);
    612             if (!point) continue;
    613             const [x, y] = this.toScreen(...point);
    614             ctx.fillStyle = source.loot ? "#f4b942" : source.vending ? "#55b8ff" : "#21db87";
    615             ctx.strokeStyle = "#102b20";
    616             ctx.lineWidth = 2;
    617             ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.fill();
    618             if (source.loot && source.vending) {
    619                 ctx.fillStyle = "#55b8ff";
    620                 ctx.beginPath(); ctx.arc(x, y, 6, -Math.PI / 2, Math.PI / 2); ctx.fill();
    621             }
    622             ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.stroke();
    623             if (this.scale >= 0.6) ctx.fillText(source.name, x + 9, y - 9);
    624         }
    625 
    626         // Draw player markers above imagery; offline markers have an empty centre.
    627         ctx.font = "12px sans-serif";
    628         for (const player of this.players) {
    629             if (!player.connected && player.id !== this.character && !this.element.querySelector("[data-map-offline]")?.checked) continue;
    630             const point = this.playerPoint(player);
    631             if (!point) continue;
    632             const occupants = this.publicStatus ? this.players.filter(other => {
    633                 const otherPoint = this.playerPoint(other);
    634                 return otherPoint && otherPoint[0] === point[0] && otherPoint[1] === point[1];
    635             }) : [player];
    636             if (occupants[0] !== player) continue;
    637             const [x, y] = this.toScreen(...point);
    638             if (x < -20 || y < -20 || x > this.width + 20 || y > this.height + 20) continue;
    639             ctx.beginPath();
    640             ctx.arc(x, y, player.id === this.character ? 7 : 5, 0, Math.PI * 2);
    641             ctx.strokeStyle = "#fff";
    642             ctx.lineWidth = 2;
    643             ctx.fillStyle = player.id === this.character ? "#ff4040" : "#00cfff";
    644             if (player.connected) ctx.fill();
    645             ctx.stroke();
    646             const atEntrance = player.entrance && this.view === "world" && !this.zones.get(player.playfield)?.origin;
    647             const names = occupants.map(other => `${other.title ? other.title + " " : ""}${other.name}`).join(", ");
    648             const separate = occupants.some(other => other.playfield !== player.playfield);
    649             const label = `${names}${player.connected ? "" : " (offline)"}${atEntrance ? (separate ? " [separate interiors]" : ` [${player.zone} entrance]`) : ""}`;
    650             ctx.lineWidth = 3;
    651             ctx.strokeStyle = "#000";
    652             ctx.strokeText(label, x + 10, y + 4);
    653             ctx.fillStyle = "#fff";
    654             ctx.fillText(label, x + 10, y + 4);
    655         }
    656         if (this.selection) {
    657             let [x, z] = this.selection.point;
    658             if (this.view === "world") {
    659                 x += this.selection.zone.origin[0];
    660                 z += this.selection.zone.origin[1];
    661             }
    662             const point = this.toScreen(x, z);
    663             ctx.strokeStyle = "#ff0";
    664             ctx.lineWidth = 2;
    665             ctx.beginPath();
    666             ctx.moveTo(point[0] - 8, point[1]); ctx.lineTo(point[0] + 8, point[1]);
    667             ctx.moveTo(point[0], point[1] - 8); ctx.lineTo(point[0], point[1] + 8);
    668             ctx.stroke();
    669         }
    670 
    671         // Retain a bounded decoded-image cache, releasing off-screen bitmaps explicitly.
    672         const unused = [...this.tiles].filter(([path, tile]) => tile.bitmap && !this.visible.has(path)).sort((a, b) => a[1].used - b[1].used);
    673         for (const [path, tile] of unused) {
    674             if (this.tileBytes <= 256 * 1024 * 1024) break;
    675             this.tileBytes -= tile.bitmap.width * tile.bitmap.height * 4;
    676             tile.bitmap.close();
    677             this.tiles.delete(path);
    678         }
    679         this.loadTiles();
    680         const detail = this.view !== "world" && !zone?.levels?.length ? " No extracted imagery for this playfield yet." : "";
    681         const failures = [...this.tiles.values()].filter(tile => tile.failed).length;
    682         this.status.textContent = `${this.sources.length ? "Drag to pan. Pinch or scroll to zoom." : `${this.players.filter(player => player.connected).length} connected players.`} ${this.element.querySelector("[data-map-npcs]")?.checked ? (this.detailVisible("npcs") ? `${this.entities.npcs.length} NPCs in view.` : "Zoom in to see NPCs.") : ""}${this.entities.limited ? " Marker limit reached; zoom in." : ""}${detail}${failures ? ` ${failures} tiles failed to load.` : ""}`;
    683     }
    684 }
    685 
    686 for (const element of document.querySelectorAll("[data-world-map]")) {
    687     new AOMap(element).start().catch(error => {
    688         element.querySelector("[data-map-status]").textContent = `Map failed: ${error.message}`;
    689         console.error(error);
    690     });
    691 }