/* Tarkov Maps -- every map on one shared canvas. * * The base layer is the overall satellite map, rotated so north is up. Every * detail map is scaled and positioned onto it, so zooming into Customs on the * world map lands you in the full-resolution re3mr Customs map. * * Coordinates: LatLng is (y, x) in *world pixels* at native resolution, where * one world pixel is 1/overallScale of an overall-map pixel. Each map's tiles * are numbered from its own padded cell origin -- see tools/common.py. */ const ZOOM_HEADROOM = 1; // how far past a layer's native detail we allow const ZOOM_SNAP = 0.25; const BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='; /* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it * takes level 2 and stretches it 1.19x; on a 1.5x display that compounds to a * visibly soft 1.78x upscale. Halving a tile's CSS size and asking for one * level deeper makes us downscale a denser level instead. */ const DENSITY_BOOST = (window.devicePixelRatio > 1.05 || ZOOM_SNAP < 1) ? 1 : 0; const OffsetTileLayer = L.TileLayer.extend({ getTileUrl(coords) { const o = this.options; const perCell = (o.baseTileSize * 2 ** coords.z) / o.tileSize; // ?v= busts the week-long immutable cache when a map is re-tiled; the same // URL would otherwise serve a previous build's imagery. return L.Util.template(this._url, { z: coords.z + o.zoomOffset, x: coords.x - o.cell[0] * perCell, y: coords.y - o.cell[1] * perCell, }) + (o.version ? `?v=${o.version}` : ''); }, }); const rectOf = (m) => L.latLngBounds( [m.origin[1], m.origin[0]], [m.origin[1] + m.size[1], m.origin[0] + m.size[0]], ); const trimPointsOf = (m) => ( Array.isArray(m.trim?.points) && m.trim.points.length >= 3 ? m.trim.points : null ); // The aligned raster keeps its original rectangle, but navigation should use // the portion the trim polygon says is actually playable/visible. const viewRectOf = (m) => { const points = trimPointsOf(m); if (!points) return rectOf(m); const xs = points.map(([x]) => x); const ys = points.map(([, y]) => y); return L.latLngBounds( [m.origin[1] + Math.min(...ys) * m.size[1], m.origin[0] + Math.min(...xs) * m.size[0]], [m.origin[1] + Math.max(...ys) * m.size[1], m.origin[0] + Math.max(...xs) * m.size[0]], ); }; const viewContains = (m, latlng) => { const points = trimPointsOf(m); if (!points) return rectOf(m).contains(latlng); const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; let inside = false; for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) { const [xi, yi] = points[i]; const [xj, yj] = points[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) { inside = !inside; } } return inside; }; 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; const [z, y, x] = p.map(Number); return [z, y, x].every(Number.isFinite) ? { z, y, x } : null; } async function main() { const [world, markerData] = await Promise.all([ fetch('data/world.json', { cache: 'no-cache' }).then((r) => { if (!r.ok) throw new Error(`world.json: ${r.status}`); return r.json(); }), fetch('data/markers.json', { cache: 'no-cache' }) .then((r) => (r.ok ? r.json() : { markers: [] })) .catch(() => ({ markers: [] })), ]); if (!world.maps.length) throw new Error('world.json contains no maps'); const ZMAX = world.maxZoom; const base = world.maps.find((m) => m.base) ?? world.maps[0]; const CRS = L.extend({}, L.CRS.Simple, { transformation: new L.Transformation(1, 0, 1, 0), scale: (z) => 2 ** (z - ZMAX), zoom: (s) => Math.log(s) / Math.LN2 + ZMAX, }); const extent = L.latLngBounds([0, 0], [world.worldSize[1], world.worldSize[0]]); const map = L.map('map', { crs: CRS, minZoom: 0, maxZoom: ZMAX + ZOOM_HEADROOM, zoomSnap: ZOOM_SNAP, zoomDelta: 0.5, wheelPxPerZoomLevel: 90, maxBounds: extent.pad(0.05), maxBoundsViscosity: 0.75, attributionControl: false, }); L.control.attribution({ prefix: false }) .addAttribution(world.attribution) .addTo(map); const boost = DENSITY_BOOST; /* Stacking. Placements are approximate, so map rectangles overlap even when * the real locations don't (Reserve clips Customs, Lighthouse clips * Shoreline). Baseline order puts the finer map on top: sort by * maxNativeZoom, then by smaller footprint. `focus()` then lifts whichever * map you are actually looking at above the rest, so an overlapping * neighbour can never hide the map you came to see. */ const detail = world.maps.filter((m) => !m.base); const stackOrder = [...detail].sort( (a, b) => (a.maxNativeZoom - b.maxNativeZoom) || (b.size[0] * b.size[1] - a.size[0] * a.size[1]), ); const BASE_Z = 1; 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 insideLayers = new Map(); const insidePanes = new Map(); const previewGeometry = new Map(detail.map((m) => [m.id, geometryOf(m)])); const savedTrim = (m) => ({ points: Array.isArray(m.trim?.points) ? m.trim.points.map((p) => [...p]) : [], transparency: Number.isFinite(m.trim?.outsideTransparency) ? m.trim.outsideTransparency : 0.75, }); const paneZ = (id, focused = false) => ( focused ? 600 + TOP_Z * 2 : 300 + baseZ.get(id) * 2 ); let updateMarkerFocus = () => {}; const focus = (id) => { const selected = detail.find((m) => m.id === id); const rootId = selected?.parent ?? selected?.id; const family = rootId ? detail.filter((m) => m.id === rootId || m.parent === rootId) : []; updateMarkerFocus(family.map((m) => m.id)); for (const [mid, pane] of panes) { const familyIndex = family.findIndex((m) => m.id === mid); let z = paneZ(mid); if (familyIndex >= 0) z = 600 + TOP_Z * 2 + familyIndex * 2; // A directly selected child remains the top member of its family. When // the parent is selected, children naturally follow above it. if (selected?.parent && mid === id) z += family.length * 2; pane.style.zIndex = String(z); const inside = insidePanes.get(mid); if (inside) inside.style.zIndex = String(z + 1); } }; const familyViewRect = (m) => { const own = viewRectOf(m); const combined = L.latLngBounds(own.getSouthWest(), own.getNorthEast()); if (!m.parent) { detail.filter((child) => child.parent === m.id) .forEach((child) => combined.extend(viewRectOf(child))); } return combined; }; 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); for (const target of [pane, insidePanes.get(m.id)].filter(Boolean)) { target.style.transformOrigin = `${origin.x}px ${origin.y}px`; target.style.transform = `translate3d(${dx}px, ${dy}px, 0) scale(${sx}, ${sy})`; } }; const updatePreviewTransforms = () => detail.forEach(updatePreviewTransform); const usesPermanentTrim = (m) => !m.base && !!m.trim && !!m.trimmedVersion; const tileUrl = (m, trimmed = false) => ( `${trimmed ? 'tiles-trimmed' : 'tiles'}/${m.id}/{z}/{x}/{y}.webp` ); const tileOptions = (m, paneName, isBase = false, version = m.version) => ({ cell: m.cell, bounds: rectOf(m), pane: isBase ? 'tilePane' : paneName, version, baseTileSize: world.tileSize, tileSize: world.tileSize / 2 ** boost, zoomOffset: boost, minZoom: isBase ? 0 : m.minZoom, maxZoom: ZMAX + ZOOM_HEADROOM, maxNativeZoom: Math.max(0, m.maxNativeZoom - boost), minNativeZoom: 0, noWrap: true, keepBuffer: isBase ? 6 : 2, updateWhenIdle: false, errorTileUrl: BLANK, zIndex: isBase ? BASE_Z : baseZ.get(m.id), className: isBase ? 'tile-base' : undefined, }); const setLayerSource = (m, trimmed) => { const layer = layers.get(m.id); if (!layer) return; const nextKind = trimmed && usesPermanentTrim(m) ? 'trimmed' : 'original'; if (layer._tarkovSource === nextKind) return; layer._tarkovSource = nextKind; layer.options.version = nextKind === 'trimmed' ? m.trimmedVersion : m.version; layer.setUrl(tileUrl(m, nextKind === 'trimmed')); }; const ensureInsideLayer = (m) => { if (insideLayers.has(m.id)) return insideLayers.get(m.id); const paneName = `map-${m.id}-inside`; const pane = map.createPane(paneName); pane.style.zIndex = String(paneZ(m.id) + 1); pane.style.pointerEvents = 'none'; pane.style.display = 'none'; insidePanes.set(m.id, pane); const layer = new OffsetTileLayer( `tiles/${m.id}/{z}/{x}/{y}.webp`, tileOptions(m, paneName), ).addTo(map); insideLayers.set(m.id, layer); updatePreviewTransform(m); return layer; }; const updateTrimClip = (m, points) => { const pane = insidePanes.get(m.id); if (!pane || points.length < 3) return; const projected = points.map(([x, y]) => map.latLngToLayerPoint([ m.origin[1] + y * m.size[1], m.origin[0] + x * m.size[0], ])); pane.style.clipPath = `polygon(${projected.map((p) => `${p.x}px ${p.y}px`).join(',')})`; }; const renderTrim = (m, points, transparency) => { const outside = panes.get(m.id); if (!outside) return; // Editing uses the untouched source plus a live preview. The normal saved // view switches back to the separately rasterized trimmed tile pyramid. setLayerSource(m, false); if (points.length < 3) { outside.style.opacity = '1'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; return; } ensureInsideLayer(m); outside.style.opacity = String(1 - transparency); const inside = insidePanes.get(m.id); inside.style.display = ''; updateTrimClip(m, points); }; const restoreMapAppearance = (m) => { if (!m || m.base) return; panes.get(m.id).style.opacity = '1'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; setLayerSource(m, true); }; 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(paneZ(m.id)); pane.style.pointerEvents = 'none'; panes.set(m.id, pane); } const trimmed = usesPermanentTrim(m); const version = trimmed ? m.trimmedVersion : m.version; const layer = new OffsetTileLayer( tileUrl(m, trimmed), tileOptions(m, paneName, isBase, version), ).addTo(map); layer._tarkovSource = trimmed ? 'trimmed' : 'original'; layers.set(m.id, layer); } // --- semantic PSD markers -------------------------------------------- const markerPane = map.createPane('semantic-markers'); markerPane.style.zIndex = '900'; markerPane.style.pointerEvents = 'none'; const markerLayer = L.layerGroup(); const markerLayersByMap = new Map(); const markerSymbols = { 'extract-pmc': '↗', 'extract-scav': '↗', 'extract-neutral': '↗', 'extract-hidden': '↗', transit: 'T', spawn: 'P', scav: 'S', boss: 'B', cultist: 'C', sniper: '△', cache: '◇', key: 'K', loot: 'L', hazard: '!', quest: '?', location: '•', poi: '•', }; const escapeHTML = (value) => String(value ?? '').replace( /[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]), ); const markerMaps = new Map(world.maps.map((m) => [m.id, m])); for (const marker of markerData.markers ?? []) { const m = markerMaps.get(marker.mapId); if (!m || !Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue; const category = String(marker.category || 'poi').replace(/[^a-z0-9-]/gi, ''); const label = marker.label || category.replaceAll('-', ' '); const icon = L.divIcon({ className: `poi-icon marker-${category}`, iconSize: [18, 18], iconAnchor: [9, 9], html: '`, }); if (!markerLayersByMap.has(m.id)) markerLayersByMap.set(m.id, L.layerGroup()); L.marker([ m.origin[1] + marker.y * m.size[1], m.origin[0] + marker.x * m.size[0], ], { icon, pane: 'semantic-markers', interactive: false, keyboard: false }) .addTo(markerLayersByMap.get(m.id)); } markerLayersByMap.forEach((layer) => markerLayer.addLayer(layer)); updateMarkerFocus = (mapIds) => { const visible = new Set(mapIds); markerLayersByMap.forEach((layer, mapId) => { if (!visible.size || visible.has(mapId)) markerLayer.addLayer(layer); else markerLayer.removeLayer(layer); }); }; const markerButton = document.getElementById('toggle-markers'); let markersVisible = localStorage.getItem('tarkov-markers-visible') !== 'false'; const renderMarkerVisibility = () => { if (markersVisible && !map.hasLayer(markerLayer)) markerLayer.addTo(map); if (!markersVisible && map.hasLayer(markerLayer)) map.removeLayer(markerLayer); markerButton.setAttribute('aria-pressed', String(markersVisible)); markerButton.textContent = `Markers (${markerData.markers?.length ?? 0})`; }; markerButton.addEventListener('click', () => { markersVisible = !markersVisible; localStorage.setItem('tarkov-markers-visible', String(markersVisible)); renderMarkerVisibility(); }); renderMarkerVisibility(); const updateMarkerDensity = () => { map.getContainer().classList.toggle('marker-labels-visible', map.getZoom() >= 6); map.getContainer().classList.toggle('marker-overview', map.getZoom() < 2.5); }; map.on('zoom zoomend', updateMarkerDensity); updateMarkerDensity(); // --- picker ----------------------------------------------------------- const list = document.getElementById('maplist'); const editButton = document.getElementById('edit-placement'); const trimButton = document.getElementById('edit-trim'); 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 trimPanel = document.getElementById('trim-editor'); const trimName = document.getElementById('trim-name'); const trimTransparency = document.getElementById('trim-transparency'); const trimTransparencyValue = document.getElementById('trim-transparency-value'); const trimPointCount = document.getElementById('trim-point-count'); const trimUndo = document.getElementById('trim-undo'); const trimClear = document.getElementById('trim-clear'); const trimSave = document.getElementById('trim-save'); const trimStatus = document.getElementById('trim-status'); const byId = new Map(world.maps.map((m) => [m.id, m])); const editor = { selectedId: null, active: false, marker: null, outline: null, }; const trimEditor = { selectedId: null, active: false, points: [], transparency: 0.75, markers: [], 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); restoreMapAppearance(m); clearEditorLayers(); editor.active = false; editorPanel.hidden = true; editButton.setAttribute('aria-pressed', 'false'); showStatus(''); }; const openEditor = (m) => { if (!m || m.base) return; if (trimEditor.active) closeTrimEditor(); const previous = byId.get(editor.selectedId); if (previous && previous.id !== m.id) { resetPreview(previous); restoreMapAppearance(previous); } clearEditorLayers(); editor.selectedId = m.id; editor.active = true; editorPanel.hidden = false; editButton.disabled = false; editButton.setAttribute('aria-pressed', 'true'); editorName.textContent = m.name; showStatus('Unsaved changes stay in this preview until you save.'); setLayerSource(m, false); 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); panes.get(m.id).style.opacity = '0.5'; const inside = insidePanes.get(m.id); if (inside) inside.style.display = 'none'; focus(m.id); }; const selectTarget = (m) => { const mode = editor.active ? 'placement' : (trimEditor.active ? 'trim' : null); if (editor.active) closeEditor(); if (trimEditor.active) closeTrimEditor(); editor.selectedId = m.base ? null : m.id; trimEditor.selectedId = m.base ? null : m.id; editButton.disabled = !!m.base; trimButton.disabled = !!m.base; buttons.forEach((b) => { b.dataset.selected = String(b.dataset.id === m.id); }); if (!m.base && mode === 'placement') openEditor(m); if (!m.base && mode === 'trim') openTrimEditor(m); }; const roots = detail.filter((m) => !m.parent); const orderedDetail = roots.flatMap((m) => [ m, ...detail.filter((child) => child.parent === m.id), ]); const orderedIds = new Set(orderedDetail.map((m) => m.id)); orderedDetail.push(...detail.filter((m) => !orderedIds.has(m.id))); const targets = [base, ...orderedDetail]; const buttons = targets.map((m) => { const b = document.createElement('button'); b.textContent = m.base ? 'Overview' : m.name; b.dataset.id = m.id; b.dataset.subMap = String(!!m.parent); b.addEventListener('click', () => { selectTarget(m); map.flyToBounds(familyViewRect(m), { padding: [24, 24], duration: 0.7 }); if (window.matchMedia('(max-width: 640px)').matches) { document.getElementById('panel').open = false; } }); list.appendChild(b); return b; }); editButton.setAttribute('aria-pressed', 'false'); trimButton.setAttribute('aria-pressed', 'false'); editButton.addEventListener('click', () => { if (editor.active) closeEditor(); else openEditor(byId.get(editor.selectedId)); }); trimButton.addEventListener('click', () => { if (trimEditor.active) closeTrimEditor(); else openTrimEditor(byId.get(trimEditor.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; } }); // --- playable-area trim editor --------------------------------------- const showTrimStatus = (message, isError = false) => { trimStatus.textContent = message; trimStatus.dataset.error = String(isError); }; const trimLatLngs = (m) => trimEditor.points.map(([x, y]) => L.latLng( m.origin[1] + y * m.size[1], m.origin[0] + x * m.size[0], )); const normalizedPoint = (m, latlng) => { const x = (latlng.lng - m.origin[0]) / m.size[0]; const y = (latlng.lat - m.origin[1]) / m.size[1]; if (x < 0 || x > 1 || y < 0 || y > 1) return null; return [Math.max(0, Math.min(1, x)), Math.max(0, Math.min(1, y))]; }; const updateTrimUI = () => { const count = trimEditor.points.length; trimPointCount.textContent = `${count} point${count === 1 ? '' : 's'}`; trimTransparency.value = String(Math.round(trimEditor.transparency * 100)); trimTransparencyValue.textContent = `${Math.round(trimEditor.transparency * 100)}%`; trimUndo.disabled = count === 0; trimClear.disabled = count === 0; trimSave.disabled = count === 1 || count === 2; }; const clearTrimEditorLayers = () => { trimEditor.markers.forEach((marker) => map.removeLayer(marker)); trimEditor.markers = []; if (trimEditor.outline) map.removeLayer(trimEditor.outline); trimEditor.outline = null; }; const updateTrimShape = (m) => { const latlngs = trimLatLngs(m); if (trimEditor.outline) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline.setLatLngs(shape); } renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); }; const rebuildTrimEditorLayers = (m) => { clearTrimEditorLayers(); const latlngs = trimLatLngs(m); if (latlngs.length) { const shape = latlngs.length >= 3 ? [...latlngs, latlngs[0]] : latlngs; trimEditor.outline = L.polyline(shape, { color: '#ffcf4a', weight: 2, dashArray: '7 6', interactive: false, }).addTo(map); } trimEditor.markers = latlngs.map((latlng, index) => { const marker = L.marker(latlng, { draggable: true, zIndexOffset: 11000, icon: L.divIcon({ className: 'trim-vertex', iconSize: [14, 14] }), }).addTo(map); marker.on('drag', (event) => { const point = normalizedPoint(m, event.target.getLatLng()); if (!point) return; trimEditor.points[index] = point; updateTrimShape(m); }); marker.on('dragend', () => showTrimStatus('Ready to save.')); return marker; }); updateTrimShape(m); }; function closeTrimEditor() { const m = byId.get(trimEditor.selectedId); clearTrimEditorLayers(); trimEditor.active = false; trimPanel.hidden = true; trimButton.setAttribute('aria-pressed', 'false'); restoreMapAppearance(m); showTrimStatus(''); } function openTrimEditor(m) { if (!m || m.base) return; if (editor.active) closeEditor(); clearTrimEditorLayers(); const saved = savedTrim(m); trimEditor.selectedId = m.id; trimEditor.active = true; trimEditor.points = saved.points; trimEditor.transparency = saved.transparency; trimPanel.hidden = false; trimButton.disabled = false; trimButton.setAttribute('aria-pressed', 'true'); trimName.textContent = m.name; setLayerSource(m, false); showTrimStatus(saved.points.length ? 'Drag existing points or click the map to add more.' : 'Add at least three points around the playable area.'); rebuildTrimEditorLayers(m); focus(m.id); } trimTransparency.addEventListener('input', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.transparency = Number(trimTransparency.value) / 100; renderTrim(m, trimEditor.points, trimEditor.transparency); updateTrimUI(); showTrimStatus('Ready to save.'); }); trimUndo.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m || !trimEditor.points.length) return; trimEditor.points.pop(); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); trimClear.addEventListener('click', () => { const m = byId.get(trimEditor.selectedId); if (!m) return; trimEditor.points = []; rebuildTrimEditorLayers(m); showTrimStatus('Trim cleared. Save to restore the full map.'); }); trimSave.addEventListener('click', async () => { const m = byId.get(trimEditor.selectedId); if (!m || (trimEditor.points.length > 0 && trimEditor.points.length < 3)) return; trimSave.disabled = true; showTrimStatus('Saving and rendering a permanent trimmed copy…'); try { const response = await fetch('api/trim', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: m.id, points: trimEditor.points, outsideTransparency: trimEditor.transparency, }), }); 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', ); m.trim = result.trim; m.version = result.map.version; m.trimmedVersion = result.map.trimmedVersion; showTrimStatus('Saved. Loading the permanent trimmed tiles…'); closeTrimEditor(); } catch (error) { showTrimStatus(`Save failed: ${error.message}`, true); } finally { updateTrimUI(); } }); map.on('click', (event) => { if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); const point = m && normalizedPoint(m, event.latlng); if (!m || !point) { showTrimStatus('Click inside the selected map to add a point.', true); return; } trimEditor.points.push(point); rebuildTrimEditorLayers(m); showTrimStatus(trimEditor.points.length >= 3 ? 'Ready to save.' : 'Add at least three points.'); }); const updateAllTrimClips = () => { if (!trimEditor.active) return; const m = byId.get(trimEditor.selectedId); if (m && trimEditor.points.length >= 3) updateTrimClip(m, trimEditor.points); }; const syncUI = () => { const c = map.getCenter(); // Smallest non-base map containing the centre wins -- Dorms beats Customs. const hit = world.maps .filter((m) => !m.base && viewContains(m, c) && map.getZoom() >= m.minZoom) .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(editor.active ? editor.selectedId : (trimEditor.active ? trimEditor.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(); updateAllTrimClips(); }); const h = readHash(); if (h) map.setView([h.y, h.x], h.z); else map.fitBounds(rectOf(base), { padding: [10, 10] }); detail.forEach(restoreMapAppearance); syncUI(); document.getElementById('boot').remove(); window.tarkovMap = map; window.tarkovWorld = world; } main().catch((err) => { document.getElementById('boot').textContent = `Failed to load: ${err.message}`; console.error(err); });