/* 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 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 = await fetch('data/world.json', { cache: 'no-cache' }).then((r) => { if (!r.ok) throw new Error(`world.json: ${r.status}`); return r.json(); }); 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 previewGeometry = new Map(detail.map((m) => [m.id, geometryOf(m)])); const focus = (id) => { for (const [mid, pane] of panes) { if (mid === base.id) continue; 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, 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, }).addTo(map); layers.set(m.id, layer); } // --- 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; } }); list.appendChild(b); 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. const hit = world.maps .filter((m) => !m.base && rectOf(m).contains(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 : 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); else map.fitBounds(rectOf(base), { padding: [10, 10] }); 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); });