Files
TarkovMaps/web/app.js
T
Claude f997c2c5e2 Render from a denser pyramid level to fix soft tiles
Leaflet chooses its tile level with Math.round(mapZoom), so the default
fit view at zoom 2.25 took level 2 and stretched it 1.19x. With a
devicePixelRatio of 1.5 that compounded to a 1.78x upscale of every
source pixel.

DENSITY_BOOST halves a tile's CSS size and adds a matching zoomOffset, so
Leaflet downscales a denser level instead of upscaling a coarser one. The
per-cell tile offset is now derived from baseTileSize rather than
assuming 2**z, so the world-grid translation stays exact under the boost.

Source pixels per device pixel at DPR 1.5, higher being sharper:

  view zoom 0-4   0.56 -> 1.33
  view zoom 5     0.67 (unchanged; this is the 1:1 source level)

Costs ~4x the tiles in view, ~17 KB each, cached for a week.

z5 is a genuine ceiling: the embedded terrain smart object is a PSB of
exactly 7832x3720 placed 1:1, so no further source detail exists.

Verified zoom 0-7: zero broken tiles.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-08 02:36:17 -07:00

187 lines
6.4 KiB
JavaScript

/* Tarkov Maps -- every map on one shared canvas.
*
* Coordinates: LatLng is (y, x) in *world pixels* at native resolution.
* A map placed in grid cell (gx, gy) occupies the world rectangle
* [gx*cellSize, gy*cellSize] .. [+width, +height]. Because cellSize is
* tileSize * 2**maxZoom, the tile-index shift for a cell is exactly
* cell * 2**z at every zoom -- so each map keeps its own locally numbered
* pyramid and we translate on the way out in getTileUrl().
*/
const ZOOM_HEADROOM = 2; // how far past 1:1 the user may zoom
const ZOOM_SNAP = 0.25;
const BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
/* Pixel density.
*
* Leaflet picks its tile level with Math.round(mapZoom), so at zoom 2.25 it
* takes level 2 and stretches it 1.19x. Multiply that by a devicePixelRatio
* of 1.5 and each source pixel covers ~1.8 device pixels -- visibly soft.
*
* DENSITY_BOOST fixes it by halving the CSS size of a tile and asking for one
* level deeper, so we downscale a denser level instead of upscaling a coarser
* one. Costs ~4x the tiles in view, which at ~17 KB each is a fair trade.
*
* Worth it whenever the screen is not 1:1, or whenever fractional zoom can
* land us between levels. Both are true almost everywhere.
*/
const DENSITY_BOOST =
(window.devicePixelRatio > 1.05 || ZOOM_SNAP < 1) ? 1 : 0;
const OffsetTileLayer = L.TileLayer.extend({
getTileUrl(coords) {
// Tiles are numbered from each map's own top-left corner, so shift world
// tile coordinates into the map's local grid. A grid cell spans
// baseTileSize * 2**z pixels at this level; divided by the layer's own
// tile size that is always a whole number of tiles, boost or no boost.
const o = this.options;
const perCell = (o.baseTileSize * 2 ** coords.z) / o.tileSize;
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,
});
},
});
const rectOf = (m) => L.latLngBounds(
[m.origin[1], m.origin[0]],
[m.origin[1] + m.size[1], m.origin[0] + m.size[0]],
);
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;
// CRS where one LatLng unit == one source pixel at zoom ZMAX, y pointing
// down so world coordinates read the same way as image coordinates.
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 = world.maps.reduce(
(acc, m) => (acc ? acc.extend(rectOf(m)) : rectOf(m)), null,
);
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.08),
maxBoundsViscosity: 0.75,
attributionControl: false,
});
L.control.attribution({ prefix: false })
.addAttribution(world.attribution)
.addTo(map);
const UNDERLAY_Z = Math.min(world.underlayZoom ?? 2, ZMAX);
// With the boost on, a level-N request is served by the level-(N+1) files,
// so the deepest level we may ask Leaflet for is one shallower.
const boost = Math.min(DENSITY_BOOST, ZMAX, UNDERLAY_Z);
for (const m of world.maps) {
const url = `tiles/${m.id}/{z}/{x}/{y}.webp`;
const common = {
cell: m.cell,
bounds: rectOf(m),
baseTileSize: world.tileSize,
tileSize: world.tileSize / 2 ** boost,
zoomOffset: boost,
minZoom: 0,
maxZoom: ZMAX + ZOOM_HEADROOM,
noWrap: true,
errorTileUrl: BLANK,
};
// Backdrop. Pinning min and max native zoom to the same low level makes
// Leaflet serve that level at every view zoom, scaled to fit -- the whole
// world is a handful of tiles, so it lands almost immediately and then
// stays put. Detail tiles draw over it, and any gap between them shows
// blurry map instead of the page background.
new OffsetTileLayer(url, {
...common,
minNativeZoom: UNDERLAY_Z - boost,
maxNativeZoom: UNDERLAY_Z - boost,
keepBuffer: 8 * 2 ** boost,
updateWhenIdle: false,
updateWhenZooming: false,
zIndex: 1,
className: 'tile-underlay',
}).addTo(map);
new OffsetTileLayer(url, {
...common,
maxNativeZoom: ZMAX - boost,
// Small on purpose: boosted tiles are half-size, so a wide buffer costs
// 4x the requests, and the underlay already covers anything a pan
// outruns.
keepBuffer: 2,
updateWhenIdle: false,
zIndex: 2,
}).addTo(map);
}
// --- picker -----------------------------------------------------------
const list = document.getElementById('maplist');
const buttons = world.maps.map((m) => {
const b = document.createElement('button');
b.textContent = m.name;
b.dataset.id = m.id;
b.addEventListener('click', () => {
map.flyToBounds(rectOf(m), { padding: [20, 20], duration: 0.6 });
if (window.matchMedia('(max-width: 640px)').matches) {
document.getElementById('panel').open = false;
}
});
list.appendChild(b);
return b;
});
const syncUI = () => {
const c = map.getCenter();
const active = world.maps.find((m) => rectOf(m).contains(c));
buttons.forEach((b) => b.setAttribute('aria-current', String(active?.id === b.dataset.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);
// --- initial view -----------------------------------------------------
const h = readHash();
if (h) map.setView([h.y, h.x], h.z);
else map.fitBounds(rectOf(world.maps[0]), { padding: [20, 20] });
syncUI();
document.getElementById('boot').remove();
window.tarkovMap = map; // handy from the console when checking a new map
window.tarkovWorld = world;
}
main().catch((err) => {
document.getElementById('boot').textContent = `Failed to load: ${err.message}`;
console.error(err);
});